answer
stringlengths 17
10.2M
|
|---|
package com.unidev.polydata;
import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
/**
* SQLite storage tests
*/
public class SQLiteStorageTest {
@Before
public void setup() {
new File("/tmp/testdb.db").delete();
}
@Test
public void testStorageMigration() throws SQLiteStorageException {
SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
sqLiteStorage.migrateStorage();
}
@Test
public void testMetadataFetching() throws SQLiteStorageException {
SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
sqLiteStorage.migrateStorage();
Optional<Poly> tomato = sqLiteStorage.fetchMetadata("tomato");
assertThat(tomato.isPresent(), is(false));
BasicPoly basicPoly = new BasicPoly();
basicPoly._id("tomato");
basicPoly.put("test_key", "test_value");
sqLiteStorage.persistMetadata("tomato", basicPoly);
Optional<Poly> updatedTomato = sqLiteStorage.fetchMetadata("tomato");
assertThat(updatedTomato.isPresent(), is(true));
Poly tomatoPoly = updatedTomato.get();
assertThat(tomatoPoly._id(), is("tomato"));
assertThat(tomatoPoly.get("test_key"), is("test_value"));
Poly metadataPoly = sqLiteStorage.metadata();
assertThat(metadataPoly, is(nullValue()));
BasicPoly metadataToUpdate = new BasicPoly()._id("meta1");
sqLiteStorage.metadata(metadataToUpdate);
Poly changedMetadata = sqLiteStorage.metadata();
assertThat(changedMetadata, is(notNullValue()));
assertThat(changedMetadata._id(), is("meta1"));
}
@Test
public void testSaveUpdate() throws SQLiteStorageException {
SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
sqLiteStorage.migrateStorage();
BasicPoly basicPoly = BasicPoly.newPoly("potato");
basicPoly.put("value", "tomato");
Poly poly = sqLiteStorage.fetchById("potato");
assertThat(poly, is(nullValue()));
sqLiteStorage.persist(basicPoly);
Poly dbPoly = sqLiteStorage.fetchById("potato");
assertThat(dbPoly, is(notNullValue()));
assertThat(dbPoly.get("value"), is("tomato"));
BasicPoly updatePoly = BasicPoly.newPoly("potato");
updatePoly.put("value", "tomato2");
sqLiteStorage.persist(updatePoly);
Poly updatedPoly = sqLiteStorage.fetchById("potato");
assertThat(updatedPoly, is(notNullValue()));
assertThat(updatedPoly.get("value"), is("tomato2"));
}
@Test
public void testPolyRemoval() throws SQLiteStorageException {
SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
sqLiteStorage.migrateStorage();
boolean missingRemoval = sqLiteStorage.remove("potato");
assertThat(missingRemoval, is(false));
BasicPoly basicPoly = BasicPoly.newPoly("potato");
basicPoly.put("value", "tomato");
sqLiteStorage.persist(basicPoly);
boolean removalResult = sqLiteStorage.remove("potato");
assertThat(removalResult, is(true));
boolean missingRemoval2 = sqLiteStorage.remove("potato");
assertThat(missingRemoval2, is(false));
}
// @Test
// public void testStatementEvaluation() throws SQLiteStorageException, SQLException {
// SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
// sqLiteStorage.setPolyMigrators(Arrays.asList(migrator));
// for(int i = 1;i<=10;i++) {
// BasicPoly basicPoly = BasicPoly.newPoly("record_" + i);
// basicPoly.put("value", "" + new Random().nextLong());
// sqLiteStorage.save("poly", basicPoly);
// try (Connection connection = sqLiteStorage.openDb()) {
// PreparedStatement statement = connection.prepareStatement("SELECT * FROM poly;");
// List<BasicPoly> polyList = sqLiteStorage.evaluateStatement(statement);
// assertThat(polyList, not(nullValue()));
// assertThat(polyList.size(), is(10));
// statement = connection.prepareStatement("SELECT _id FROM poly WHERE _id = 'record_3' ");
// polyList = sqLiteStorage.evaluateStatement(statement);
// assertThat(polyList, not(nullValue()));
// assertThat(polyList.size(), is(1));
// BasicPoly basicPoly = polyList.get(0);
// assertThat(basicPoly.size(), is(1));
// assertThat(basicPoly._id(), is("record_3"));
// statement = connection.prepareStatement("SELECT _id FROM poly WHERE _id = 'record_666' ");
// polyList = sqLiteStorage.evaluateStatement(statement);
// assertThat(polyList, not(nullValue()));
// assertThat(polyList.size(), is(0));
}
|
package com.opengamma.util.rest;
import java.net.URI;
import com.opengamma.transport.jaxrs.FudgeObjectBinaryConsumer;
import com.opengamma.transport.jaxrs.FudgeObjectBinaryProducer;
import com.sun.jersey.api.client.AsyncWebResource;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
* Fudge-based client to call remote RESTful services.
* <p>
* This has configuration to rethrow exceptions sent across the network.
*/
public class FudgeRestClient {
/**
* The client.
*/
private final Client _client;
/**
* Creates an instance.
* @param underlyingClient the
*/
protected FudgeRestClient(final Client underlyingClient) {
_client = underlyingClient;
}
/**
* Creates an instance, initializing the providers
* @return the RESTful client, not null
*/
public static FudgeRestClient create() {
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(FudgeObjectBinaryConsumer.class);
config.getClasses().add(FudgeObjectBinaryProducer.class);
Client client = Client.create(config);
client.addFilter(new ExceptionThrowingClientFilter());
return new FudgeRestClient(client);
}
/**
* Gets the underlying Jersey RESTful client.
* @return the client, not null
*/
public Client getClient() {
return _client;
}
/**
* Obtains a class that can be used to call a remote resource synchronously.
*
* @param uri the URI of the resource, not null
* @return a class that can be used to call a remote resource, not null
*/
public WebResource access(final URI uri) {
return getClient().resource(uri);
}
/**
* Obtains a class that can be used to call a remote resource asynchronously.
*
* @param uri the URI of the resource, not null
* @return a class that can be used to call a remote resource, not null
*/
public AsyncWebResource accessAsync(final URI uri) {
return getClient().asyncResource(uri);
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.Screen;
import com.valkryst.VTerminal.Tile;
import com.valkryst.VTerminal.builder.ButtonBuilder;
import com.valkryst.VTerminal.palette.ColorPalette;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import javax.swing.event.MouseInputListener;
import java.awt.*;
import java.awt.event.MouseEvent;
@ToString
public class Button extends Component {
/** Whether or not the button is in the normal state. */
private boolean isInNormalState = true;
/** whether or not the button is in the hovered state. */
private boolean isInHoveredState = false;
/** Whether or not the button is in the pressed state. */
private boolean isInPressedState = false;
/** The background color for when the button is in the normal state. */
protected Color backgroundColor_normal;
/** The foreground color for when the button is in the normal state. */
protected Color foregroundColor_normal;
/** The background color for when the button is in the hover state. */
protected Color backgroundColor_hover;
/** The foreground color for when the button is in the hover state. */
protected Color foregroundColor_hover;
/** The background color for when the button is in the pressed state. */
protected Color backgroundColor_pressed;
/** The foreground color for when the button is in the pressed state. */
protected Color foregroundColor_pressed;
/** The function to run when the button is clicked. */
@Getter @Setter @NonNull private Runnable onClickFunction;
/**
* Constructs a new AsciiButton.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public Button(final @NonNull ButtonBuilder builder) {
super(builder.getDimensions(), builder.getPosition());
colorPalette = builder.getColorPalette();
backgroundColor_normal = colorPalette.getButton_defaultBackground();
foregroundColor_normal = colorPalette.getButton_defaultForeground();
backgroundColor_hover = colorPalette.getButton_hoverBackground();
foregroundColor_hover = colorPalette.getButton_hoverForeground();
backgroundColor_pressed = colorPalette.getButton_pressedBackground();
foregroundColor_pressed = colorPalette.getButton_pressedForeground();
this.onClickFunction = builder.getOnClickFunction();
// Set the button's text:
final char[] text = builder.getText().toCharArray();
final Tile[] tiles = super.tiles.getRow(0);
for (int x = 0; x < tiles.length; x++) {
tiles[x].setCharacter(text[x]);
tiles[x].setBackgroundColor(backgroundColor_normal);
tiles[x].setForegroundColor(foregroundColor_normal);
}
}
@Override
public void createEventListeners(final @NonNull Screen parentScreen) {
if (super.eventListeners.size() > 0) {
return;
}
final MouseInputListener mouseListener = new MouseInputListener() {
@Override
public void mouseDragged(final MouseEvent e) {}
@Override
public void mouseMoved(final MouseEvent e) {
if (intersects(parentScreen.getMousePosition())) {
setStateHovered();
} else {
setStateNormal();
}
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (intersects(parentScreen.getMousePosition())) {
setStatePressed();
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (isInPressedState) {
onClickFunction.run();
}
if (intersects(parentScreen.getMousePosition())) {
setStateHovered();
} else {
setStateNormal();
}
}
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
};
super.eventListeners.add(mouseListener);
}
@Override
public void setColorPalette(final ColorPalette colorPalette, final boolean redraw) {
if (colorPalette == null) {
return;
}
// Set the instance variables.
this.colorPalette = colorPalette;
this.backgroundColor_normal = colorPalette.getButton_defaultBackground();
this.foregroundColor_normal = colorPalette.getButton_defaultForeground();
this.backgroundColor_pressed = colorPalette.getButton_pressedBackground();
this.foregroundColor_pressed = colorPalette.getButton_pressedForeground();
this.backgroundColor_hover = colorPalette.getButton_hoverBackground();
this.foregroundColor_hover = colorPalette.getButton_hoverForeground();
// Determine the colors to color the tiles with.
final Color backgroundColor;
final Color foregroundColor;
if (isInPressedState) {
backgroundColor = backgroundColor_pressed;
foregroundColor = foregroundColor_pressed;
} else if (isInHoveredState) {
backgroundColor = backgroundColor_hover;
foregroundColor = foregroundColor_hover;
} else {
backgroundColor = backgroundColor_normal;
foregroundColor = foregroundColor_normal;
}
for (int y = 0 ; y < super.tiles.getHeight() ; y++) {
for (int x = 0 ; x < super.tiles.getWidth() ; x++) {
final Tile tile = super.tiles.getTileAt(x, y);
tile.setBackgroundColor(backgroundColor);
tile.setForegroundColor(foregroundColor);
}
}
if (redraw) {
redrawFunction.run();
}
}
/**
* Sets the button state to normal if the current state allows for the normal
* state to be set.
*/
protected void setStateNormal() {
boolean canSetState = isInNormalState == false;
canSetState &= isInHoveredState || isInPressedState;
if (canSetState) {
isInNormalState = true;
isInHoveredState = false;
isInPressedState = false;
setColors(backgroundColor_normal, foregroundColor_normal);
redrawFunction.run();
}
}
/**
* Sets the button state to hovered if the current state allows for the normal
* state to be set.
*/
protected void setStateHovered() {
boolean canSetState = isInNormalState || isInPressedState;
canSetState &= isInHoveredState == false;
if (canSetState) {
isInNormalState = false;
isInHoveredState = true;
isInPressedState = false;
setColors(backgroundColor_hover, foregroundColor_hover);
redrawFunction.run();
}
}
/**
* Sets the button state to pressed if the current state allows for the normal
* state to be set.
*/
protected void setStatePressed() {
boolean canSetState = isInNormalState || isInHoveredState;
canSetState &= isInPressedState == false;
if (canSetState) {
isInNormalState = false;
isInHoveredState = false;
isInPressedState = true;
setColors(backgroundColor_pressed, foregroundColor_pressed);
redrawFunction.run();
}
}
/**
* Sets the back/foreground colors of all characters to the specified colors.
*
* @param backgroundColor
* The new background color.
*
* @param foregroundColor
* The new foreground color.
*
* @throws NullPointerException
* If the background or foreground color is null.
*/
private void setColors(final @NonNull Color backgroundColor, final @NonNull Color foregroundColor) {
for (final Tile tile : super.tiles.getRow(0)) {
tile.setBackgroundColor(backgroundColor);
tile.setForegroundColor(foregroundColor);
}
}
/**
* Sets the text displayed on the button.
*
* @param text
* The new text.
*/
public void setText(String text) {
if (text == null) {
text = "";
}
for (int x = 0 ; x < tiles.getWidth() ; x++) {
if (x <= text.length()) {
tiles.getTileAt(x, 0).setCharacter(text.charAt(x));
} else {
tiles.getTileAt(x, 0).setCharacter(' ');
}
}
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.builder.component.*;
import com.valkryst.VTerminal.font.Font;
import com.valkryst.VTerminal.misc.ImageCache;
import com.valkryst.VTerminal.printer.RectanglePrinter;
import lombok.NonNull;
import lombok.ToString;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.LinkedHashSet;
import java.util.Set;
@ToString
public class Screen extends Component {
/** The non-layer components displayed on the screen. */
private Set<Component> components = new LinkedHashSet<>();
/** The layer components displayed on the screen. */
private Set<Layer> layerComponents = new LinkedHashSet<>();
/**
* Constructs a new Screen.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public Screen (final @NonNull ScreenBuilder builder) {
super(builder);
setBackgroundColor(new Color(45, 45, 45, 255));
if (builder.getJsonObject() != null) {
parseJSON(builder.getJsonObject());
}
}
private void parseJSON(final @NonNull JSONObject jsonObject) {
final JSONArray components = (JSONArray) jsonObject.get("components");
if (components != null) {
for (final Object obj : components) {
final JSONObject arrayElement = (JSONObject) obj;
if (arrayElement != null) {
final ComponentBuilder componentBuilder = loadElementFromJSON(arrayElement, super.getRadio());
if (componentBuilder != null) {
if (componentBuilder instanceof LayerBuilder) {
layerComponents.add((Layer) componentBuilder.build());
} else {
this.components.add(componentBuilder.build());
}
}
}
}
}
}
private ComponentBuilder loadElementFromJSON(final @NonNull JSONObject jsonObject, final @NonNull Radio<String> radio) {
String componentType = (String) jsonObject.get("type");
if (componentType == null) {
return null;
}
componentType = componentType.toLowerCase();
switch (componentType) {
case "button": {
final ButtonBuilder buttonBuilder = new ButtonBuilder();
buttonBuilder.parseJSON(jsonObject);
buttonBuilder.setRadio(radio);
return buttonBuilder;
}
case "check box": {
final CheckBoxBuilder checkBoxBuilder = new CheckBoxBuilder();
checkBoxBuilder.parseJSON(jsonObject);
checkBoxBuilder.setRadio(radio);
return checkBoxBuilder;
}
case "label": {
final LabelBuilder labelBuilder = new LabelBuilder();
labelBuilder.parseJSON(jsonObject);
labelBuilder.setRadio(radio);
return labelBuilder;
}
case "layer": {
final LayerBuilder layerBuilder = new LayerBuilder();
layerBuilder.parseJSON(jsonObject);
layerBuilder.setRadio(radio);
return layerBuilder;
}
case "progress bar": {
final ProgressBarBuilder progressBarBuilder = new ProgressBarBuilder();
progressBarBuilder.parseJSON(jsonObject);
progressBarBuilder.setRadio(radio);
return progressBarBuilder;
}
case "radio button": {
final RadioButtonBuilder radioButtonBuilder = new RadioButtonBuilder();
radioButtonBuilder.parseJSON(jsonObject);
radioButtonBuilder.setRadio(radio);
return radioButtonBuilder;
}
case "radio button group": {
final RadioButtonGroup radioButtonGroup = new RadioButtonGroup();
final JSONArray radioButtons = (JSONArray) jsonObject.get("components");
if (radioButtons != null) {
for (final Object object : radioButtons) {
final JSONObject buttonJSON = (JSONObject) object;
final RadioButtonBuilder builder = (RadioButtonBuilder) loadElementFromJSON(buttonJSON, radio);
builder.setGroup(radioButtonGroup);
components.add(builder.build());
}
}
return null;
}
case "screen": {
final ScreenBuilder screenBuilder = new ScreenBuilder();
screenBuilder.parseJSON(jsonObject);
screenBuilder.setRadio(radio);
return screenBuilder;
}
case "text field": {
final TextFieldBuilder textFieldBuilder = new TextFieldBuilder();
textFieldBuilder.parseJSON(jsonObject);
textFieldBuilder.setRadio(radio);
return textFieldBuilder;
}
case "text area": {
final TextAreaBuilder textAreaBuilder = new TextAreaBuilder();
textAreaBuilder.parseJSON(jsonObject);
textAreaBuilder.setRadio(radio);
return textAreaBuilder;
}
case "rectangle printer": {
final RectanglePrinter rectanglePrinter = new RectanglePrinter();
rectanglePrinter.printFromJSON(this, jsonObject);
return null;
}
default: {
throw new IllegalArgumentException("The element type '" + componentType + "' is not supported.");
}
}
}
@Override
public void draw(final @NonNull Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache) {
// Draw non-layer components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
for (int row = 0 ; row < getHeight() ; row++) {
super.getString(row).draw(gc, imageCache, row);
}
// Draw layer components onto the screen:
layerComponents.forEach(layer -> layer.draw(gc, imageCache));
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point
* to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param columnIndex
* The x-axis (column) coordinate of the cell to clear.
*
* @param rowIndex
* The y-axis (row) coordinate of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final int columnIndex, final int rowIndex, int width, int height) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= width >= 0;
canProceed &= height >= 0;
if (canProceed) {
width += columnIndex;
height += rowIndex;
for (int column = columnIndex ; column < width ; column++) {
for (int row = rowIndex ; row < height ; row++) {
write(character, column, row);
}
}
}
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*/
public void clear(final char character) {
clear(character, 0, 0, super.getWidth(), super.getHeight());
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*
* @throws NullPointerException
* If the character is null.
*/
public void write(final @NonNull AsciiCharacter character, final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex)) {
super.getString(rowIndex).setCharacter(columnIndex, character);
}
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*/
public void write(final char character, final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex)) {
super.getString(rowIndex).setCharacter(columnIndex, character);
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param columnIndex
* The x-axis (column) coordinate to begin writing from.
*
* @param rowIndex
* The y-axis (row) coordinate to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull AsciiString string, final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex)) {
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0; i < characters.length && i < super.getWidth(); i++) {
write(characters[i], columnIndex + i, rowIndex);
}
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param columnIndex
* The x-axis (column) coordinate to begin writing from.
*
* @param rowIndex
* The y-axis (row) coordinate to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull String string, final int columnIndex, final int rowIndex) {
write(new AsciiString(string), columnIndex, rowIndex);
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point
* to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param position
* The x/y-axis (column/row) coordinates of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final Point position, int width, int height) {
clear(character, position.x, position.y, width, height);
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinates to write to.
*
* @throws NullPointerException
* If the character is null.
*/
public void write(final @NonNull AsciiCharacter character, final Point position) {
write(character, position.x, position.y);
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinates to write to.
*/
public void write(final char character, final Point position) {
write(character, position.x, position.y);
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull AsciiString string, final Point position) {
write(string, position.x, position.y);
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull String string, final Point position) {
write(new AsciiString(string), position);
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a little different
* if there are blink effects or new updates to characters that haven't yet
* been drawn.
*
* This is an expensive operation as it essentially creates an in-memory
* screen and draws each AsciiCharacter onto that screen.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @return
* An image of the screen.
*
* @throws NullPointerException
* If the image cache is null.
*/
public BufferedImage screenshot(final @NonNull ImageCache imageCache) {
final Font font = imageCache.getFont();
final int width = this.getWidth() * font.getWidth();
final int height = this.getHeight() * font.getHeight();
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
draw(gc, imageCache);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setBackgroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setForegroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*
* @throws NullPointerException
* If the background or foreground color is null.
*/
public void setBackgroundAndForegroundColor(final @NonNull Color background, final @NonNull Color foreground) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(background);
string.setForegroundColor(foreground);
}
}
/**
* Adds a component to the screen.
*
* @param component
* The component.
*
* @throws NullPointerException
* If the component is null.
*/
public void addComponent(final @NonNull Component component) {
if (component instanceof Layer) {
component.setScreen(this);
layerComponents.add((Layer) component);
} else {
component.setScreen(this);
components.add(component);
}
}
/**
* Adds one or more components to the screen.
*
* @param components
* The components.
*
* @throws NullPointerException
* If the components are null.
*/
public void addComponents(final @NonNull Component ... components) {
for (int i = 0 ; i < components.length ; i++) {
addComponent(components[i]);
}
}
public void removeComponent(final @NonNull Component component) {
if (component == this) {
throw new IllegalArgumentException("A screen cannot be removed from itself.");
}
if (component instanceof Layer) {
component.setScreen(null);
layerComponents.remove(component);
} else {
component.setScreen(null);
components.remove(component);
}
}
/**
* Removes one or more components from the screen.
*
* @param components
* The components.
*
* @throws NullPointerException
* If the components are null.
*/
public void removeComponents(final @NonNull Component ... components) {
for (final Component component : components) {
removeComponent(component);
}
}
/**
* Determines whether or not the screen contains a specific component.
*
* @param component
* The component.
*
* @return
* Whether or not the screen contains the component.
*
* @throws NullPointerException
* If the component is null.
*/
public boolean containsComponent(final @NonNull Component component) {
if (component == this) {
return false;
}
if (component instanceof Layer) {
if (layerComponents.contains(component)) {
return true;
}
}
return components.contains(component);
}
/**
* Determines whether or not the screen, or any sub-screen of the screen,
* contains a specific component.
*
* @param component
* The component.
*
* @return
* Whether or not the component is contained within the
* screen or any sub-screen.
*
* @throws NullPointerException
* If the component is null.
*/
public boolean recursiveContainsComponent(final @NonNull Component component) {
if (component == this) {
return false;
}
if (containsComponent(component)) {
return true;
}
if (component instanceof Screen) {
if (((Screen) component).containsComponent(this)) {
return true;
}
}
return false;
}
/**
* Determines the total number of components.
*
* @return
* The total number of components.
*/
public int totalComponents() {
int sum = components.size();
sum += layerComponents.size();
return sum;
}
/**
* Retrieves the first encountered component that uses the specified ID.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, the null is returned.
* Else the component is returned.
*/
public Component getComponentByID(final String id) {
for (final Component component : components) {
if (component.getId().equals(id)) {
return component;
}
}
for (final Layer layer : layerComponents) {
if (layer.getId().equals(id)) {
return layer;
}
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Button component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no button component matches the ID, then null is returned.
* Else the component is returned.
*/
public Button getButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Button) {
return (Button) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Check Box component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no check box component matches the ID, then null is returned.
* Else the component is returned.
*/
public CheckBox getCheckBoxByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof CheckBox) {
return (CheckBox) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Layer component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no layer component matches the ID, then null is returned.
* Else the component is returned.
*/
public Layer getLayerByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Layer) {
return (Layer) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* ProgressBar component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no progress bar component matches the ID, then null is returned.
* Else the component is returned.
*/
public ProgressBar getProgressBarByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof ProgressBar) {
return (ProgressBar) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* RadioButton component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no radio button component matches the ID, then null is returned.
* Else the component is returned.
*/
public RadioButton getRadioButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof RadioButton) {
return (RadioButton) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextArea component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text area component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextArea getTextAreaByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextArea) {
return (TextArea) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextField component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text field component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextField getTextFieldByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextField) {
return (TextField) component;
}
return null;
}
/**
* Retrieves a combined set of all components.
*
* @return
* A combined set of all components.
*/
public Set<Component> getComponents() {
final Set<Component> set = new LinkedHashSet<>(components);
set.addAll(layerComponents);
return set;
}
}
|
package com.xnx3.j2ee.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.shiro.ActiveUser;
/**
* Controller
* @author
*
*/
public class BaseController {
/**
*
* @return <li>ActiveUser
* <li>null
*/
protected ActiveUser getActiveUser() {
//shirosessionactiveUser
Subject subject = SecurityUtils.getSubject();
ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
if(activeUser != null){
return activeUser;
}else{
return null;
}
}
/**
*
* @return <li>User
* <li>null
*/
protected User getUser(){
ActiveUser activeUser = getActiveUser();
if(activeUser!=null){
return activeUser.getUser();
}else{
return null;
}
}
/**
*
* @param user
*/
protected void setUserForSession(User user){
getActiveUser().setUser(user);
}
protected String success(Model model , String info , String redirectUrl){
return prompt(model, info,redirectUrl, Global.PROMPT_STATE_SUCCESS);
}
/**
*
* @param model
* @param info
* @return
*/
protected String success(Model model , String info){
return prompt(model, info,null, Global.PROMPT_STATE_SUCCESS);
}
protected String error(Model model , String info,String redirectUrl){
return prompt(model, info,redirectUrl, Global.PROMPT_STATE_ERROR);
}
/**
*
* @param model
* @param info
* @return
*/
protected String error(Model model,String info){
return error(model, info, null);
}
private String prompt(Model model , String info,String redirectUrl, int state){
model.addAttribute("info", info);
model.addAttribute("state", state);
if(redirectUrl==null||redirectUrl.length()==0){
redirectUrl = "javascript:history.go(-1);";
}
model.addAttribute("redirectUrl", redirectUrl);
return "/prompt";
}
protected String redirect(String redirectUtl) {
if(redirectUtl != null && redirectUtl.indexOf("http")>-1){
return "redirect:"+redirectUtl;
}else{
return "redirect:/"+redirectUtl;
}
}
}
|
package com.opengamma.language.view;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.engine.view.client.ViewClient;
import com.opengamma.engine.view.client.ViewResultMode;
import com.opengamma.id.UniqueId;
import com.opengamma.language.context.SessionContext;
import com.opengamma.language.context.UserContext;
/**
* Manages a set of {@link ViewClient} within a {@link UserContext}. Each is uniquely identified by a {@link ViewClientKey}. When
* clients are referred to externally within a session, the reference can be detached into the {@link SessionContext} and be
* retrieved by its {@link UniqueId}.
*/
public class UserViewClients extends ViewClients<ViewClientKey, UserContext> {
private static final Logger s_logger = LoggerFactory.getLogger(UserViewClients.class);
public UserViewClients(final UserContext userContext) {
super(userContext);
}
protected ViewClient createViewClient() {
final ViewClient viewClient = getContext().getGlobalContext().getViewProcessor().createViewClient(getContext().getLiveDataUser());
viewClient.setResultMode(ViewResultMode.DELTA_ONLY);
return viewClient;
}
/**
* Gets the view client described by the given key. If such a client already exists, it is returned. If none exists, a new
* one is created. Do not call after (or while) calling {@link #destroyAll}. The client is "locked" and each call must be balanced
* by a call to {@link #unlockViewClient}.
* <p>
* For example, if the view client is passed back to the language binding, it may remain locked. When the language representation
* is discarded the unlock must occur. If listeners are registered with the client to push data to the language binding, the
* client must remain locked. If the "push" feed to the binding breaks (or is formally discarded), the unlock must occur.
* <p>
* A locked client will not be destroyed unless the whole user context is destroyed.
*
* @param viewClientKey key describing the client, not null
* @return the view client
*/
@Override
public AttachedViewClientHandle lockViewClient(final ViewClientKey viewClientKey) {
UserViewClient client;
do {
client = getClients().get(viewClientKey);
if (client == null) {
// TODO: check the graveyard for a matching view client instead of creating a new one
final ViewClient viewClient = createViewClient();
try {
client = new UserViewClient(getContext(), viewClient, viewClientKey);
final UserViewClient existing = getClients().putIfAbsent(viewClientKey, client);
if (existing == null) {
return new AttachedViewClientHandle(this, client);
}
client = existing;
} catch (Exception e) {
viewClient.shutdown();
throw new OpenGammaRuntimeException("Error initialising new view client", e);
}
}
} while (!client.incrementRefCount());
return new AttachedViewClientHandle(this, client);
}
/**
* Releases a client that is no longer locked (i.e. has a zero reference count).
*
* @param viewClient the client to unlock, not null
*/
@Override
protected void releaseViewClient(final UserViewClient viewClient) {
assert !viewClient.isLocked();
// TODO: post the old view client to a "graveyard" queue
getClients().remove(viewClient.getViewClientKey());
// TODO: only destroy immediately if the client is older than a given age
// TODO: remove the client from the graveyard (only destroy if still in the graveyard)
viewClient.destroy();
}
@Override
protected void destroyAll() {
super.destroyAll();
// TODO: destroy anything in the graveyard
}
@Override
protected Logger getLogger() {
return s_logger;
}
}
|
package com.knox.array;
import com.knox.Asserts;
import com.knox.list.AbstractList;
import com.knox.list.List;
public class ArrayList<T> extends AbstractList<T> {
private T[] elements;
private static final int DEFAULT_CAPACITY = 10;
public ArrayList(int capacity) {
capacity = Math.max(capacity, DEFAULT_CAPACITY);
elements = (T[]) new Object[capacity];
size = 0;
}
public ArrayList() {
this(DEFAULT_CAPACITY);
}
private void ensureCapacity(int capacity) {
int oldCapacity = elements.length;
if (oldCapacity >= capacity) return;
int newCapacity = oldCapacity + (oldCapacity >> 1);
T[] newElements = (T[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
elements = newElements;
System.out.println("[ capacity from " + oldCapacity + " to " + newCapacity + " ]");
}
private void trim() {
int newCapacity = elements.length >> 1;
if (size > newCapacity || newCapacity < DEFAULT_CAPACITY) return;
T[] newElements = (T[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
elements = newElements;
}
@Override
public void append(T element) {
insert(element, size);
}
@Override
public void insert(T element, int index) {
checkIndexForInsert(index);
ensureCapacity(size + 1);
for (int i = size - 1; i >= index; i
elements[i+1] = elements[i];
}
elements[index] = element;
size++;
}
@Override
public T removeAtIndex(int index) {
checkIndex(index);
T target = elements[index];
for (int i = index + 1; i < size; i++) {
elements[i-1] = elements[i];
}
elements[size-1] = null;
size
trim();
return target;
}
@Override
public void remove(T element) {
int targetIndex = indexOf(element);
if (targetIndex != ELEMENT_NOT_FOUND) {
removeAtIndex(targetIndex);
}
}
@Override
public int indexOf(T element) {
for (int i = 0; i < size; i++) {
// java ==
T value = elements[i];
if (element == null) {
if (value == null) return i;
} else {
if (value != null && value.equals(element)) return i;
}
}
return ELEMENT_NOT_FOUND;
}
@Override
public boolean contains(T element) {
return indexOf(element) != ELEMENT_NOT_FOUND;
}
@Override
public T get(int index) {
checkIndex(index);
return elements[index];
}
@Override
public T set(T element, int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size: " + size);
}
T old = elements[index];
elements[index] = element;
return old;
}
@Override
public T first() {
checkIndex(0);
return elements[0];
}
@Override
public T last() {
checkIndex(size-1);
return elements[size-1];
}
@Override
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ArrayList: size=").append(size).append(", [");
for (int i = 0; i < size; i++) {
if (i != 0) {
builder.append(", ");
}
builder.append(elements[i]);
}
builder.append("]");
return builder.toString();
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Asserts.testTrue(list.isEmpty());
Asserts.testEqual(list.size(), 0);
// append
list.append(10);
list.append(20);
list.append(30);
list.append(40);
Asserts.testEqual(list.size(), 4);
// last first
Asserts.testEqual(list.last(), 40);
Asserts.testEqual(list.first(), 10);
// contains
Asserts.testTrue(list.contains(30));
Asserts.testFalse(list.contains(100));
// insert
list.insert(13, 1);
Asserts.testEqual(list.get(1), 13);
// removeAtIndex
int oldSize = list.size();
Integer ret = list.removeAtIndex(1);
Asserts.testEqual(ret, 13);
int newSize = list.size();
Asserts.testEqual(newSize, oldSize - 1);
// set
Integer setNewValue = 300;
Integer oldValue = list.get(0);
Integer setRet = list.set(setNewValue, 0);
Asserts.testEqual(oldValue, setRet);
Asserts.testEqual(list.first(), setNewValue);
// clear
list.clear();
Asserts.testEqual(list.size(), 0);
Asserts.testTrue(list.isEmpty());
// remove
list.clear();
list.append(10);
list.append(20);
list.append(30);
list.append(20);
int size = list.size();
list.remove(10);
Asserts.testFalse(list.contains(10));
Asserts.testEqual(list.size(), size-1);
}
}
|
package com.cs446.kluster;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.IntentSender;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
/** Handles switching to Camera, saving data, and recording GPS information */
public class PhotoFactory extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private static Uri fileUri;
private static LocationClient mLocationClient = null;
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Create a new location client, using the enclosing class to
* handle callbacks. */
mLocationClient = new LocationClient(this, this, this);
TakePhoto();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to"+fileUri.toString(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
// Disconnecting the client invalidates it.
Log.w("gps", mLocationClient.getLastLocation().toString());
mLocationClient.disconnect();
}
public void TakePhoto() {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = PhotoFactory.getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// Connect the location client.
mLocationClient.connect();
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
/** Create a file Uri for saving an image or video */
public static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
if (!isExternalStorageWritable()) {
Log.d("Kluster", "External not writable");
return null;
}
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Kluster");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("Kluster", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
// Get the error code
int errorCode = connectionResult.getErrorCode();
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
errorCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment =
new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getFragmentManager(),
"Location Updates");
}
}
}
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
}
|
package de.aima13.whoami.modules;
import de.aima13.whoami.Analyzable;
import de.aima13.whoami.GlobalData;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.AbstractID3v2;
import org.farng.mp3.id3.ID3v1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.sql.*;
import java.util.*;
/**
* favourite Music, created 16.10.14.
*
* @author Inga Miadowicz
* @version 1.0
*/
public class Music implements Analyzable {
List<Path> musicDatabases = new ArrayList<>(); //List I get from FileSearcher
List<Path> localFiles = new ArrayList<>(); //List of MP3-files from musicDatabase
List<Path> browserFiles = new ArrayList<>(); //List of browser-entries from musicDatabase
List<Path> exeFiles = new ArrayList<>(); //List of browser-entries from musicDatabase
ArrayList<String> FileArtist = new ArrayList<>(); //List of Artists
ArrayList<String> FileGenre = new ArrayList<>(); //List of Genres
ArrayList<String> urls = new ArrayList<>(); //List of URLs
Map<String, Integer> mapMaxApp = new HashMap<>();//Map Artist - frequency of this artist
Map<String, Integer> mapMaxGen = new HashMap<>();//Map Genre - frequency of this genre
public String html = ""; //Output der HTML
public String favArtist = "";
public String favGenre = "";
public String onlService = ""; //Genutzte Onlinedienste (siehe: MY_SEARCH_DELIVERY_URLS)
public String cltProgram = ""; //Installierte Programme
String stmtGenre = ""; //Kommentar zum Genre nach Kategorie
private static final String[] MY_SEARCH_DELIEVERY_URLS = {"youtube.com", "myvideo.de", "dailymotion.com",
"soundcloud.com", "deezer.com"};
private static final String TITLE = "Musikgeschmack";
String[] arrayGenre = { // Position im Array ist Byte des id3Tag:
// z.B. GenreID ist 3: Genre zu 3 ist "Dance"
//Dies sind die offiziellen ID3v1 Genres.
"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge",
"Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap",
"Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
"Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient",
"Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical",
"Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise",
"Alternative Rock", "Bass", "Soul", "Punk", "Space", "Meditative",
"Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave",
"Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream",
"Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap",
"Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
"Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal",
"Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll",
"Hard Rock",
//These were made up by the authors of Winamp but backported into the ID3 spec.
"Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion",
"Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde",
"Gothic Rock", "Progressive Rock", "Psychedelic Rock", "Symphonic Rock",
"Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour",
"Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony",
"Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club",
"Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul",
"Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House",
"Dance Hall",
//These were also invented by the Winamp folks but ignored by the ID3 authors.
"Goa", "Drum & Bass", "Club-House", "Hardcore", "Terror", "Indie",
"BritPop", "Negerpunk", "Polsk Punk", "Beat", "Christian Gangsta Rap",
"Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian",
"Christian Rock", "Merengue", "Salsa", "Thrash Metal", "Anime", "Jpop",
"Synthpop"
};
@Override
public void run() {
/**
* Implementierung der Methode run() von Runnable
* @return void
* @param
*/
getFilter();
readId3Tag();
checkNativeClients();
readBrowser(MY_SEARCH_DELIEVERY_URLS);
}
@Override
public List<String> getFilter() {
//a) local MP3-files. LATER ADD(.FLAC, .RM, .acc, .ogg, .wav?)
List<String> filterMusic = new ArrayList<>();
filterMusic.add("**.mp3");
filterMusic.add("**.MP3");
filterMusic.add("**.mP3");
filterMusic.add("**.Mp3");
filterMusic.add("**.FLAC");
filterMusic.add("**.flac");
//b) Browser-history
filterMusic.add("**Google/Chrome**History");
filterMusic.add("**Firefox**places.sqlite");
//c) installed programs
filterMusic.add("**spotify.exe"); //AppData/Roaming... -> versteckter Ordner by default
filterMusic.add("**iTunes.exe");
filterMusic.add("**SWYH.exe");
filterMusic.add("**simfy.exe");
//jukebox, napster kostenpflichtig?
//Vorschlag: Amazon Prime instant
return filterMusic;
} //ANDERE DATEN
@Override
public void setFileInputs(List<Path> files) throws Exception {
if (!(files == null)) {
musicDatabases = files;
} else {
throw new IllegalArgumentException("Auf dem Dateisystem konnten keine " +
"Informationen zu Musik gefunden werden.");
}
//Spalte die Liste in drei Unterlisten:
for (Path element : musicDatabases) {
if (element.toString().contains(".mp3") || element.toString().contains(".flac") ||
element.toString().contains(".FLAC") || element.toString().contains(".MP3")) {
localFiles.add(element); // Liste der lokalen Audiodateien von denen der ID3Tag
// ausgelesen wird
} else if (element.toString().contains(".exe")) {
exeFiles.add(element);
} else {
browserFiles.add(element);
}
}
}
///// Output-Dateien vorbereiten /////////////////////
@Override
public String getHtml() {
/**
* Das Ergebnis der Analyse wird in HTML-lesbaren Format umgesetzt
*
* @return String html
* @param
*/
StringBuilder buffer = new StringBuilder();
buffer.append("<table>");
if (!(favArtist.equals(""))) {
buffer.append("<tr><td>Lieblingskünstler:</td>" +
"<td>" + favArtist + "</td></tr>");
}
if (!(favGenre.equals(""))) {
buffer.append("<tr>" +
"<td>Lieblingsgenre:</td>" +
"<td>" + favGenre + "</td>" +
"</tr>");
}
if (!(cltProgram.equals(""))) {
buffer.append("<tr>" +
"<td>Musikprogramme:</td>" +
"<td>" + cltProgram + "</td>" +
"</tr>");
}
if (!(onlService.equals(""))) {
buffer.append("<tr>" +
"<td>Onlinestreams:</td>" +
"<td>" + onlService + "</td>" +
"</tr>");
}
// Abschlussfazit des Musikmoduls
if (musicDatabases.isEmpty()) {
buffer.append("<tr><td><br />Es wurden keine Informationen gefunden um den scheinbar " +
"sehr geheimen Musikgeschmack des Users zu analysieren.</td></tr>");
} else if (!(onlService.equals("")) && !(favArtist.equals("")) && !(favGenre.equals(""))
&& !(cltProgram.equals(""))) {
buffer.append("<tr>" +
"<td colspan='2'><br /><b>Fazit:</b> Dein Computer enthält Informationen zu allem " +
"was wir gesucht haben.<br /> Musik schein ein wichtiger Teil deines Lebens " +
"zu sein. <br />" + stmtGenre + "</td>" +
"</tr>");
} else if (onlService.equals("") && cltProgram.equals("") && !(favGenre.equals(""))) {
buffer.append("<tr>" +
"<td colspan='2'><br /><b>Fazit:</b> Das Modul konnte weder online noch nativ " +
"herausfinden wie du Musik hörst. Du scheinst dies über einen nicht sehr " +
"verbreiteten Weg zu machen. Nichts desto trotz konnten wir deinen Geschmack " +
"analysieren:<br /> " + stmtGenre + "</td>" +
"</tr>");
} else if (favGenre.equals("") && favArtist.equals("")) {
buffer.append("<td colspan='2'><br /><b>Fazit:</b> Es können keine Informationen zu deinem " +
"Musikgeschmack " + "gefunden werden. ");
if (!(onlService.equals("")) || !(cltProgram.equals(""))) {
buffer.append("Aber Musik hörst du über " + onlService + cltProgram + "" +
". Nur was bleibt eine offene Frage.</td></tr>");
}
} else {
buffer.append("<tr>" +
"<td colspan='2'><br /><b>Fazit:</b>Zwar konnten einige Informationen über " +
"dich nicht herausgefunden werden, <br />aber einiges wissen wir.<br />");
if (!(onlService.equals(""))) {
buffer.append("<br />Du hörst über " + onlService + " online Musik.<br />");
}
if (!(cltProgram.equals(""))) {
buffer.append("<br />Auf deinem PC benutzt du zum Musik hören " + cltProgram + ".<br />");
}
if (!(favArtist.equals(""))) {
buffer.append("<br />Deine Lieblingsband ist" + favArtist + "<br />");
}
if (!(favGenre.equals(""))) {
buffer.append(stmtGenre);
}
buffer.append("</td></tr>");
}
buffer.append("</table>");
html = buffer.toString();
return html;
}
@Override
public String getReportTitle() {
return TITLE;
}
@Override
public String getCsvPrefix() {
return TITLE;
}
@Override
public SortedMap<String, String> getCsvContent() {
/**
*
* @return SortedMap<String, String> csvData
* @param
*/
SortedMap<String, String> csvData = new TreeMap<>();
if (!(favArtist.equals(""))) {
csvData.put("Lieblingskünstler", favArtist);
}
if (!(favArtist.equals(""))) {
csvData.put("Lieblingsgenre", favGenre);
}
if (!(favArtist.equals(""))) {
csvData.put("Onlineservices", onlService);
}
if (!(favArtist.equals(""))) {
csvData.put("Musikprogramme", cltProgram);
}
return csvData;
}
///// Analysiere Audidateien /////////////
public void scoreFavGenre() {
/**
* Sucht aus der Liste aller Genres das Lieblingsgenre heraus
* @return String favGenre
* @param ArrayList<String> fileArtist
*/
int max = 0;
int count;
FileGenre.removeAll(Arrays.asList("", null));
for (String each : FileGenre) {
count = 0;
if (mapMaxGen.containsKey(each)) {
count = mapMaxGen.get(each);
mapMaxGen.remove(each);
}
count++;
mapMaxGen.put(each, count);
}
Iterator it = mapMaxGen.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
if ((int) (pairs.getValue()) > max) {
favGenre = (String) pairs.getKey();
max = (int) (pairs.getValue());
}
it.remove();
}
//Einige ID3-Tags sind fehlerhaft und das Byte wird in der Form "(XX)"als String
// gespeichert. Hier wird nochmal geguckt ob das Genre zugeordnet werden kann.
if (favGenre.startsWith("(")) {
String str;
str = favGenre.replaceAll("\\D+", "");
byte gId = Byte.parseByte(str);
favGenre = arrayGenre[gId];
}
getCategory();
if (favGenre.equals("Emo")) {
GlobalData.getInstance().changeScore("Selbstmordgefährung", 50);
}
else if (favGenre.equals("Dance") || favGenre.equals("Disco")) {
GlobalData.getInstance().changeScore("Selbstmordgefährung", -20);
}
else if (favGenre.equals("Chillout")) {
GlobalData.getInstance().changeScore("Faulenzerfaktor", 40);
}
}
public String getCategory() {
StringBuilder statementToGenre = new StringBuilder();
if (favGenre.equals("Top 40") || favGenre.equals("House") || favGenre.equals("Drum & " +
"Bass") || favGenre.equals("Euro-House")) {
statementToGenre.append("Dein Musikgeschmack ist nicht gerade " +
"aussagekräftig.<br />Du scheinst nicht wirklich auszuwählen was " +
"dir gefällt,<br />sondern orientierst dich an Listen und Freunden.<br />" +
"Was dich charaktierisitert ist wahrscheinlich das Mainstream-Opfer");
} else if (favGenre.equals("Dance") || favGenre.equals("Disco") || favGenre.equals("Dancehall")
|| favGenre.equals("Samba") || favGenre.equals("Tango") || favGenre.equals("Club") ||
favGenre.equals("Swing") || favGenre.equals("Latin") || favGenre.equals("Salsa")
|| favGenre.equals("Eurodance")) {
statementToGenre.append("Deinem Musikstil, " + favGenre + ", " +
"nach zu urteilen,<br />schwingst " +
"du gerne dein Tanzbein.");
} else if (favGenre.equals("Techno") || favGenre.equals("Industrial") || favGenre.equals
("Acid Jazz") || favGenre.equals("Rave") || favGenre.equals("Psychedelic") ||
favGenre.equals("Dream") || favGenre.equals("Elecronic") || favGenre
.equals("Techno-Industrial") || favGenre.equals("Space") || favGenre.equals("Acid")
|| favGenre.equals("Trance") || favGenre.equals("Fusion") ||
favGenre.equals("Euro-Techno") || favGenre.equals("Hardcore Techno") || favGenre
.equals("Goa") || favGenre.equals("Fast Fusion") || favGenre.equals("Synthpop") ||
favGenre.equals("Dub") || favGenre.equals("Psytrance") || favGenre.equals
("Dubstep") || favGenre.equals("Psybient")) {
statementToGenre.append("Dein Musikstil lässt darauf schließen, " +
"<br />dass wenn man dich grob einer Richtung zuordnet du am ehesten einem Raver " +
"entsprichst.");
} else if (favGenre.equals("Retro") || favGenre.equals("Polka") || favGenre.equals
("Country") || favGenre.equals("Oldies") || favGenre.equals("Native US") ||
favGenre.equals("Southern Rock") || favGenre.equals("Instrumental") || favGenre
.equals("Classical") || favGenre.equals("Gospel") || favGenre.equals("Folklore") ||
favGenre.equals("A capella") || favGenre.equals("Symphony") ||
favGenre.equals("Sonata") || favGenre.equals("Opera") || favGenre.equals
("National Folk") || favGenre.equals("Avantgarde") || favGenre.equals("Baroque") ||
favGenre.equals("World Music") || favGenre.equals("Neoclassical")) {
statementToGenre.append("Dein Musikstil" + favGenre + "ist eher von traditioneller" +
" Natur.");
} else if (favGenre.equals("Christian Rap") || favGenre.equals("Pop-Folk") || favGenre
.equals("Christian Rock") || favGenre.equals("Contemporary Christian") ||
favGenre.equals("Christian Gangsta Rap") || favGenre.equals("Terror") || favGenre
.equals("Jpop") || favGenre.equals("Math Rock") || favGenre.equals("Emo") ||
favGenre.equals("New Romantic")) {
statementToGenre.append("Über Geschmack lässt sich ja bekanntlich streiten. " +
"Aber " + favGenre + " - Dein Ernst?!");
} else if (favGenre.equals("Post-Rock") || favGenre.equals("Classic Rock") || favGenre
.equals("Metal") || favGenre.equals("Rock") || favGenre.equals("Death Metal") ||
favGenre.equals("Hard Rock") || favGenre.equals("Alternative Rock") || favGenre
.equals("Instrumental Rock") || favGenre.equals("Darkwave") || favGenre.equals
("Gothic") || favGenre.equals("Alternative") || favGenre.equals("Folk Rock") ||
favGenre.equals("Symphonic Rock") || favGenre.equals("Gothic Rock") || favGenre
.equals("Progressive Rock") || favGenre.equals("Black Metal") || favGenre.equals
("Heavy Metal") || favGenre.equals("Punk Rock") || favGenre.equals("Rythmic " +
"Soul") || favGenre.equals("Thrash Metal") || favGenre.equals("Garage Rock") ||
favGenre.equals("Space Rock") || favGenre.equals("Industro-Goth") || favGenre
.equals("Garage") || favGenre.equals("Art Rock")) {
statementToGenre.append(favGenre + "? <br />In dir steckt bestimmt ein Headbanger!");
} else if (favGenre.equals("Chillout") || favGenre.equals("Reggea") || favGenre.equals
("Trip-Hop") || favGenre.equals("Hip-Hop")) {
statementToGenre.append("Deine Szene ist wahrscheinlich die Hip Hop Szene.<br />Du bist ein " +
"sehr relaxter Mensch <br />und vermutlich gehören die Baggy Pants " +
"zu deinen Lieblingskleidungstücken?");
} else if (favGenre.equals("Blues") || favGenre.equals("Jazz") || favGenre.equals("Vocal")
|| favGenre.equals("Jazz & Funk") || favGenre.equals("Soul") || favGenre.equals
("Ambient") || favGenre.equals("Illbient") || favGenre.equals("Lounge")) {
statementToGenre.append("Deinem Lieblingsgenre zu urteilen beschreibt sich dieses " +
"Modul als wahren Kenner.<br />Vermutlich spielst du selber mindestens ein " +
"Instrument <br />und verbringt dein Leben am liebsten entspannt mit einem " +
"Glas Rotwein.");
} else if (favGenre.equals("Gangsta") || favGenre.equals("Rap")) {
statementToGenre.append("Du hörst Rap. Vielleicht bis du sogar ein übler " +
"Gangstarapper");
} else if (favGenre.equals("Ska") || favGenre.equals("Acid Punk") || favGenre.equals("Punk")
|| favGenre.equals("Polsk Punk") || favGenre.equals("Negerpunk") || favGenre
.equals("Post-Punk")) {
statementToGenre.append("Deine Musiklieblingsrichtung ist Punk oder zumindest eine" +
"Strömung des Punks.");
} else if (favGenre.equals("Funk") || favGenre.equals("New Age") || favGenre.equals
("Grunge") || favGenre.equals("New Wave") || favGenre.equals("Rock & Roll") ||
favGenre.equals("BritPop") || favGenre.equals("Indie") || favGenre.equals("Porn " +
"Groove") || favGenre.equals("Chanson") || favGenre.equals("Folk") || favGenre
.equals("Experimental") || favGenre.equals("Neue Deutsche Welle") || favGenre
.equals("Indie Rock")) {
statementToGenre.append("Dein Musikgeschmack, " + favGenre + ", " +
"zeugt von Geschmack und Stil.");
} else if (favGenre.equals("Podcast") || favGenre.equals("Audio Theatre") || favGenre.equals
("Audiobook") || favGenre.equals("Speech") || favGenre.equals("Satire") ||
favGenre.equals("Soundtrack") || favGenre.equals("Sound Clip") || favGenre.equals
("Comedy") || favGenre.equals("Cabaret") || favGenre.equals("Showtunes") ||
favGenre.equals("Trailer") || favGenre.equals("Musical")) {
statementToGenre.append("Die Audiodatei lässt sich einer Art Literatur zuordnen. " +
"<br />Du bist entweder sehr Literaturbegeistert und liebst Soundtracks und Co" +
"<br />oder eine sehr faule Leseratte, die sich lieber alles vorlesen lässt. <br />" +
"Wie auch immer du bist, " +
"wahrscheinlich ein ziemlich belesener Mensch. ");
} else if (favGenre.equals("Other")) {
statementToGenre.append("Wer auch immer sich die ID3v1-Genres ausgedacht hat, " +
"<br />diese Richtung als 'Other' zu " +
"betiteln ist mehr als unaussagekräftig.<br />Du hast wahrscheinlich einen guten " +
"Musikgeschmack, wenn man sich anschaut <br />was da so unter diese Bezeichnung " +
"fällt :-)");
} else {
statementToGenre.append("Dein Musikgeschmack " + favGenre + " ist ziemlich " +
"extravagant.");
}
stmtGenre = statementToGenre.toString();
return stmtGenre;
}
public void scoreFavArtist() {
/**
* Sucht aus einer Liste aller Artisten des Lieblingsartisten heraus
*
* @param ArrayList<String> FileArtist
* @return void
*/
int count; //counts frequency of artist
int max = 0; //highest frequency
FileArtist.removeAll(Arrays.asList("", null)); //delete empty entries
Collections.sort(FileArtist); //sort list alphabetically
//hashes frequency to artist
for (String each : FileArtist) {
count = 0;
if (mapMaxApp.containsKey(each)) {
count = mapMaxApp.get(each);
mapMaxApp.remove(each);
}
count++;
mapMaxApp.put(each, count);
}
//Find artist with highest frequency
Iterator it = mapMaxApp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
if ((int) (pairs.getValue()) > max) {
favArtist = (String) pairs.getKey();
max = (int) (pairs.getValue());
}
it.remove();
}
}
public void readId3Tag() {
/**
* Liest den ID3 Tag von gefundenen MP3- und FLAC-Dateien aus
*
* @param ArrayList<File> localFiles
* @return void
* @remark benutzt Bibliothek "jid3lib-0.5.4.jar"
*/
String genre = ""; //Name of Genre
for (Path file : localFiles) {
try {
String fileLocation = file.toAbsolutePath().toString(); //Get path to file
MP3File mp3file = new MP3File(fileLocation); //create new object from ID3tag-package
if (mp3file.hasID3v2Tag()) {
AbstractID3v2 tagv2 = mp3file.getID3v2Tag();
//Fill ArrayList<String> with Artists and Genres
FileArtist.add(tagv2.getLeadArtist());
FileGenre.add(tagv2.getSongGenre());
} else if (mp3file.hasID3v1Tag()) {
ID3v1 tagv1 = mp3file.getID3v1Tag();
FileArtist.add(tagv1.getArtist()); //Fill List of Type String with artist
//Have to map genreID to name of genre
byte gId = tagv1.getGenre(); //Get Genre ID
try {
genre = arrayGenre[gId]; //look up String to ID
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("This Genre doesn't exist");
}
FileGenre.add(genre); //Fill List of Type String with genre
System.out.println("Artists: " + FileArtist);
System.out.println("Genre: " + FileGenre);
}
} catch (TagException e) {
} //bewusst ignoriert
catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (UnsupportedOperationException e) {
} catch (Exception e) {
}
}
scoreFavArtist(); //Call functions to find favArtist
scoreFavGenre(); //Call functions to find favGenre
}
///// Analysiere Musikprogramme //////////
public void checkNativeClients() {
String clients[] = new String[4];
int count = 0;
for (Path currentExe : exeFiles) {
if (currentExe.toString().endsWith("spotify.exe")) {
clients[count] = "Spotify";
count++;
}
if (currentExe.toString().endsWith("iTunes.exe")) {
clients[count] = "iTunes";
count++;
}
if (currentExe.toString().endsWith("SWYH.exe")) {
clients[count] = "Stream What You Hear";
count++;
}
if (currentExe.toString().endsWith("simfy.exe")) {
clients[count] = "simfy";
count++;
}
}
if (count == 0) {
cltProgram = "";
} else if (count == 1) {
cltProgram = clients[0];
} else if (count == 2) {
cltProgram = clients[0] + ", " + clients[1];
} else if (count == 3) {
cltProgram = clients[0] + ", " + clients[1] + ", " + clients[2];
} else if (count == 4) {
cltProgram = clients[0] + ", " + clients[1] + ", " + clients[2] + ", " + clients[3];
}
}
///// Analysiere Browserverlauf //////////
public void readBrowser(String searchUrl[]) {
/**
* Durchsucht den Browser-Verlauf auf bekannte Musikportale
*
* @param browserFiles
* @return void
*/
dbExtraction();
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
String sqlStatement = "SELECT * FROM urls WHERE url LIKE '%" + searchUrl[0] + "%'";
for (int i = 1; i < searchUrl.length; i++) {
sqlStatement += "OR url LIKE '%" + searchUrl[i] + "%' ";
}
//Datenbankabfrage Chrome
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + urls.get(0));
statement = connection.createStatement();
try {
resultSet = statement.executeQuery(sqlStatement);
} catch (SQLException e) {
System.out.println("database file ist busy. Have to Close Browser to get acces.");
}
urls.clear();
try {
while (resultSet.next()) {
if (!(resultSet.getString("url").contains("google"))) {
urls.add(resultSet.getString("url"));
}
}
for (int i = 1; i < urls.size(); i++) {
String curr = urls.get(i);
if (curr.contains("youtube.com") && !(onlService.contains("youtube.com"))) {
if (onlService.isEmpty()) {
onlService += "youtube.com";
} else {
onlService += ", youtube.com";
}
}
if (curr.contains("myvideo.de") && !(onlService.contains("myvideo.de"))) {
if (onlService.isEmpty()) {
onlService += "myvideo.de";
} else {
onlService += ", myvideo.de";
}
}
if (curr.contains("soundcloud.com") && !(onlService.contains("soundcloud.com"))) {
if (onlService.isEmpty()) {
onlService += "soundcloud.com";
} else {
onlService += ", soundcloud.com";
}
}
if (curr.contains("dailymotion.com") && !(onlService.contains("dailymotion.com"))) {
if (onlService.isEmpty()) {
onlService += "dailymotion.com";
} else {
onlService += ", dailymotion.com";
}
}
if (curr.contains("deezer.com") && !(onlService.contains("deezer.com"))) {
if (onlService.isEmpty()) {
onlService += "deezer.com";
} else {
onlService += ", deezer.com";
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (NullPointerException e) {
} catch (Exception e) {
}
}
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
} catch (IndexOutOfBoundsException e) {
}
}
private void dbExtraction() {
/**
*
*
* @param
* @retrun void
*/
String username = System.getProperty("user.name");
GlobalData.getInstance().changeScore("Name des Benutzers: " + username, 0);
int foundDbs = 0;
try {
for (Path curr : browserFiles) {
if (curr != null) {
String path = "";
try {
path = curr.toString();
} catch (Exception e) {
}
//Unterscheidung zwischen Firefox und Chrome Datenbank
if (path.contains(".sqlite")) {
urls.add(path);
foundDbs++;
} else if (path.endsWith("\\History") && path.contains(username)) {
urls.add(path);
foundDbs++;
}
if (foundDbs > 1) {
break;
}
}
}
} catch (Exception e) {
}
}
}
|
package base;
import housing.roles.HousingBaseRole;
import housing.roles.HousingRenterRole;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.Semaphore;
import market.roles.MarketCustomerRole;
import restaurant.interfaces.RestaurantCustomerRole;
import transportation.roles.TransportationBusRiderRole;
import bank.roles.BankCustomerRole;
import bank.roles.BankMasterTellerRole;
import base.Event.EnumEventType;
import base.Item.EnumMarketItemType;
import base.interfaces.Person;
import base.interfaces.Role;
//import city.gui.PersonGui;
import city.gui.CityPerson;
public class PersonAgent extends Agent implements Person {
//Static data
static int sSSN = 0;
static int sTimeSchedule = 0; //0,1,2
static int sEatingTime = 0;
//Roles and Job
public static enum EnumJobType {BANK, HOUSING, MARKET, RESTAURANT, TRANSPORTATION, NONE};
private EnumJobType mJobPlace;
public Map<Role, Boolean> mRoles; // i.e. WaiterRole, BankTellerRole, etc.
public HousingBaseRole mHouseRole;
//Lists
List<Person> mFriends; // best are those with same timeshift
SortedSet<Event> mEvents; // tree set ordered by time of event
Map<EnumMarketItemType, Integer> mItemInventory; // personal inventory
//ALL: Does this need to be synchronized? -Shane
Map<EnumMarketItemType, Integer> mItemsDesired; // not ordered yet
//Personal Variables
private String mName;
int mSSN;
int mTimeShift;
double mCash;
double mLoan;
boolean mHasHome;
Set<Location> mHomeLocations; //multiple for landlord
boolean mHasCar;
Location mWorkLocation;
CityPerson personGui = null;
public Semaphore semAnimationDone = new Semaphore(0);
private boolean mRoleFinished;
//Role References
public BankMasterTellerRole mMasterTeller;
private CityPerson mGui; //SHANE JERRY: 2 instantiate this
public PersonAgent() {
initializePerson();
}
public PersonAgent(EnumJobType job, double cash, String name){
initializePerson();
mJobPlace = job;
mCash = cash;
mName = name;
boolean active = (mTimeShift == 0);
switch (job){
case BANK:
mRoles.put(SortingHat.getBankRole(mTimeShift), active);
break;
case MARKET:
mRoles.put(SortingHat.getMarketRole(mTimeShift), active);
break;
case RESTAURANT:
mRoles.put(SortingHat.getRestaurantRole(mTimeShift), active);
break;
case TRANSPORTATION: break;
case HOUSING: break;
case NONE: break;
}
mHouseRole = (HousingBaseRole) SortingHat.getHousingRole(this); //get housing status
mRoles.put(mHouseRole, true);
//Add customer/rider role possibilities
mRoles.put(new BankCustomerRole(this), false);
mRoles.put(new HousingRenterRole(this), false);
mRoles.put(new MarketCustomerRole(this), false);
mRoles.put(new TransportationBusRiderRole(this), false);
mRoles.put(new RestaurantCustomerRole(this), false); //DAVID: 1 add this here when done
}
private void initializePerson(){
mSSN = sSSN++; // assign SSN
mTimeShift = (sTimeSchedule++ % 3); // assign time schedule
mRoles = new HashMap<Role, Boolean>();
mCash = 100;
mLoan = 0;
// Event Setup
mEvents = Collections.synchronizedSortedSet(new TreeSet<Event>());
mEvents.add(new Event(EnumEventType.GET_CAR, 0));
mEvents.add(new Event(EnumEventType.JOB, mTimeShift + 0));
mEvents.add(new Event(EnumEventType.EAT, (mTimeShift + 8 + mSSN % 4) % 24)); // personal time
mEvents.add(new Event(EnumEventType.EAT, (mTimeShift + 12 + mSSN % 4) % 24)); // shift 4
mEvents.add(new Event(EnumEventType.PARTY, (mTimeShift + 16) + (mSSN + 3) * 24)); // night time, every SSN+3 days
}
public void msgTimeShift() {
if (Time.GetShift() == 0) {
// resetting of variables?
}
stateChanged();
}
public void msgAddEvent(Event event) {
if ((event.mEventType == EnumEventType.RSVP1) && (mSSN % 2 == 1)) return; // maybe don't respond (half are deadbeats)
mEvents.add(event);
}
public void msgAnimationDone(){
if (semAnimationDone.availablePermits() == 0) semAnimationDone.release();
}
public void msgRoleFinished(){
mRoleFinished = true;
}
@Override
public boolean pickAndExecuteAnAction() {
//if not during job shift
if ((mRoleFinished) && (Time.GetShift() != mTimeShift)){
// Process events (calendar)
Iterator<Event> itr = mEvents.iterator();
while (itr.hasNext()) {
Event event = itr.next();
if (event.mTime > Time.GetTime())
break; // don't do future calendar events
processEvent(event);
itr.remove();
}
}
// Do role actions
for (Role iRole : mRoles.keySet()) {
if (mRoles.get(iRole)) {
if (iRole.pickAndExecuteAnAction())
return true;
}
}
return false;
}
private synchronized void processEvent(Event event) {
//One time events (Car)
if (event.mEventType == EnumEventType.GET_CAR) {
getCar(); //SHANE: 1 get car
}
//Daily Recurring Events (Job, Eat)
else if (event.mEventType == EnumEventType.JOB) {
//bank is closed on weekends
if (!(Time.IsWeekend()) || (mJobPlace != EnumJobType.BANK)){
goToJob(); //SHANE: 1 go to job
}
mEvents.add(new Event(event, 24));
}
else if (event.mEventType == EnumEventType.EAT) {
eatFood(); //SHANE: 1 eat food
mEvents.add(new Event(event, 24));
}
//Intermittent Events (Deposit Check)
else if (event.mEventType == EnumEventType.DEPOSIT_CHECK) {
depositCheck(); //SHANE: 1 deposit check
}
else if (event.mEventType == EnumEventType.ASK_FOR_RENT) {
invokeRent(); //SHANE: 1 invoke rent
}
else if (event.mEventType == EnumEventType.MAINTAIN_HOUSE) {
invokeMaintenance(); //SHANE: 1 invoke maintenance
}
//Party Events
else if (event.mEventType == EnumEventType.INVITE1) {
inviteToParty(); //SHANE: 1 invite to party
}
else if (event.mEventType == EnumEventType.INVITE2) {
reinviteDeadbeats(); //SHANE: 1 reinvite deadbeats
}
else if (event.mEventType == EnumEventType.RSVP1) {
respondToRSVP(); //SHANE: 1 respond to rsvp
}
else if (event.mEventType == EnumEventType.RSVP2) {
respondToRSVP(); //SHANE: 1 respond to rsvp (same)
}
else if (event.mEventType == EnumEventType.PARTY) {
throwParty(); //SHANE: 1 throw party
int inviteNextDelay = 24*mSSN;
EventParty party = (EventParty) event;
mEvents.add(new EventParty(party, inviteNextDelay + 2));
mEvents.add(new EventParty(party, EnumEventType.INVITE1, inviteNextDelay, getBestFriends()));
mEvents.add(new EventParty(party, EnumEventType.INVITE2, inviteNextDelay + 1, getBestFriends()));
//SHANE: 3 check event classes
}
}
private void acquireSemaphore(Semaphore semaphore){
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void getCar(){
Location location = ContactList.cMARKET_LOCATION;
mGui.DoGoToDestination(location);
acquireSemaphore(semAnimationDone);
//remove current gui (isPresent = false)
//create new market gui
//lock person until role is finished
mRoleFinished = false;
//activate marketcustomer role
for (Role iRole : mRoles.keySet()){
if (iRole instanceof MarketCustomerRole){
mRoles.put(iRole, true); //set active
}
}
//add desired item
mItemsDesired.put(EnumMarketItemType.CAR, 1); //want 1 car
//message market cashier to start transaction
}
private void goToJob() {
// gui.DoGoTo(Location Job);
// semAnimation.acquire();
//add job role
// DoGoTo(work.location);
// work.getHost().msgImHere(job);
// job.active = T;
// state = PersonState.Working;
}
private void eatFood() {
//set restaurant for restaurantcustomerrole
RestaurantCustomerRole restaurantCustomerRole = null;
for (Role iRole : mRoles.keySet()){
if (iRole instanceof RestaurantCustomerRole){
restaurantCustomerRole = (RestaurantCustomerRole) iRole;
}
}
int randomRestaurant = 1; //SHANE: Make random
// restaurantCustomerRole
// // What will be our algorithm to figure out which to do?
// switch(random(2)) {
// case 0:
// // Eat at home.
// DoGoTo(home.location);
// roles.find(HouseRenterRole).active = T;
// DoGoMakeFoodAtHome();
// state = PersonState.Eating;
// break;
// case 1:
// // Eat at restaurant.
// // What will be our algorithm to figure out which restaurant to go
// restaurantChoice = restaurants.chooseRestaurant();
// DoGoTo(restaurantChoice.location);
// restaurantChoice.getHost().msgImHungry(roles.find(CustomerRole));
// roles.find(CustomerRole).active = T;
// state = PersonState.Eating;
// break;
}
public void SetGui(CityPerson pGui){
personGui = pGui;
}
private void depositCheck() {
}
private void throwParty() {
}
private void inviteToParty() {
}
private void reinviteDeadbeats() {
}
private void respondToRSVP(){
}
private void invokeRent() {
mHouseRole.msgTimeToCheckRent();
}
private void invokeMaintenance() {
mHouseRole.msgTimeToMaintain();
}
private List<Person> getBestFriends(){
List<Person> bestFriends = new ArrayList<Person>();
for (Person iPerson : mFriends){
if (iPerson.getTimeShift() == mTimeShift) bestFriends.add(iPerson);
}
return bestFriends;
}
//SHANE: 4 Organize PersonAgent Accessors
public void addRole(Role role, boolean active) {
mRoles.put(role, active);
role.setPerson(this);
}
public void removeRole(Role r) {
mRoles.remove(r);
}
public double getCash() {
return mCash;
}
public void setCash(double cash) {
mCash = cash;
}
public void addCash(double amount) {
mCash += amount;
}
public void setLoan(double loan) {
mLoan = loan;
}
public double getLoan() {
return mLoan;
}
public Map<EnumMarketItemType, Integer> getItemsDesired() {
return mItemsDesired;
}
public int getSSN() {
return mSSN;
}
public Map<EnumMarketItemType, Integer> getItemInventory() {
return mItemInventory;
}
protected void print(String msg) {
System.out.println("" + mName + ": " + msg);
}
public String getName(){
return mName;
}
public int getTimeShift(){
return mTimeShift;
}
public void msgHereIsPayment(int senderSSN, double amount) {
mCash += amount;
}
public void setName(String name) {
mName = name;
}
public void setSSN(int SSN) {
mSSN = SSN;
}
@Override
public void setItemsDesired(Map<EnumMarketItemType, Integer> map) {
mItemsDesired = map;
}
@Override
public void msgOverdrawnAccount(double loan) {
mLoan += loan;
}
@Override
public Map<Role, Boolean> getRoles() {
return mRoles;
}
@Override
public Role getHousingRole() {
return mHouseRole;
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.Objects;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
ListModel<IconItem> list = makeIconList();
TableModel model = makeIconTableModel(list);
JTable table = new IconTable(model, list);
JPanel p = new JPanel(new GridBagLayout());
p.add(table, new GridBagConstraints());
p.setBackground(Color.WHITE);
add(p);
setPreferredSize(new Dimension(320, 240));
}
private static ListModel<IconItem> makeIconList() {
DefaultListModel<IconItem> list = new DefaultListModel<>();
list.addElement(new IconItem("wi0009"));
list.addElement(new IconItem("wi0054"));
list.addElement(new IconItem("wi0062"));
list.addElement(new IconItem("wi0063"));
list.addElement(new IconItem("wi0064"));
list.addElement(new IconItem("wi0096"));
list.addElement(new IconItem("wi0111"));
list.addElement(new IconItem("wi0122"));
list.addElement(new IconItem("wi0124"));
return list;
}
private static <E extends IconItem> TableModel makeIconTableModel(ListModel<E> list) {
Object[][] data = {
{list.getElementAt(0), list.getElementAt(1), list.getElementAt(2)},
{list.getElementAt(3), list.getElementAt(4), list.getElementAt(5)},
{list.getElementAt(6), list.getElementAt(7), list.getElementAt(8)}
};
return new DefaultTableModel(data, null) {
@Override public boolean isCellEditable(int row, int column) {
return false;
}
@Override public int getColumnCount() {
return 3;
}
};
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class IconItem {
public final ImageIcon large;
public final ImageIcon small;
protected IconItem(String str) {
large = new ImageIcon(getClass().getResource(str + "-48.png"));
small = new ImageIcon(getClass().getResource(str + "-24.png"));
}
}
class IconTableCellRenderer extends DefaultTableCellRenderer {
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setIcon(((IconItem) value).large);
setHorizontalAlignment(SwingConstants.CENTER);
return this;
}
}
class IconTable extends JTable {
protected static final int OFFSET = 4;
protected final JList<IconItem> editor;
protected final JComponent glassPane = new JComponent() {
@Override public void setVisible(boolean flag) {
super.setVisible(flag);
setFocusTraversalPolicyProvider(flag);
setFocusCycleRoot(flag);
}
@Override protected void paintComponent(Graphics g) {
g.setColor(new Color(0x64_FF_FF_FF, true));
g.fillRect(0, 0, getWidth(), getHeight());
BufferedImage buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = buffer.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .15f));
g2.setPaint(Color.BLACK);
Rectangle r = editor.getBounds();
for (int i = 0; i < OFFSET; i++) {
g2.fillRoundRect(r.x - i, r.y + OFFSET, r.width + i + i, r.height - OFFSET + i, 5, 5);
}
g2.dispose();
g.drawImage(buffer, 0, 0, this);
}
};
protected IconTable(TableModel model, ListModel<IconItem> list) {
super(model);
setDefaultRenderer(Object.class, new IconTableCellRenderer());
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
initCellSize(50);
addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
startEditing();
}
});
editor = new EditorFromList<>(list);
editor.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel-editing");
editor.getActionMap().put("cancel-editing", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
cancelEditing();
}
});
// editor.addKeyListener(new KeyAdapter() {
// @Override public void keyPressed(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
// cancelEditing();
editor.addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
IconItem item = editor.getModel().getElementAt(editor.locationToIndex(p));
setValueAt(item, getSelectedRow(), getSelectedColumn());
cancelEditing();
}
});
glassPane.addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
// Point pt = e.getPoint();
// if (!editor.getBounds().contains(pt)) {
// cancelEditing();
cancelEditing();
}
});
glassPane.setFocusTraversalPolicy(new DefaultFocusTraversalPolicy() {
@Override public boolean accept(Component c) {
return Objects.equals(c, editor);
}
});
glassPane.add(editor);
glassPane.setVisible(false);
}
public void initCellSize(int size) {
setRowHeight(size);
JTableHeader tableHeader = getTableHeader();
tableHeader.setResizingAllowed(false);
tableHeader.setReorderingAllowed(false);
TableColumnModel m = getColumnModel();
for (int i = 0; i < m.getColumnCount(); i++) {
TableColumn col = m.getColumn(i);
col.setMinWidth(size);
col.setMaxWidth(size);
}
setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public void startEditing() {
getRootPane().setGlassPane(glassPane);
Dimension d = editor.getPreferredSize();
editor.setSize(d);
int sr = getSelectedRow();
int sc = getSelectedColumn();
Rectangle r = getCellRect(sr, sc, true);
Point p = SwingUtilities.convertPoint(this, r.getLocation(), glassPane);
p.translate((r.width - d.width) / 2, (r.height - d.height) / 2);
editor.setLocation(p);
glassPane.setVisible(true);
editor.setSelectedValue(getValueAt(sr, sc), true);
editor.requestFocusInWindow();
}
protected void cancelEditing() {
glassPane.setVisible(false);
}
}
class EditorFromList<E extends IconItem> extends JList<E> {
private static final int INS = 2;
private final Dimension dim;
private transient RollOverListener handler;
protected int rollOverRowIndex = -1;
protected EditorFromList(ListModel<E> model) {
super(model);
ImageIcon icon = model.getElementAt(0).small;
int iw = INS + icon.getIconWidth();
int ih = INS + icon.getIconHeight();
dim = new Dimension(iw * 3 + INS, ih * 3 + INS);
setFixedCellWidth(iw);
setFixedCellHeight(ih);
}
@Override public Dimension getPreferredSize() {
return dim;
}
@Override public void updateUI() {
removeMouseMotionListener(handler);
removeMouseListener(handler);
super.updateUI();
handler = new RollOverListener();
addMouseMotionListener(handler);
addMouseListener(handler);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setLayoutOrientation(JList.HORIZONTAL_WRAP);
setVisibleRowCount(0);
JLabel renderer = new JLabel();
Color selectedColor = new Color(0xC8_C8_FF);
setCellRenderer((list, value, index, isSelected, cellHasFocus) -> {
renderer.setOpaque(true);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
if (index == rollOverRowIndex) {
renderer.setBackground(getSelectionBackground());
} else if (isSelected) {
renderer.setBackground(selectedColor);
} else {
renderer.setBackground(getBackground());
}
renderer.setIcon(value.small);
return renderer;
});
}
private class RollOverListener extends MouseAdapter {
@Override public void mouseExited(MouseEvent e) {
rollOverRowIndex = -1;
repaint();
}
@Override public void mouseMoved(MouseEvent e) {
int row = locationToIndex(e.getPoint());
if (row != rollOverRowIndex) {
rollOverRowIndex = row;
repaint();
}
}
}
}
|
package org.openprovenance.prov.interop;
import javax.ws.rs.core.MediaType;
/** Definition of all Media Types and file Extensions supported by ProvToolbox. */
public interface InteropMediaType {
public static final String EXTENSION_DOT = "dot";
public static final String EXTENSION_JPEG = "jpeg";
public static final String EXTENSION_JPG = "jpg";
public static final String EXTENSION_JSON = "json";
public static final String EXTENSION_PDF = "pdf";
public static final String EXTENSION_PROVN = "provn";
public static final String EXTENSION_PROVX = "provx";
public static final String EXTENSION_RDF = "rdf";
public static final String EXTENSION_SVG = "svg";
public static final String EXTENSION_TRIG = "trig";
public static final String EXTENSION_TTL = "ttl";
/** The extension for XML files. */
public static final String EXTENSION_XML = "xml";
public static final String MEDIA_APPLICATION_FORM_URLENCODED = MediaType.APPLICATION_FORM_URLENCODED;
public static final String MEDIA_APPLICATION_JSON = MediaType.APPLICATION_JSON;
public static final String MEDIA_APPLICATION_PDF = "application/pdf";
public static final String MEDIA_APPLICATION_PROVENANCE_XML = "application/provenance+xml";
public static final String MEDIA_APPLICATION_RDF_XML = "application/rdf+xml";
public static final String MEDIA_APPLICATION_XML = MediaType.APPLICATION_XML;
public static final String MEDIA_APPLICATION_TRIG = "application/trig";
public static final String MEDIA_IMAGE_JPEG = "image/jpeg";
public static final String MEDIA_IMAGE_SVG_XML = "image/svg+xml";
public static final String MEDIA_TEXT_HTML = MediaType.TEXT_HTML;
public static final String MEDIA_TEXT_PLAIN = MediaType.TEXT_PLAIN;
public static final String MEDIA_TEXT_PROVENANCE_NOTATION = "text/provenance-notation";
public static final String MEDIA_TEXT_TURTLE = "text/turtle";
public static final String MEDIA_TEXT_VND_GRAPHVIZ = "text/vnd.graphviz";
public static final String MEDIA_TEXT_XML = MediaType.TEXT_XML;
/**
* All Media Types accepted as input for PROV.
*/
public final static String[] ALL_PROV_INPUT_MEDIA_TYPES = new String[] {
MEDIA_TEXT_TURTLE, MEDIA_TEXT_PROVENANCE_NOTATION,
MEDIA_APPLICATION_PROVENANCE_XML, MEDIA_APPLICATION_TRIG,
MEDIA_APPLICATION_RDF_XML, MEDIA_APPLICATION_JSON,
MEDIA_APPLICATION_PDF };
public static final String[] ALL_PROV_OUTPUT_MEDIA_TYPES = new String[] {
MEDIA_TEXT_TURTLE, MEDIA_TEXT_PROVENANCE_NOTATION,
MEDIA_APPLICATION_PROVENANCE_XML, MEDIA_APPLICATION_TRIG,
MEDIA_APPLICATION_RDF_XML, MEDIA_APPLICATION_JSON,
MEDIA_IMAGE_SVG_XML, MEDIA_APPLICATION_PDF };
}
|
package linkedList;
import java.io.DataInputStream;
import java.io.IOException;
public class DoubleLinkedList<E> {
private Node<E> head ,tail;
public void add(E item){
if(head == null){
Node<E> node = new Node<E>(item);
head = node ;
tail = node;
}else{
Node<E> node = new Node<E>(item);
tail.next = node;
node.prev = tail.next;
tail = node;
}
}
public E delete(E item){
Node temp = head ;
while (temp != null){
if(temp.item.equals(item) && temp.prev == null){
head = temp.next.prev;
}
if(temp.item.equals(item) && temp.next != null && temp.prev != null){
/* temp.prev.next = temp.next;
temp.next.prev = temp.prev;*/
temp.item = null;
}
if(temp.next == null && temp.item.equals(item)){
tail = temp.prev;
temp.item = null;
break;
}
temp = temp.next;
}
return item;
}
public void search(E item){
Node temp = head;
while (temp != null){
if(temp.item.equals(item))
break;
temp = temp.next;
}
}
public void display(){
Node temp = head;
while (temp != null){
System.out.print(temp.item + ",");
temp = temp.next;
}
}
private static class Node<E>{
private Node<E> next, prev;
private E item ;
public Node(E item ){
this.item = item ;
this.next = null;
this.prev = null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] input = {1,2,4,4,5,6,7};
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
for(int i : input){
list.add(i);
}
System.out.print("Item inserted in list are :");
list.display();
DataInputStream dis = new DataInputStream(System.in);
System.out.println();
System.out.println("Enter item to be delete ");
try {
System.out.println(list.delete(Integer.parseInt(dis.readLine())));
System.out.println("After deleting item list : ");
list.display();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package org.jetbrains.plugins.ruby.ruby.actions;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.execution.Executor;
import com.intellij.execution.ExecutorRegistry;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ChooseRunConfigurationPopup;
import com.intellij.execution.actions.ExecutorProvider;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.laf.darcula.ui.DarculaTextBorder;
import com.intellij.ide.ui.laf.intellij.MacIntelliJTextBorder;
import com.intellij.ide.ui.laf.intellij.WinIntelliJTextBorder;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.internal.statistic.customUsageCollectors.ui.ToolbarClicksCollector;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actions.TextComponentEditorAction;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.impl.ModifierKeyDoubleClickHandler;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.ComponentPopupBuilder;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.*;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.util.Alarm;
import com.intellij.util.Consumer;
import com.intellij.util.IconUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.components.BorderLayoutPanel;
import icons.RubyIcons;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.ruby.RBundle;
import org.jetbrains.plugins.ruby.gem.bundler.actions.AbstractBundlerAction;
import org.jetbrains.plugins.ruby.rails.actions.generators.actions.GeneratorsActionGroup;
import org.jetbrains.plugins.ruby.rails.facet.RailsFacetUtil;
import org.jetbrains.plugins.ruby.ruby.RModuleUtil;
import org.jetbrains.plugins.ruby.tasks.rake.RakeAction;
import org.jetbrains.plugins.ruby.tasks.rake.RakeTaskModuleCache;
import org.jetbrains.plugins.ruby.tasks.rake.task.RakeTask;
import javax.accessibility.Accessible;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.TextUI;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance;
import static org.jetbrains.plugins.ruby.ruby.actions.RunAnythingIconHandler.*;
import static org.jetbrains.plugins.ruby.ruby.actions.RunAnythingUndefinedItem.UNDEFINED_COMMAND_ICON;
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
public class RunAnythingAction extends AnAction implements CustomComponentAction, DumbAware, DataProvider {
public static final String RUN_ANYTHING_HISTORY_KEY = "RunAnythingHistoryKey";
public static final int SEARCH_FIELD_COLUMNS = 25;
public static final String UNKNOWN_CONFIGURATION = "UNKNOWN_CONFIGURATION";
public static final String RUN_ICON_TEXT = "RUN_ICON_TEXT";
public static final AtomicBoolean ourShiftIsPressed = new AtomicBoolean(false);
public static final AtomicBoolean ourAltIsPressed = new AtomicBoolean(false);
public static final Key<JBPopup> RUN_ANYTHING_POPUP = new Key<>("RunAnythingPopup");
public static final String RUN_ANYTHING_ACTION_ID = "RunAnything";
private static final int MAX_RAKE = 5;
private static final int MAX_RUN_CONFIGURATION = 6;
private static final int MAX_BUNDLER_ACTIONS = 2;
private static final int MAX_UNDEFINED_FILES = 5;
private static final int MAX_RUN_ANYTHING_HISTORY = 50;
private static final int MAX_GENERATORS = 3;
private static final int DEFAULT_MORE_STEP_COUNT = 5;
private static final Logger LOG = Logger.getInstance(RunAnythingAction.class);
private static final Border RENDERER_BORDER = JBUI.Borders.empty(1, 0);
private static final String SHIFT_SHORTCUT_TEXT = KeymapUtil.getShortcutText(KeyboardShortcut.fromString(("SHIFT")));
private static final String AD_ACTION_TEXT = String.format("Press %s to run with default settings", SHIFT_SHORTCUT_TEXT);
private static final String AD_DEBUG_TEXT = String.format("%s to debug", SHIFT_SHORTCUT_TEXT);
private static final String AD_MODULE_CONTEXT =
String.format("Press %s to run in the current file context", KeymapUtil.getShortcutText(KeyboardShortcut.fromString("pressed ALT")));
private static final Icon RUN_ANYTHING_BRIGHTER_ICON = IconUtil.brighter(RubyIcons.RunAnything.Run_anything, 2);
private AnAction[] myRakeActions = AnAction.EMPTY_ARRAY;
private AnAction[] myGeneratorsActions = AnAction.EMPTY_ARRAY;
private RunAnythingAction.MyListRenderer myRenderer;
private MySearchTextField myPopupField;
private Component myFocusComponent;
private JBPopup myPopup;
private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, ApplicationManager.getApplication());
private JBList myList;
private AnActionEvent myActionEvent;
private Component myContextComponent;
private CalcThread myCalcThread;
private volatile ActionCallback myCurrentWorker = ActionCallback.DONE;
private int myCalcThreadRestartRequestId = 0;
private final Object myWorkerRestartRequestLock = new Object();
private int myHistoryIndex = 0;
private boolean mySkipFocusGain = false;
private volatile JBPopup myBalloon;
private int myPopupActualWidth;
private Component myFocusOwner;
private Editor myEditor;
@Nullable
private FileEditor myFileEditor;
private RunAnythingHistoryItem myHistoryItem;
private AnAction[] myBundlerActions;
private JLabel myAdComponent;
private DataContext myDataContext;
private static final NotNullLazyValue<Map<String, Icon>> ourIconsMap;
private JLabel myTextFieldTitle;
static {
ModifierKeyDoubleClickHandler.getInstance().registerAction(RUN_ANYTHING_ACTION_ID, KeyEvent.VK_CONTROL, -1, false);
ourIconsMap = new NotNullLazyValue<Map<String, Icon>>() {
@NotNull
@Override
protected Map<String, Icon> compute() {
Map<String, Icon> map = ContainerUtil.newHashMap();
map.put(UNKNOWN_CONFIGURATION, UNDEFINED_COMMAND_ICON);
for (RunAnythingProvider provider : RunAnythingProvider.EP_NAME.getExtensions()) {
map.put(provider.getConfigurationFactory().getName(), provider.getConfigurationFactory().getIcon());
}
return map;
}
};
IdeEventQueue.getInstance().addPostprocessor(event -> {
if (event instanceof KeyEvent) {
final int keyCode = ((KeyEvent)event).getKeyCode();
if (keyCode == KeyEvent.VK_SHIFT) {
ourShiftIsPressed.set(event.getID() == KeyEvent.KEY_PRESSED);
}
else if (keyCode == KeyEvent.VK_ALT) {
ourAltIsPressed.set(event.getID() == KeyEvent.KEY_PRESSED);
}
}
return false;
}, null);
}
@Override
public JComponent createCustomComponent(Presentation presentation) {
JPanel panel = new BorderLayoutPanel() {
@Override
public Dimension getPreferredSize() {
return JBUI.size(25);
}
};
panel.setOpaque(false);
final JLabel label = new JBLabel(RubyIcons.RunAnything.Run_anything) {
{
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
};
panel.add(label, BorderLayout.CENTER);
RunAnythingUtil.initTooltip(label);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (myBalloon != null) {
myBalloon.cancel();
}
myFocusOwner = IdeFocusManager.findInstance().getFocusOwner();
label.setToolTipText(null);
IdeTooltipManager.getInstance().hideCurrentNow(false);
ActionToolbarImpl toolbar = UIUtil.getParentOfType(ActionToolbarImpl.class, panel);
if (toolbar != null) {
ToolbarClicksCollector.record(RunAnythingAction.this, toolbar.getPlace());
}
actionPerformed(null, e);
}
@Override
public void mouseEntered(MouseEvent e) {
if (myBalloon == null || myBalloon.isDisposed()) {
label.setIcon(RUN_ANYTHING_BRIGHTER_ICON);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (myBalloon == null || myBalloon.isDisposed()) {
label.setIcon(RubyIcons.RunAnything.Run_anything);
}
}
});
return panel;
}
private void updateComponents() {
//noinspection unchecked
myList = new JBList(new RunAnythingSearchListModel()) {
int lastKnownHeight = JBUI.scale(30);
@Override
public Dimension getPreferredSize() {
final Dimension size = super.getPreferredSize();
if (size.height == -1) {
size.height = lastKnownHeight;
}
else {
lastKnownHeight = size.height;
}
int width = myBalloon != null ? myBalloon.getSize().width : 0;
return new Dimension(Math.max(width, Math.min(size.width - 2, RunAnythingUtil.getPopupMaxWidth())),
myList.isEmpty() ? JBUI.scale(30) : size.height);
}
@Override
public void clearSelection() {
//avoid blinking
}
@Override
public Object getSelectedValue() {
try {
return super.getSelectedValue();
}
catch (Exception e) {
return null;
}
}
};
myRenderer = new MyListRenderer();
myList.setCellRenderer(myRenderer);
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent event, int clickCount) {
if (clickCount > 1 && clickCount % 2 == 0 || tryGetSettingsModel() != null) {
event.consume();
final int i = myList.locationToIndex(event.getPoint());
if (i != -1) {
getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(getField(), true));
ApplicationManager.getApplication().invokeLater(() -> {
myList.setSelectedIndex(i);
executeCommand();
});
}
}
return false;
}
}.installOn(myList);
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
return null;
}
private void initSearchField(final MySearchTextField search) {
final JTextField editor = search.getTextEditor();
// onFocusLost();
editor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
final String pattern = editor.getText();
if (editor.hasFocus()) {
rebuildList(pattern);
}
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if (mySkipFocusGain) {
mySkipFocusGain = false;
return;
}
String text = RunAnythingUtil.getInitialTextForNavigation(myEditor);
text = text != null ? text.trim() : "";
search.setText(text);
search.getTextEditor().setForeground(UIUtil.getLabelForeground());
search.selectText();
editor.setColumns(SEARCH_FIELD_COLUMNS);
myFocusComponent = e.getOppositeComponent();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> {
final JComponent parent = (JComponent)editor.getParent();
parent.revalidate();
parent.repaint();
});
rebuildList(text);
}
@Override
public void focusLost(FocusEvent e) {
if (myPopup instanceof AbstractPopup && myPopup.isVisible()
&& ((myList == e.getOppositeComponent()) || ((AbstractPopup)myPopup).getPopupWindow() == e.getOppositeComponent())) {
return;
}
onPopupFocusLost();
}
});
}
@NotNull
private ActionCallback onPopupFocusLost() {
final ActionCallback result = new ActionCallback();
//noinspection SSBasedInspection
UIUtil.invokeLaterIfNeeded(() -> {
try {
if (myCalcThread != null) {
myCalcThread.cancel();
//myCalcThread = null;
}
myAlarm.cancelAllRequests();
if (myBalloon != null && !myBalloon.isDisposed() && myPopup != null && !myPopup.isDisposed()) {
myBalloon.cancel();
myPopup.cancel();
}
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> ActionToolbarImpl.updateAllToolbarsImmediately());
}
finally {
result.setDone();
}
});
return result;
}
private SearchTextField getField() {
return myPopupField;
}
private void executeCommand() {
final String pattern = getField().getText();
int index = myList.getSelectedIndex();
//do nothing on attempt to execute empty command
if (pattern.isEmpty() && index == -1) return;
final Project project = getProject();
final Module module = getModule();
if (index != -1) {
final RunAnythingSearchListModel model = tryGetSearchingModel(myList);
if (model != null) {
if (isMoreItem(index)) {
WidgetID wid = null;
if (index == model.moreIndex.permanentRunConfigurations) {
wid = WidgetID.PERMANENT;
}
else if (index == model.moreIndex.rakeTasks) {
wid = WidgetID.RAKE;
}
else if (index == model.moreIndex.generators) {
wid = WidgetID.GENERATORS;
}
else if (index == model.moreIndex.bundlerActions) {
wid = WidgetID.BUNDLER;
}
else if (index == model.moreIndex.temporaryRunConfigurations) {
wid = WidgetID.TEMPORARY;
}
else if (index == model.moreIndex.undefined) {
wid = WidgetID.UNDEFINED;
}
if (wid != null) {
final WidgetID widgetID = wid;
myCurrentWorker.doWhenProcessed(() -> {
myCalcThread = new CalcThread(project, pattern, true);
myPopupActualWidth = 0;
myCurrentWorker = myCalcThread.insert(index, widgetID);
});
return;
}
}
}
}
final Object value = myList.getSelectedValue();
saveHistory(project, pattern, value);
IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(getField().getTextEditor());
if (myPopup != null && myPopup.isVisible()) {
myPopup.cancel();
}
if (value instanceof BooleanOptionDescription) {
updateOption((BooleanOptionDescription)value);
return;
}
Runnable onDone = null;
AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
try {
if (isActionValue(value) || isRunConfigurationItem(value)) {
focusManager.requestDefaultFocus(true);
final Component comp = myContextComponent;
final AnActionEvent event = myActionEvent;
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> {
Component c = comp;
if (c == null) {
c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
}
if (isRunConfigurationItem(value)) {
ChooseRunConfigurationPopup.ItemWrapper itemWrapper = (ChooseRunConfigurationPopup.ItemWrapper)value;
RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(itemWrapper.getValue(), RunnerAndConfigurationSettings.class);
if (settings != null) {
Executor executor = RunAnythingUtil.findExecutor(settings);
if (executor != null) {
itemWrapper.perform(project, executor, DataManager.getInstance().getDataContext(c));
}
}
}
else {
RunAnythingUtil.performRunAnythingAction(value, project, c, event);
}
});
return;
}
VirtualFile directory = getWorkDirectory(module);
if (value instanceof RunAnythingUndefinedItem) {
onDone = () -> ((RunAnythingUndefinedItem)value).run(RunAnythingUtil.getExecutor(), directory);
}
else if (value == null) {
onDone = () -> RunAnythingUtil.runOrCreateRunConfiguration(project, pattern, module, directory);
return;
}
}
finally {
token.finish();
final ActionCallback callback = onPopupFocusLost();
if (onDone != null) {
callback.doWhenDone(onDone);
}
}
focusManager.requestDefaultFocus(true);
}
@NotNull
private Project getProject() {
final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(getField().getTextEditor()));
assert project != null;
return project;
}
@Nullable
private Module getModule() {
return RModuleUtil.getInstance().getModule(myDataContext);
}
@Nullable
private VirtualFile getWorkDirectory(@Nullable Module module) {
if (module == null) return null;
VirtualFile workDirectory = RModuleUtil.getInstance().getFirstContentRoot(module);
if (myFileEditor == null) return workDirectory;
VirtualFile file = myFileEditor.getFile();
if (file == null) return workDirectory;
if (ourAltIsPressed.get()) {
workDirectory = file.getParent();
}
return workDirectory;
}
private void updateOption(BooleanOptionDescription value) {
value.setOptionState(!value.isOptionEnabled());
myList.revalidate();
myList.repaint();
getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(getField(), true));
}
private boolean isMoreItem(int index) {
RunAnythingSearchListModel model = tryGetSearchingModel(myList);
if (model == null) return false;
return index == model.moreIndex.permanentRunConfigurations ||
index == model.moreIndex.rakeTasks ||
index == model.moreIndex.bundlerActions ||
index == model.moreIndex.generators ||
index == model.moreIndex.undefined ||
index == model.moreIndex.temporaryRunConfigurations;
}
@Nullable
public static RunAnythingSearchListModel tryGetSearchingModel(@NotNull JBList list) {
ListModel model = list.getModel();
return model instanceof RunAnythingSearchListModel ? (RunAnythingSearchListModel)model : null;
}
@Nullable
private RunAnythingSettingsModel tryGetSettingsModel() {
ListModel model = myList.getModel();
return model instanceof RunAnythingSettingsModel ? (RunAnythingSettingsModel)model : null;
}
private void rebuildList(final String pattern) {
assert EventQueue.isDispatchThread() : "Must be EDT";
if (myCalcThread != null && !myCurrentWorker.isProcessed()) {
myCurrentWorker = myCalcThread.cancel();
}
if (myCalcThread != null && !myCalcThread.isCanceled()) {
myCalcThread.cancel();
}
synchronized (myWorkerRestartRequestLock) { // this lock together with RestartRequestId should be enough to prevent two CalcThreads running at the same time
final int currentRestartRequest = ++myCalcThreadRestartRequestId;
myCurrentWorker.doWhenProcessed(() -> {
synchronized (myWorkerRestartRequestLock) {
if (currentRestartRequest != myCalcThreadRestartRequestId) {
return;
}
myCalcThread = new CalcThread(getProject(), pattern, false);
myPopupActualWidth = 0;
myCurrentWorker = myCalcThread.start();
}
});
}
}
@Override
public void actionPerformed(AnActionEvent e) {
if (Registry.is("ide.suppress.double.click.handler") && e.getInputEvent() instanceof KeyEvent) {
if (((KeyEvent)e.getInputEvent()).getKeyCode() == KeyEvent.VK_CONTROL) {
return;
}
}
actionPerformed(e, null);
}
public void actionPerformed(AnActionEvent e, MouseEvent me) {
if (myBalloon != null && myBalloon.isVisible()) {
rebuildList(myPopupField.getText());
return;
}
myCurrentWorker = ActionCallback.DONE;
if (e != null) {
myEditor = e.getData(CommonDataKeys.EDITOR);
myFileEditor = e.getData(PlatformDataKeys.FILE_EDITOR);
}
if (e == null && myFocusOwner != null) {
e = AnActionEvent.createFromAnAction(this, me, ActionPlaces.UNKNOWN, DataManager.getInstance().getDataContext(myFocusOwner));
}
if (e == null) return;
final Project project = e.getProject();
if (project == null) return;
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> LookupManager.getInstance(project).hideActiveLookup());
updateComponents();
myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext());
Window wnd = myContextComponent != null ? SwingUtilities.windowForComponent(myContextComponent)
: KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
if (wnd == null && myContextComponent instanceof Window) {
wnd = (Window)myContextComponent;
}
if (wnd == null || wnd.getParent() != null) return;
myActionEvent = e;
Module module = RModuleUtil.getInstance().getModule(myActionEvent.getDataContext());
myDataContext = SimpleDataContext.getSimpleContext(LangDataKeys.MODULE.getName(), module);
initActions();
if (myPopupField != null) {
Disposer.dispose(myPopupField);
}
myPopupField = new MySearchTextField();
myPopupField.setPreferredSize(new Dimension(500, 43));
myPopupField.getTextEditor().setFont(EditorUtil.getEditorFont().deriveFont(18f));
JBTextField myTextField = myPopupField.getTextEditor();
myTextField.putClientProperty(MATCHED_CONFIGURATION_PROPERTY, UNKNOWN_CONFIGURATION);
setHandleMatchedConfiguration(myTextField);
myTextField.setMinimumSize(new Dimension(500, 50));
myTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_SHIFT:
myTextFieldTitle.setText(RBundle.message("run.anything.run.debug.title"));
break;
case KeyEvent.VK_ALT:
myTextFieldTitle.setText(RBundle.message("run.anything.run.in.context.title"));
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_SHIFT:
myTextFieldTitle.setText(RBundle.message("run.anything.run.anything.title"));
break;
case KeyEvent.VK_ALT:
myTextFieldTitle.setText(RBundle.message("run.anything.run.anything.title"));
break;
}
}
});
myPopupField.getTextEditor().addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
myHistoryIndex = 0;
myHistoryItem = null;
}
});
initSearchField(myPopupField);
JTextField editor = myPopupField.getTextEditor();
editor.setColumns(SEARCH_FIELD_COLUMNS);
JPanel panel = new JPanel(new BorderLayout());
myTextFieldTitle = new JLabel(RBundle.message("run.anything.run.anything.title"));
JPanel topPanel = new NonOpaquePanel(new BorderLayout());
Color foregroundColor = UIUtil.isUnderDarcula()
? UIUtil.isUnderWin10LookAndFeel() ? JBColor.WHITE : new JBColor(Gray._240, Gray._200)
: UIUtil.getLabelForeground();
myTextFieldTitle.setForeground(foregroundColor);
myTextFieldTitle.setBorder(BorderFactory.createEmptyBorder(3, 5, 5, 0));
if (SystemInfo.isMac) {
myTextFieldTitle.setFont(myTextFieldTitle.getFont().deriveFont(Font.BOLD, myTextFieldTitle.getFont().getSize() - 1f));
} else {
myTextFieldTitle.setFont(myTextFieldTitle.getFont().deriveFont(Font.BOLD));
}
topPanel.add(myTextFieldTitle, BorderLayout.WEST);
JPanel controls = new JPanel(new BorderLayout());
controls.setOpaque(false);
JLabel settings = new JLabel(AllIcons.General.GearPlain);
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent event, int clickCount) {
showSettings();
return true;
}
}.installOn(settings);
settings.setBorder(UIUtil.isUnderWin10LookAndFeel() ? JBUI.Borders.emptyLeft(6) : JBUI.Borders.empty());
controls.add(settings, BorderLayout.EAST);
controls.setBorder(UIUtil.isUnderWin10LookAndFeel() ? JBUI.Borders.emptyTop(1) : JBUI.Borders.empty());
topPanel.add(controls, BorderLayout.EAST);
panel.add(myPopupField, BorderLayout.CENTER);
panel.add(topPanel, BorderLayout.NORTH);
panel.setBorder(JBUI.Borders.empty(3, 5, 4, 5));
myAdComponent = HintUtil.createAdComponent(AD_MODULE_CONTEXT, JBUI.Borders.empty(1, 5), SwingConstants.LEFT);
panel.add(myAdComponent, BorderLayout.SOUTH);
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
updateAdText();
}
});
DataManager.registerDataProvider(panel, this);
final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor);
myBalloon = builder
.setCancelOnClickOutside(true)
.setModalContext(false)
.setRequestFocus(true)
.setCancelCallback(() -> !mySkipFocusGain)
.createPopup();
myBalloon.getContent().setBorder(JBUI.Borders.empty());
final Window window = WindowManager.getInstance().suggestParentWindow(project);
project.getMessageBus().connect(myBalloon).subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
@Override
public void enteredDumbMode() {
}
@Override
public void exitDumbMode() {
ApplicationManager.getApplication().invokeLater(() -> rebuildList(myPopupField.getText()));
}
});
Component parent = UIUtil.findUltimateParent(window);
final RelativePoint showPoint;
if (parent != null) {
int height = UISettings.getInstance().getShowMainToolbar() ? 135 : 115;
if (parent instanceof IdeFrameImpl && ((IdeFrameImpl)parent).isInFullScreen()) {
height -= 20;
}
showPoint = new RelativePoint(parent, new Point((parent.getSize().width - panel.getPreferredSize().width) / 2, height));
}
else {
showPoint = JBPopupFactory.getInstance().guessBestPopupLocation(e.getDataContext());
}
myList.setFont(UIUtil.getListFont());
myBalloon.show(showPoint);
initSearchActions(myBalloon, myPopupField);
IdeFocusManager focusManager = IdeFocusManager.getInstance(project);
focusManager.requestFocus(editor, true);
FeatureUsageTracker.getInstance().triggerFeatureUsed(RunAnythingUtil.RUN_ANYTHING);
}
private void setHandleMatchedConfiguration(JBTextField textField) {
textField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
String pattern;
try {
pattern = e.getDocument().getText(0, e.getDocument().getLength());
}
catch (BadLocationException e1) {
LOG.error(e1);
return;
}
String name = null;
for (RunAnythingProvider provider : RunAnythingProvider.EP_NAME.getExtensions()) {
if (provider.isMatched(getProject(), pattern, getWorkDirectory(getModule()))) {
name = provider.getConfigurationFactory().getName();
}
}
if (name != null) {
textField.putClientProperty(MATCHED_CONFIGURATION_PROPERTY, name);
setAdText(AD_MODULE_CONTEXT + ", " + AD_DEBUG_TEXT);
}
else {
textField.putClientProperty(MATCHED_CONFIGURATION_PROPERTY, UNKNOWN_CONFIGURATION);
}
}
});
}
private void updateAdText() {
Object value = myList.getSelectedValue();
String text = AD_MODULE_CONTEXT;
if (isRunConfigurationItem(value)) {
text += " , " + AD_DEBUG_TEXT;
}
else if (isActionValue(value)) {
text = AD_ACTION_TEXT;
}
setAdText(text);
}
private void initActions() {
myBundlerActions = Stream.of(((DefaultActionGroup)ActionManager.getInstance().getAction("BUNDLER_ACTIONS")).getChildren(myActionEvent))
.filter(action -> action instanceof AbstractBundlerAction).toArray(AnAction[]::new);
//todo move to EP
Module myModule = getModule();
if (myModule != null && RailsFacetUtil.hasRailsSupport(myModule)) {
RakeTask rakeTasks = RakeTaskModuleCache.getInstance(myModule).getRakeTasks();
if (rakeTasks != null) {
myRakeActions = Arrays.stream(RakeTaskModuleCache.getInstance(myModule).getRakeActions())
.filter(RakeAction.class::isInstance)
.map(RakeAction.class::cast)
.filter(action -> {
RakeTask task = action.getTask(myModule);
return task != null && task.isDescriptionProvided();
})
.peek(rakeAction -> rakeAction.updateAction(myDataContext, rakeAction.getTemplatePresentation()))
.toArray(AnAction[]::new);
}
myGeneratorsActions = GeneratorsActionGroup.collectGeneratorsActions(myModule, false).toArray(AnAction.EMPTY_ARRAY);
}
}
private void showSettings() {
myPopupField.setText("");
final RunAnythingSettingsModel model = new RunAnythingSettingsModel();
model.addElement(new RunAnythingSEOption("Show generators", "run.anything.generators"));
model.addElement(new RunAnythingSEOption("Show rake tasks", "run.anything.rake.tasks"));
model.addElement(new RunAnythingSEOption("Show bundler actions", "run.anything.bundler.actions"));
model.addElement(new RunAnythingSEOption("Show permanent run configurations", "run.anything.permanent.configurations"));
model.addElement(new RunAnythingSEOption("Show temporary run configurations", "run.anything.temporary.configurations"));
model.addElement(new RunAnythingSEOption("Show undefined command ", "run.anything.undefined.commands"));
if (myCalcThread != null && !myCurrentWorker.isProcessed()) {
myCurrentWorker = myCalcThread.cancel();
}
if (myCalcThread != null && !myCalcThread.isCanceled()) {
myCalcThread.cancel();
}
myCurrentWorker.doWhenProcessed(() -> {
myList.setModel(model);
updatePopupBounds();
});
}
private static void saveHistory(Project project, String text, Object value) {
if (project == null || project.isDisposed() || !project.isInitialized()) {
return;
}
HistoryType type = null;
String fqn = null;
if (isActionValue(value)) {
type = HistoryType.ACTION;
fqn = ActionManager.getInstance().getId((AnAction)value);
}
else if (isRunConfigurationItem(value)) {
type = HistoryType.RUN_CONFIGURATION;
fqn = ((ChooseRunConfigurationPopup.ItemWrapper)value).getText();
}
final PropertiesComponent storage = PropertiesComponent.getInstance(project);
final String[] values = storage.getValues(RUN_ANYTHING_HISTORY_KEY);
List<RunAnythingHistoryItem> history = new ArrayList<>();
if (values != null) {
for (String s : values) {
final String[] split = s.split("\t");
if (split.length != 3 || text.equals(split[0])) {
continue;
}
if (!StringUtil.isEmpty(split[0])) {
history.add(new RunAnythingHistoryItem(split[0], split[1], split[2]));
}
}
}
history.add(0, new RunAnythingHistoryItem(text, type == null ? null : type.name(), fqn));
if (history.size() > MAX_RUN_ANYTHING_HISTORY) {
history = history.subList(0, MAX_RUN_ANYTHING_HISTORY);
}
final String[] newValues = new String[history.size()];
for (int i = 0; i < newValues.length; i++) {
newValues[i] = history.get(i).toString();
}
storage.setValues(RUN_ANYTHING_HISTORY_KEY, newValues);
}
private void initSearchActions(@NotNull JBPopup balloon, @NotNull MySearchTextField searchTextField) {
final JTextField editor = searchTextField.getTextEditor();
DumbAwareAction.create(e -> RunAnythingUtil.jumpNextGroup(true, myList))
.registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), editor, balloon);
DumbAwareAction.create(e -> RunAnythingUtil.jumpNextGroup(false, myList))
.registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), editor, balloon);
AnAction escape = ActionManager.getInstance().getAction("EditorEscape");
DumbAwareAction.create(e -> {
if (myBalloon != null && myBalloon.isVisible()) {
myBalloon.cancel();
}
if (myPopup != null && myPopup.isVisible()) {
myPopup.cancel();
}
}).registerCustomShortcutSet(escape == null ? CommonShortcuts.ESCAPE : escape.getShortcutSet(), editor, balloon);
DumbAwareAction.create(e -> executeCommand())
.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER", "shift ENTER", "alt ENTER", "meta ENTER"), editor, balloon);
DumbAwareAction.create(e -> {
//todo
RunAnythingSearchListModel model = tryGetSearchingModel(myList);
if (model == null) return;
Object selectedValue = myList.getSelectedValue();
if (!(selectedValue instanceof RunAnythingUndefinedItem)) return;
RunAnythingCache.getInstance(getProject()).getState().undefinedCommands.remove(((RunAnythingUndefinedItem)selectedValue).getText());
int shift = -1;
int index = myList.getSelectedIndex();
model.remove(index);
RunAnythingMoreIndex moreIndex = model.moreIndex;
model.titleIndex.shift(index, shift);
moreIndex.shift(index, shift);
if (model.size() > 0) ScrollingUtil.selectItem(myList, index < model.size() ? index : index - 1);
updatePopupBounds();
}).registerCustomShortcutSet(CustomShortcutSet.fromString("shift BACK_SPACE"), editor, balloon);
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
final PropertiesComponent storage = PropertiesComponent.getInstance(e.getProject());
final String[] values = storage.getValues(RUN_ANYTHING_HISTORY_KEY);
if (values != null) {
if (values.length > myHistoryIndex) {
final List<String> data = StringUtil.split(values[myHistoryIndex], "\t");
myHistoryItem = new RunAnythingHistoryItem(data.get(0), data.get(1), data.get(2));
myHistoryIndex++;
editor.setText(myHistoryItem.pattern);
editor.setCaretPosition(myHistoryItem.pattern.length());
editor.moveCaretPosition(0);
}
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(editor.getCaretPosition() == 0);
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), editor, balloon);
}
public void setAdText(@NotNull final String s) {
myAdComponent.setText(s);
}
private class MyListRenderer extends ColoredListCellRenderer {
private RunAnythingMyAccessibleComponent myMainPanel = new RunAnythingMyAccessibleComponent(new BorderLayout());
private JLabel myTitle = new JLabel();
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component cmp = null;
String pattern = "*" + myPopupField.getText();
if (isMoreItem(index)) {
cmp = RunAnythingMore.get(isSelected);
}
if (cmp == null) {
if (isActionValue(value)) {
cmp = RunAnythingUtil.getActionCellRendererComponent(((AnAction)value), isSelected);
}
else if (isRunConfigurationItem(value)) {
cmp = RunAnythingUtil.getRunConfigurationCellRendererComponent(((ChooseRunConfigurationPopup.ItemWrapper)value), isSelected);
}
else if (isUndefined(value)) {
cmp = RunAnythingUtil.getUndefinedCommandCellRendererComponent(((RunAnythingUndefinedItem)value), isSelected);
}
else {
cmp = super.getListCellRendererComponent(list, value, index, isSelected, isSelected);
final JPanel p = new JPanel(new BorderLayout());
p.setBackground(UIUtil.getListBackground(isSelected));
p.add(cmp, BorderLayout.CENTER);
cmp = p;
}
if (isSetting(value)) {
final JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(UIUtil.getListBackground(isSelected));
panel.add(cmp, BorderLayout.CENTER);
final Component rightComponent;
final OnOffButton button = new OnOffButton();
button.setSelected(((BooleanOptionDescription)value).isOptionEnabled());
rightComponent = button;
panel.add(rightComponent, BorderLayout.EAST);
JLabel settingLabel = new JLabel(RunAnythingUtil.getSettingText((OptionDescription)value));
settingLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
panel.add(settingLabel, BorderLayout.WEST);
panel.add(rightComponent, BorderLayout.EAST);
cmp = panel;
}
}
Color bg = cmp.getBackground();
if (bg == null) {
cmp.setBackground(UIUtil.getListBackground(isSelected));
bg = cmp.getBackground();
}
myMainPanel.removeAll();
RunAnythingSearchListModel model = tryGetSearchingModel(RunAnythingAction.this.myList);
if (model != null) {
String title = model.titleIndex.getTitle(index);
if (title != null) {
myTitle.setText(title);
myMainPanel.add(RunAnythingUtil.createTitle(" " + title), BorderLayout.NORTH);
}
}
JPanel wrapped = new JPanel(new BorderLayout());
wrapped.setBackground(bg);
wrapped.setBorder(RENDERER_BORDER);
wrapped.add(cmp, BorderLayout.CENTER);
myMainPanel.add(wrapped, BorderLayout.CENTER);
if (cmp instanceof Accessible) {
myMainPanel.setAccessible((Accessible)cmp);
}
final int width = myMainPanel.getPreferredSize().width;
if (width > myPopupActualWidth) {
myPopupActualWidth = width;
//schedulePopupUpdate();
}
return myMainPanel;
}
@Override
protected void customizeCellRenderer(@NotNull JList list, final Object value, int index, final boolean selected, boolean hasFocus) {
}
public void recalculateWidth() {
RunAnythingSearchListModel model = tryGetSearchingModel(RunAnythingAction.this.myList);
if (model == null) return;
myTitle.setIcon(EmptyIcon.ICON_16);
myTitle.setFont(RunAnythingUtil.getTitleFont());
int index = 0;
while (index < model.getSize()) {
String title = model.titleIndex.getTitle(index);
if (title != null) {
myTitle.setText(title);
}
index++;
}
myTitle.setForeground(Gray._122);
myTitle.setAlignmentY(BOTTOM_ALIGNMENT);
}
}
private static boolean isActionValue(Object o) {
return o instanceof AnAction;
}
//todo remain bool options
private static boolean isSetting(Object o) {
return o instanceof BooleanOptionDescription;
}
private static boolean isRunConfigurationItem(Object o) {
return o instanceof ChooseRunConfigurationPopup.ItemWrapper;
}
private static boolean isUndefined(Object o) {
return o instanceof RunAnythingUndefinedItem;
}
enum WidgetID {PERMANENT, RAKE, BUNDLER, TEMPORARY, GENERATORS, UNDEFINED}
@SuppressWarnings({"SSBasedInspection", "unchecked"})
private class CalcThread implements Runnable {
@NotNull private final Project myProject;
@NotNull private final String myPattern;
private final ProgressIndicator myProgressIndicator = new ProgressIndicatorBase();
private final ActionCallback myDone = new ActionCallback();
@NotNull private final RunAnythingSearchListModel myListModel;
@Nullable private final Module myModule;
public CalcThread(@NotNull Project project, @NotNull String pattern, boolean reuseModel) {
myProject = project;
myModule = getModule();
myPattern = pattern;
RunAnythingSearchListModel model = tryGetSearchingModel(RunAnythingAction.this.myList);
myListModel = reuseModel ? model != null ? model : new RunAnythingSearchListModel() : new RunAnythingSearchListModel();
}
@Override
public void run() {
try {
check();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> {
// this line must be called on EDT to avoid context switch at clear().append("text") Don't touch. Ask [kb]
myList.getEmptyText().setText("Searching...");
if (tryGetSearchingModel(myList) != null) {
//noinspection unchecked
myAlarm.cancelAllRequests();
myAlarm.addRequest(() -> {
if (!myDone.isRejected()) {
myList.setModel(myListModel);
updatePopup();
}
}, 50);
}
else {
myList.setModel(myListModel);
}
});
if (myPattern.trim().length() == 0) {
buildModelFromRecentFiles();
buildTemporaryConfigurations("");
//updatePopup();
return;
}
check();
buildRecentUndefined();
runReadAction(() -> buildTemporaryConfigurations(myPattern));
runReadAction(() -> buildPermanentConfigurations(myPattern));
check();
buildGenerators(myPattern);
updatePopup();
check();
buildRakeActions(myPattern);
buildBundlerActions(myPattern);
updatePopup();
}
catch (ProcessCanceledException ignore) {
myDone.setRejected();
}
catch (Exception e) {
LOG.error(e);
myDone.setRejected();
}
finally {
if (!isCanceled()) {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> myList.getEmptyText().setText(RBundle.message("run.command.empty.list.title")));
updatePopup();
}
if (!myDone.isProcessed()) {
myDone.setDone();
}
}
}
private void runReadAction(@NotNull Runnable action) {
runReadAction(action, false);
}
private void runReadAction(@NotNull Runnable action, boolean isPreserveSelection) {
if (!DumbService.getInstance(myProject).isDumb()) {
ApplicationManager.getApplication().runReadAction(action);
updatePopup(isPreserveSelection);
}
}
protected void check() {
myProgressIndicator.checkCanceled();
if (myDone.isRejected()) throw new ProcessCanceledException();
if (myBalloon == null || myBalloon.isDisposed()) throw new ProcessCanceledException();
assert myCalcThread == this : "There are two CalcThreads running before one of them was cancelled";
}
private synchronized void buildRakeActions(String pattern) {
SearchResult actions = getRakeTasks(pattern, MAX_RAKE);
check();
addActionsToModel(
actions,
() -> myListModel.titleIndex.rakeTasks = myListModel.size(),
() -> myListModel.moreIndex.rakeTasks = actions.size() >= MAX_RAKE ? myListModel.size() - 1 : -1);
}
private SearchResult getActions(final String pattern, final int max, AnAction[] actions, String prefix) {
final SearchResult result = new SearchResult();
final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern).build();
for (AnAction action : actions) {
if (!myListModel.contains(action) && matcher.matches(prefix + " " + RunAnythingUtil.getPresentationText(action))) {
if (result.size() == max) {
result.needMore = true;
break;
}
result.add(action);
}
check();
}
return result;
}
private synchronized void buildBundlerActions(String pattern) {
SearchResult bundlerActions = getBundlerActions(pattern, MAX_BUNDLER_ACTIONS);
check();
addActionsToModel(
bundlerActions,
() -> myListModel.titleIndex.bundler = myListModel.size(),
() -> myListModel.moreIndex.bundlerActions = bundlerActions.size() >= MAX_BUNDLER_ACTIONS ? myListModel.size() - 1 : -1);
}
private void addActionsToModel(final SearchResult actions, Runnable updateTitleIndex, Runnable updateModeIndex) {
SwingUtilities.invokeLater(() -> {
if (isCanceled()) return;
if (actions.size() > 0) {
updateTitleIndex.run();
for (Object action : actions) {
myListModel.addElement(action);
}
}
updateModeIndex.run();
});
}
private synchronized void buildGenerators(final String pattern) {
SearchResult generators = getGenerators(pattern, MAX_GENERATORS);
check();
addActionsToModel(
generators,
() -> myListModel.titleIndex.generators = myListModel.size(),
() -> myListModel.moreIndex.generators = generators.size() >= MAX_GENERATORS ? myListModel.size() - 1 : -1);
}
private synchronized void buildPermanentConfigurations(@NotNull String pattern) {
SearchResult permanentRunConfigurations = getPermanentConfigurations(pattern, MAX_RUN_CONFIGURATION);
if (permanentRunConfigurations.size() > 0) {
SwingUtilities.invokeLater(() -> {
if (isCanceled()) return;
myListModel.titleIndex.permanentRunConfigurations = myListModel.size();
for (Object runConfiguration : permanentRunConfigurations) {
myListModel.addElement(runConfiguration);
}
myListModel.moreIndex.permanentRunConfigurations = permanentRunConfigurations.needMore ? myListModel.getSize() - 1 : -1;
});
}
}
private synchronized void buildTemporaryConfigurations(@NotNull String pattern) {
SearchResult runConfigurations = getTemporaryRunConfigurations(pattern, MAX_RUN_CONFIGURATION);
if (runConfigurations.size() > 0) {
SwingUtilities.invokeLater(() -> {
if (isCanceled()) return;
myListModel.titleIndex.temporaryRunConfigurations = myListModel.size();
for (Object runConfiguration : runConfigurations) {
myListModel.addElement(runConfiguration);
}
myListModel.moreIndex.temporaryRunConfigurations = runConfigurations.needMore ? myListModel.getSize() - 1 : -1;
});
}
}
private SearchResult getConfigurations(String pattern, int max, Predicate<ChooseRunConfigurationPopup.ItemWrapper> filter) {
SearchResult configurations = new SearchResult();
final MinusculeMatcher matcher = NameUtil.buildMatcher(pattern).build();
final ChooseRunConfigurationPopup.ItemWrapper[] wrappers =
ChooseRunConfigurationPopup.createSettingsList(myProject, new ExecutorProvider() {
@Override
public Executor getExecutor() {
return ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.RUN);
}
}, false);
check();
for (ChooseRunConfigurationPopup.ItemWrapper wrapper : wrappers) {
if (!filter.test(wrapper)) continue;
if (matcher.matches(wrapper.getText()) && !myListModel.contains(wrapper)) {
if (configurations.size() == max) {
configurations.needMore = true;
break;
}
configurations.add(wrapper);
}
check();
}
return configurations;
}
private boolean isTemporary(ChooseRunConfigurationPopup.ItemWrapper wrapper) {
Object value = wrapper.getValue();
return value instanceof RunnerAndConfigurationSettings && ((RunnerAndConfigurationSettings)value).isTemporary();
}
private SearchResult getTemporaryRunConfigurations(String pattern, final int max) {
if (!Registry.is("run.anything.temporary.configurations")) return new SearchResult();
return getConfigurations(pattern, max, it -> isTemporary(it));
}
private SearchResult getPermanentConfigurations(String pattern, final int max) {
if (!Registry.is("run.anything.permanent.configurations")) return new SearchResult();
return getConfigurations(pattern, max, it -> !isTemporary(it));
}
private synchronized void buildRecentUndefined() {
SearchResult recentUndefined = getUndefinedCommands(myPattern, MAX_UNDEFINED_FILES);
if (recentUndefined.size() > 0) {
SwingUtilities.invokeLater(() -> {
if (isCanceled()) return;
myListModel.titleIndex.recentUndefined = myListModel.size();
for (Object file : recentUndefined) {
myListModel.addElement(file);
}
myListModel.moreIndex.undefined = recentUndefined.needMore ? myListModel.getSize() - 1 : -1;
});
}
}
private boolean isCanceled() {
return myProgressIndicator.isCanceled() || myDone.isRejected();
}
private void buildModelFromRecentFiles() {
buildRecentUndefined();
}
private void updatePopup() {
updatePopup(false);
}
@SuppressWarnings("SSBasedInspection")
private void updatePopup(boolean isPreserveSelection) {
check();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myListModel.update();
myList.revalidate();
myList.repaint();
if (!isPreserveSelection) {
myList.getSelectionModel().removeSelectionInterval(0, myListModel.getSize() - 1);
}
myRenderer.recalculateWidth();
if (myBalloon == null || myBalloon.isDisposed()) {
return;
}
if (myPopup == null || !myPopup.isVisible()) {
ScrollingUtil.installActions(myList, getField().getTextEditor());
JBScrollPane content = new JBScrollPane(myList) {
{
if (UIUtil.isUnderDarcula()) {
setBorder(null);
}
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
Dimension listSize = myList.getPreferredSize();
if (size.height > listSize.height || myList.getModel().getSize() == 0) {
size.height = Math.max(JBUI.scale(30), listSize.height);
}
if (myBalloon != null && size.width < myBalloon.getSize().width) {
size.width = myBalloon.getSize().width;
}
return size;
}
};
content.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
content.setMinimumSize(new Dimension(myBalloon.getSize().width, 30));
final ComponentPopupBuilder builder = JBPopupFactory.getInstance()
.createComponentPopupBuilder(content, null);
myPopup = builder
.setRequestFocus(false)
.setCancelKeyEnabled(false)
.setResizable(true)
.setCancelCallback(() -> {
final JBPopup balloon = myBalloon;
final AWTEvent event = IdeEventQueue.getInstance().getTrueCurrentEvent();
if (event instanceof MouseEvent) {
final Component comp = ((MouseEvent)event).getComponent();
if (balloon != null && UIUtil.getWindow(comp) == UIUtil.getWindow(balloon.getContent())) {
return false;
}
}
final boolean canClose =
balloon == null || balloon.isDisposed() || (!getField().getTextEditor().hasFocus() && !mySkipFocusGain);
if (canClose) {
PropertiesComponent.getInstance()
.setValue("run.anything.max.popup.width", Math.max(content.getWidth(), JBUI.scale(600)), JBUI.scale(600));
}
return canClose;
})
.setShowShadow(false)
.setShowBorder(false)
.createPopup();
myProject.putUserData(RUN_ANYTHING_POPUP, myPopup);
myPopup.getContent().setBorder(null);
Disposer.register(myPopup, new Disposable() {
@Override
public void dispose() {
myProject.putUserData(RUN_ANYTHING_POPUP, null);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
resetFields();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> ActionToolbarImpl.updateAllToolbarsImmediately());
if (myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) {
final Component component = myActionEvent.getInputEvent().getComponent();
if (component != null) {
final JLabel label = UIUtil.getParentOfType(JLabel.class, component);
if (label != null) {
SwingUtilities.invokeLater(() -> label.setIcon(RubyIcons.RunAnything.Run_anything));
}
}
}
myActionEvent = null;
});
}
});
updatePopupBounds();
myPopup.show(new RelativePoint(getField().getParent(), new Point(0, getField().getParent().getHeight())));
ActionManager.getInstance().addAnActionListener(new AnActionListener.Adapter() {
@Override
public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
if (action instanceof TextComponentEditorAction) {
return;
}
if (myPopup != null) {
myPopup.cancel();
}
}
}, myPopup);
}
else {
myList.revalidate();
myList.repaint();
}
//ScrollingUtil.ensureSelectionExists(myList);
if (myList.getModel().getSize() > 0) {
updatePopupBounds();
}
}
});
}
public ActionCallback cancel() {
myProgressIndicator.cancel();
//myDone.setRejected();
return myDone;
}
public ActionCallback insert(final int index, final WidgetID id) {
ApplicationManager.getApplication().executeOnPooledThread(() -> runReadAction(() -> {
try {
SearchResult result = new SearchResult();
switch (id) {
case PERMANENT:
result = getPermanentConfigurations(myPattern, DEFAULT_MORE_STEP_COUNT);
break;
case RAKE:
result = getRakeTasks(myPattern, DEFAULT_MORE_STEP_COUNT);
break;
case BUNDLER:
result = getBundlerActions(myPattern, DEFAULT_MORE_STEP_COUNT);
break;
case TEMPORARY:
result = getTemporaryRunConfigurations(myPattern, DEFAULT_MORE_STEP_COUNT);
break;
case GENERATORS:
result = getGenerators(myPattern, DEFAULT_MORE_STEP_COUNT);
break;
case UNDEFINED:
result = getUndefinedCommands(myPattern, DEFAULT_MORE_STEP_COUNT);
break;
}
check();
SearchResult finalResult = result;
SwingUtilities.invokeLater(() -> {
try {
int shift = 0;
int i = index + 1;
for (Object o : finalResult) {
//noinspection unchecked
myListModel.insertElementAt(o, i);
shift++;
i++;
}
RunAnythingMoreIndex moreIndex = myListModel.moreIndex;
myListModel.titleIndex.shift(index, shift);
moreIndex.shift(index, shift);
if (!finalResult.needMore) {
switch (id) {
case PERMANENT:
moreIndex.permanentRunConfigurations = -1;
break;
case RAKE:
moreIndex.rakeTasks = -1;
break;
case BUNDLER:
moreIndex.bundlerActions = -1;
break;
case TEMPORARY:
moreIndex.temporaryRunConfigurations = -1;
break;
case GENERATORS:
moreIndex.generators = -1;
break;
case UNDEFINED:
moreIndex.undefined = -1;
break;
}
}
ScrollingUtil.selectItem(myList, index);
myDone.setDone();
}
catch (Exception e) {
myDone.setRejected();
}
});
}
catch (Exception e) {
myDone.setRejected();
}
}, true));
return myDone;
}
@NotNull
private SearchResult getUndefinedCommands(@NotNull String pattern, int max) {
SearchResult result = new SearchResult();
MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern).build();
if (!Registry.is("run.anything.undefined.commands")) {
return result;
}
check();
for (String command : ContainerUtil.iterateBackward(RunAnythingCache.getInstance(myProject).getState().undefinedCommands)) {
RunAnythingUndefinedItem undefinedItem = new RunAnythingUndefinedItem(myProject, myModule, command);
if (matcher.matches(command) && !myListModel.contains(undefinedItem)) {
if (result.size() == max) {
result.needMore = true;
break;
}
result.add(undefinedItem);
}
check();
}
return result;
}
private SearchResult getRakeTasks(String pattern, int count) {
if (!Registry.is("run.anything.rake.tasks")) return new SearchResult();
return getActions(pattern, count, myRakeActions, "rake");
}
private SearchResult getGenerators(String pattern, int count) {
if (!Registry.is("run.anything.generators")) return new SearchResult();
return getActions(pattern, count, myGeneratorsActions, "generator");
}
private SearchResult getBundlerActions(String pattern, int count) {
if (!Registry.is("run.anything.bundler.actions")) return new SearchResult();
return getActions(pattern, count, myBundlerActions, "bundle");
}
public ActionCallback start() {
ApplicationManager.getApplication().executeOnPooledThread(this);
return myDone;
}
}
protected void resetFields() {
if (myBalloon != null) {
final JBPopup balloonToBeCanceled = myBalloon;
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> balloonToBeCanceled.cancel());
myBalloon = null;
}
myCurrentWorker.doWhenProcessed(() -> {
final Object lock = myCalcThread;
if (lock != null) {
synchronized (lock) {
myFocusComponent = null;
myContextComponent = null;
myFocusOwner = null;
myPopup = null;
myHistoryIndex = 0;
myPopupActualWidth = 0;
myCurrentWorker = ActionCallback.DONE;
myCalcThread = null;
myEditor = null;
myFileEditor = null;
}
}
});
mySkipFocusGain = false;
}
private void updatePopupBounds() {
if (myPopup == null || !myPopup.isVisible()) {
return;
}
final Container parent = getField().getParent();
final Dimension size = myList.getParent().getParent().getPreferredSize();
size.width = myPopupActualWidth - 2;
if (size.width + 2 < parent.getWidth()) {
size.width = parent.getWidth();
}
if (myList.getItemsCount() == 0) {
size.height = JBUI.scale(30);
}
Dimension sz = new Dimension(size.width, myList.getPreferredSize().height);
if (!SystemInfo.isMac) {
if ((sz.width > RunAnythingUtil.getPopupMaxWidth() || sz.height > RunAnythingUtil.getPopupMaxWidth())) {
final JBScrollPane pane = new JBScrollPane();
final int extraWidth = pane.getVerticalScrollBar().getWidth() + 1;
final int extraHeight = pane.getHorizontalScrollBar().getHeight() + 1;
sz = new Dimension(Math.min(RunAnythingUtil.getPopupMaxWidth(), Math.max(getField().getWidth(), sz.width + extraWidth)),
Math.min(RunAnythingUtil.getPopupMaxWidth(), sz.height + extraHeight));
sz.width += 20;
}
else {
sz.width += 2;
}
}
sz.height += 2;
sz.width = Math.max(sz.width, myPopup.getSize().width);
myPopup.setSize(sz);
if (myActionEvent != null && myActionEvent.getInputEvent() == null) {
final Point p = parent.getLocationOnScreen();
p.y += parent.getHeight();
if (parent.getWidth() < sz.width) {
p.x -= sz.width - parent.getWidth();
}
myPopup.setLocation(p);
}
else {
try {
RunAnythingUtil.adjustPopup(myBalloon, myPopup);
}
catch (Exception ignore) {
}
}
}
static class SearchResult extends ArrayList<Object> {
boolean needMore;
}
private enum HistoryType {PSI, FILE, SETTING, ACTION, RUN_CONFIGURATION}
static class MySearchTextField extends SearchTextField implements DataProvider, Disposable {
public MySearchTextField() {
super(false, "RunAnythingHistory");
JTextField editor = getTextEditor();
editor.setOpaque(false);
editor.putClientProperty("JTextField.Search.noBorderRing", Boolean.TRUE);
if (UIUtil.isUnderDarcula()) {
editor.setBackground(Gray._45);
editor.setForeground(Gray._240);
}
}
@Override
protected boolean customSetupUIAndTextField(@NotNull TextFieldWithProcessing textField, @NotNull Consumer<TextUI> uiConsumer) {
if (UIUtil.isUnderDarcula()) {
uiConsumer.consume(new MyDarcula(ourIconsMap));
textField.setBorder(new DarculaTextBorder());
}
else {
if (SystemInfo.isMac) {
uiConsumer.consume(new MyMacUI(ourIconsMap));
textField.setBorder(new MacIntelliJTextBorder());
}
else {
uiConsumer.consume(new MyWinUI(ourIconsMap));
textField.setBorder(new WinIntelliJTextBorder());
}
}
return true;
}
@Override
protected boolean isSearchControlUISupported() {
return true;
}
@Override
protected boolean hasIconsOutsideOfTextField() {
return false;
}
@Override
protected void showPopup() {
}
@Nullable
@Override
public Object getData(@NonNls String dataId) {
if (PlatformDataKeys.PREDEFINED_TEXT.is(dataId)) {
return getTextEditor().getText();
}
return null;
}
@Override
public void dispose() {
}
}
private static class RunAnythingSettingsModel extends DefaultListModel {
}
}
|
package org.opens.tanaguru.rules.rgaa22;
import org.opens.tanaguru.entity.audit.TestSolution;
import org.opens.tanaguru.processor.SSPHandler;
import org.opens.tanaguru.ruleimplementation.ElementHandler;
import org.opens.tanaguru.ruleimplementation.TestSolutionHandler;
import org.opens.tanaguru.ruleimplementation.link.AbstractAllLinkAggregateRuleImplementation;
import org.opens.tanaguru.rules.elementchecker.link.IdenticalLinkWithDifferentTargetChecker;
import org.opens.tanaguru.rules.elementselector.AreaLinkElementSelector;
import org.opens.tanaguru.rules.elementselector.CompositeLinkElementSelector;
import org.opens.tanaguru.rules.elementselector.LinkElementSelector;
import static org.opens.tanaguru.rules.keystore.RemarkMessageStore.CHECK_BUTTON_WITH_SAME_TEXT_LEAD_TO_SAME_ACTION_MSG;
public class Rgaa22Rule06151 extends AbstractAllLinkAggregateRuleImplementation {
/**
* Constructor
*/
public Rgaa22Rule06151 () {
super(new LinkElementSelector(false, true),
new CompositeLinkElementSelector(false, true, true),
new AreaLinkElementSelector(false, true),
new CompositeLinkElementSelector(false, true, false),
new IdenticalLinkWithDifferentTargetChecker(false),
new IdenticalLinkWithDifferentTargetChecker(true)
);
}
@Override
protected void checkButtonSelection(
SSPHandler sspHandler,
ElementHandler formButtonHandler,
TestSolutionHandler testSolutionHandler) {
// after all checks, if the test is passed, we check whether some form
// buttons are present on the page and set the result as NMI
if (testSolutionHandler.getTestSolution().equals(TestSolution.PASSED)
&& !formButtonHandler.isEmpty()) {
testSolutionHandler.addTestSolution(TestSolution.NEED_MORE_INFO);
sspHandler.getProcessRemarkService().addProcessRemark(
TestSolution.NEED_MORE_INFO,
CHECK_BUTTON_WITH_SAME_TEXT_LEAD_TO_SAME_ACTION_MSG);
}
}
}
|
package co.cutely.asim.service;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smackx.nick.packet.Nick;
import java.io.IOException;
/**
* Service handling all XMPP connection logic
*/
public class XmppService extends Service {
private static final String TAG = XmppService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
Log.i(TAG, "Started with start id " + startId + ": " + intent);
connect(new XmppServiceConnectionConfiguration("0xxon.net", "smacktest", "thisIsThePasswordForSmacktest"));
// continue running until stopped
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void connect(final XmppServiceConnectionConfiguration conf) {
new AsyncTask<XmppServiceConnectionConfiguration, Void, AbstractXMPPConnection>() {
@Override
protected AbstractXMPPConnection doInBackground(final XmppServiceConnectionConfiguration... configs) {
Log.i(TAG, "In doInBackground");
if ( configs.length != 1 ) {
Log.e(TAG, "Wrong number of connection configurations in connect");
assert(false);
}
XmppServiceConnectionConfiguration config = configs[0];
Log.i(TAG, "trying to connect to " + config.service);
AbstractXMPPConnection conn = new XMPPTCPConnection(config.service);
try {
conn.connect();
Log.i(TAG, "trying to login...");
conn.login(config.user, config.password);
return conn;
} catch (SmackException e) {
Log.e(TAG, "Error connecting", e);
} catch (IOException e) {
Log.e(TAG, "Error connecting", e);
} catch (XMPPException e) {
Log.e(TAG, "Error connecting", e);
}
return null;
}
@Override
protected void onPostExecute(final AbstractXMPPConnection connection) {
onConnected(connection);
}
}.execute(conf);
}
private void onConnected(AbstractXMPPConnection conn) {
if (conn == null) {
Log.i(TAG, "Didn't connect =(");
return;
}
Log.i(TAG, "Connected to " + conn.getServiceName() + " with " + conn.getUser() );
Roster roster = conn.getRoster();
Log.i(TAG, "Duming roster");
for ( RosterEntry e : roster.getEntries() ) {
Log.i(TAG, "User " + e.getName() + "(" + e.getUser() + ")" + e.getGroups());
}
}
public static class XmppServiceConnectionConfiguration {
public final String service;
public final String user;
public final String password;
public XmppServiceConnectionConfiguration(String service, String user, String password) {
this.service = service;
this.user = user;
this.password = password;
}
}
}
|
package com.blazeloader.api.obf;
import net.acomputerdog.OBFUtil.table.DirectOBFTableSRG;
import net.acomputerdog.OBFUtil.util.TargetType;
import java.util.HashMap;
import java.util.Map;
/**
* BlazeLoader OBFTable that allows converting stored data into BLOBFs.
* Provided methods automatically cache calls, so repeated calls with the same parameters will return the same BLOBF object.
*/
public class BLOBFTable extends DirectOBFTableSRG {
private final Map<TargetType, Map<String, BLOBF>> obfNameMap = new HashMap<TargetType, Map<String, BLOBF>>();
private final Map<TargetType, Map<String, BLOBF>> srgNameMap = new HashMap<TargetType, Map<String, BLOBF>>();
private final Map<TargetType, Map<String, BLOBF>> mcpNameMap = new HashMap<TargetType, Map<String, BLOBF>>();
public BLOBFTable() {
super();
for (TargetType type : TargetType.values()) {
obfNameMap.put(type, new HashMap<String, BLOBF>());
srgNameMap.put(type, new HashMap<String, BLOBF>());
mcpNameMap.put(type, new HashMap<String, BLOBF>());
}
}
public BLOBF getOBF(String obfName, TargetType type) {
BLOBF obf = obfNameMap.get(type).get(obfName);
if (obf == null) {
if (super.hasTypeObf(obfName, type)) {
obf = new BLOBF(obfName, super.getSRGFromObfType(obfName, type), super.deobfType(obfName, type));
obfNameMap.get(type).put(obf.obf, obf);
srgNameMap.get(type).put(obf.srg, obf);
mcpNameMap.get(type).put(obf.name, obf);
}
}
return obf;
}
public BLOBF getSRG(String srgName, TargetType type) {
BLOBF obf = srgNameMap.get(type).get(srgName);
if (obf == null) {
if (super.hasTypeSRG(srgName, type)) {
obf = new BLOBF(super.getObfFromSRGType(srgName, type), srgName, super.getDeObfFromSRGType(srgName, type));
obfNameMap.get(type).put(obf.obf, obf);
srgNameMap.get(type).put(obf.srg, obf);
mcpNameMap.get(type).put(obf.name, obf);
}
}
return obf;
}
public BLOBF getMCP(String mcpName, TargetType type) {
BLOBF obf = mcpNameMap.get(type).get(mcpName);
if (obf == null) {
if (super.hasTypeDeobf(mcpName, type)) {
obf = new BLOBF(super.obfType(mcpName, type), super.getSRGFromDeObfType(mcpName, type), mcpName);
obfNameMap.get(type).put(obf.obf, obf);
srgNameMap.get(type).put(obf.srg, obf);
mcpNameMap.get(type).put(obf.name, obf);
}
}
return obf;
}
}
|
package com.ecyrd.jspwiki;
import java.io.*;
import java.util.*;
import java.text.*;
import org.apache.log4j.Category;
import org.apache.oro.text.*;
import org.apache.oro.text.regex.*;
import com.ecyrd.jspwiki.plugin.PluginManager;
import com.ecyrd.jspwiki.plugin.PluginException;
/**
* Handles conversion from Wiki format into fully featured HTML.
* This is where all the magic happens. It is CRITICAL that this
* class is tested, or all Wikis might die horribly.
* <P>
* The output of the HTML has not yet been validated against
* the HTML DTD. However, it is very simple.
*
* @author Janne Jalkanen
*/
// FIXME: Class still has problems with {{{: all conversion on that line where the {{{
// appears is done, but after that, conversion is not done. The only real solution
// is to move away from a line-based system into a pure stream-based system.
public class TranslatorReader extends Reader
{
public static final int READ = 0;
public static final int EDIT = 1;
private static final int EMPTY = 2; // Empty message
private static final int LOCAL = 3;
private static final int LOCALREF = 4;
private static final int IMAGE = 5;
private static final int EXTERNAL = 6;
private static final int INTERWIKI = 7;
private static final int IMAGELINK = 8;
private static final int IMAGEWIKILINK = 9;
private BufferedReader m_in;
private StringReader m_data = new StringReader("");
private static Category log = Category.getInstance( TranslatorReader.class );
private boolean m_iscode = false;
private boolean m_isbold = false;
private boolean m_isitalic = false;
private boolean m_isTypedText = false;
private boolean m_istable = false;
private int m_listlevel = 0;
private int m_numlistlevel = 0;
private WikiEngine m_engine;
private WikiContext m_context;
/** Optionally stores internal wikilinks */
private ArrayList m_localLinkMutatorChain = new ArrayList();
private ArrayList m_externalLinkMutatorChain = new ArrayList();
/** Keeps image regexp Patterns */
private ArrayList m_inlineImagePatterns;
private PatternMatcher m_inlineMatcher = new Perl5Matcher();
private ArrayList m_linkMutators = new ArrayList();
/**
* This property defines the inline image pattern. It's current value
* is jspwiki.translatorReader.inlinePattern
*/
public static final String PROP_INLINEIMAGEPTRN = "jspwiki.translatorReader.inlinePattern";
/** If true, consider CamelCase hyperlinks as well. */
public static final String PROP_CAMELCASELINKS = "jspwiki.translatorReader.camelCaseLinks";
/** If true, all hyperlinks are translated as well, regardless whether they
are surrounded by brackets. */
public static final String PROP_PLAINURIS = "jspwiki.translatorReader.plainUris";
/** If true, then considers CamelCase links as well. */
private boolean m_camelCaseLinks = false;
/** If true, consider URIs that have no brackets as well. */
// FIXME: Currently reserved, but not used.
private boolean m_plainUris = false;
private PatternMatcher m_matcher = new Perl5Matcher();
private PatternCompiler m_compiler = new Perl5Compiler();
private Pattern m_camelCasePtrn;
/**
* The default inlining pattern. Currently "*.png"
*/
public static final String DEFAULT_INLINEPATTERN = "*.png";
/**
* @param engine The WikiEngine this reader is attached to. Is
* used to figure out of a page exits.
*/
// FIXME: TranslatorReaders should be pooled for better performance.
public TranslatorReader( WikiContext context, Reader in )
{
PatternCompiler compiler = new GlobCompiler();
ArrayList compiledpatterns = new ArrayList();
m_in = new BufferedReader( in );
m_engine = context.getEngine();
m_context = context;
Collection ptrns = getImagePatterns( m_engine );
// Make them into Regexp Patterns. Unknown patterns
// are ignored.
for( Iterator i = ptrns.iterator(); i.hasNext(); )
{
try
{
compiledpatterns.add( compiler.compile( (String)i.next() ) );
}
catch( MalformedPatternException e )
{
log.error("Malformed pattern in properties: ", e );
}
}
m_inlineImagePatterns = compiledpatterns;
try
{
m_camelCasePtrn = m_compiler.compile( "(^|\\W|\\~)([A-Z][a-z]+([A-Z][a-z]+)+)" );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: Someone put in a faulty pattern.",e);
throw new InternalWikiException("Faulty camelcasepattern in TranslatorReader");
}
// Set the properties.
Properties props = m_engine.getWikiProperties();
m_camelCaseLinks = "true".equals( props.getProperty( PROP_CAMELCASELINKS, "false" ) );
m_plainUris = "true".equals( props.getProperty( PROP_PLAINURIS, "false" ) );
}
/**
* Adds a hook for processing link texts. This hook is called
* when the link text is written into the output stream, and
* you may use it to modify the text. It does not affect the
* actual link, only the user-visible text.
*
* @param mutator The hook to call. Null is safe.
*/
public void addLinkTransmutator( StringTransmutator mutator )
{
if( mutator != null )
{
m_linkMutators.add( mutator );
}
}
/**
* Adds a hook for processing local links. The engine
* transforms both non-existing and existing page links.
*
* @param mutator The hook to call. Null is safe.
*/
public void addLocalLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_localLinkMutatorChain.add( mutator );
}
}
public void addExternalLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_externalLinkMutatorChain.add( mutator );
}
}
/**
* Figure out which image suffixes should be inlined.
* @return Collection of Strings with patterns.
*/
protected static Collection getImagePatterns( WikiEngine engine )
{
Properties props = engine.getWikiProperties();
ArrayList ptrnlist = new ArrayList();
for( Enumeration e = props.propertyNames(); e.hasMoreElements(); )
{
String name = (String) e.nextElement();
if( name.startsWith( PROP_INLINEIMAGEPTRN ) )
{
String ptrn = props.getProperty( name );
ptrnlist.add( ptrn );
}
}
if( ptrnlist.size() == 0 )
{
ptrnlist.add( DEFAULT_INLINEPATTERN );
}
return ptrnlist;
}
/**
* Returns link name, if it exists; otherwise it returns null.
*/
private String linkExists( String page )
{
return m_engine.getFinalPageName( page );
}
/**
* Calls a transmutator chain.
*
* @param list Chain to call
* @param text Text that should be passed to the mutate() method
* of each of the mutators in the chain.
* @return The result of the mutation.
*/
private String callMutatorChain( Collection list, String text )
{
if( list == null || list.size() == 0 )
{
return text;
}
for( Iterator i = list.iterator(); i.hasNext(); )
{
StringTransmutator m = (StringTransmutator) i.next();
text = m.mutate( m_context, text );
}
return text;
}
/**
* Write a HTMLized link depending on its type.
* The link mutator chain is processed.
*
* @param type Type of the link.
* @param link The actual link.
* @param text The user-visible text for the link.
*/
public String makeLink( int type, String link, String text )
{
String result;
if( text == null ) text = link;
// Make sure we make a link name that can be accepted
// as a valid URL.
String encodedlink = m_engine.encodeName( link );
if( encodedlink.length() == 0 )
{
type = EMPTY;
}
text = callMutatorChain( m_linkMutators, text );
switch(type)
{
case READ:
result = "<A CLASS=\"wikipage\" HREF=\""+m_engine.getBaseURL()+"Wiki.jsp?page="+encodedlink+"\">"+text+"</A>";
break;
case EDIT:
result = "<U>"+text+"</U><A HREF=\""+m_engine.getBaseURL()+"Edit.jsp?page="+encodedlink+"\">?</A>";
break;
case EMPTY:
result = "<U>"+text+"</U>";
break;
// These two are for local references - footnotes and
// references to footnotes.
// We embed the page name (or whatever WikiContext gives us)
// to make sure the links are unique across Wiki.
case LOCALREF:
result = "<A CLASS=\"footnoteref\" HREF=\"#ref-"+
m_context.getPage().getName()+"-"+
link+"\">["+text+"]</A>";
break;
case LOCAL:
result = "<A CLASS=\"footnote\" NAME=\"ref-"+
m_context.getPage().getName()+"-"+
link.substring(1)+"\">["+text+"]</A>";
break;
// With the image, external and interwiki types we need to
// make sure nobody can put in Javascript or something else
// annoying into the links themselves. We do this by preventing
// a haxor from stopping the link name short with quotes in
// fillBuffer().
case IMAGE:
result = "<IMG CLASS=\"inline\" SRC=\""+link+"\" ALT=\""+text+"\">";
break;
case IMAGELINK:
result = "<A HREF=\""+text+"\"><IMG CLASS=\"inline\" SRC=\""+link+"\"></A>";
break;
case IMAGEWIKILINK:
String pagelink = m_engine.getBaseURL()+"Wiki.jsp?page="+text;
result = "<A CLASS=\"wikipage\" HREF=\""+pagelink+"\"><IMG CLASS=\"inline\" SRC=\""+link+"\" ALT=\""+text+"\"></A>";
break;
case EXTERNAL:
result = "<A CLASS=\"external\" HREF=\""+link+"\">"+text+"</A>";
break;
case INTERWIKI:
result = "<A CLASS=\"interwiki\" HREF=\""+link+"\">"+text+"</A>";
break;
default:
result = "";
break;
}
return result;
}
/**
* Cleans a Wiki name.
* <P>
* [ This is a link ] -> ThisIsALink
*
* @since 2.0
*/
public static String cleanLink( String link )
{
StringBuffer clean = new StringBuffer();
// Compress away all whitespace and capitalize
// all words in between.
StringTokenizer st = new StringTokenizer( link, " -" );
while( st.hasMoreTokens() )
{
StringBuffer component = new StringBuffer(st.nextToken());
component.setCharAt(0, Character.toUpperCase( component.charAt(0) ) );
clean.append( component );
}
// Remove non-alphanumeric characters that should not
// be put inside WikiNames. Note that all valid
// Unicode letters are considered okay for WikiNames.
// It is the problem of the WikiPageProvider to take
// care of actually storing that information.
for( int i = 0; i < clean.length(); i++ )
{
if( !(Character.isLetterOrDigit(clean.charAt(i)) ||
clean.charAt(i) == '_' ||
clean.charAt(i) == '.') )
{
clean.deleteCharAt(i);
--i; // We just shortened this buffer.
}
}
return clean.toString();
}
/**
* Figures out if a link is an off-site link. This recognizes
* the most common protocols by checking how it starts.
*/
private boolean isExternalLink( String link )
{
return link.startsWith("http:") || link.startsWith("ftp:") ||
link.startsWith("https:") || link.startsWith("mailto:") ||
link.startsWith("news:") || link.startsWith("file:");
}
/**
* Matches the given link to the list of image name patterns
* to determine whether it should be treated as an inline image
* or not.
*/
private boolean isImageLink( String link )
{
for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); )
{
if( m_inlineMatcher.matches( link, (Pattern) i.next() ) )
return true;
}
return false;
}
/**
* Returns true, if the argument contains a number, otherwise false.
* In a quick test this is roughly the same speed as Integer.parseInt()
* if the argument is a number, and roughly ten times the speed, if
* the argument is NOT a number.
*/
private boolean isNumber( String s )
{
if( s == null ) return false;
if( s.length() > 1 && s.charAt(0) == '-' )
s = s.substring(1);
for( int i = 0; i < s.length(); i++ )
{
if( !Character.isDigit(s.charAt(i)) )
return false;
}
return true;
}
/**
* Attempts to set traditional, CamelCase style WikiLinks.
*/
private String setCamelCaseLinks( String line )
{
PatternMatcherInput input;
input = new PatternMatcherInput( line );
while( m_matcher.contains( input, m_camelCasePtrn ) )
{
// Weed out links that will be matched later on.
MatchResult res = m_matcher.getMatch();
int lastOpen = line.substring(0,res.endOffset(2)).lastIndexOf('[');
int lastClose = line.substring(0,res.endOffset(2)).lastIndexOf(']');
if( (lastOpen < lastClose && lastOpen >= 0) || // Links closed ok
lastOpen < 0 ) // No links yet
{
int start = res.beginOffset(2);
int end = res.endOffset(2);
String link = res.group(2);
String matchedLink;
// System.out.println("LINE="+line);
// System.out.println(" Replacing: "+link);
// System.out.println(" open="+lastOpen+", close="+lastClose);
callMutatorChain( m_localLinkMutatorChain, link );
if( "~".equals( res.group(1) ) )
{
// Delete the (~) from beginning.
// We'll make '~' the generic kill-processing-character from
// now on.
start
}
else if( (matchedLink = linkExists( link )) != null )
{
link = makeLink( READ, matchedLink, link );
}
else
{
link = makeLink( EDIT, link, link );
}
line = TextUtil.replaceString( line,
start,
end,
link );
input.setInput( line );
input.setCurrentOffset( start+link.length() );
}
} // while
return line;
}
/**
* Gobbles up all hyperlinks that are encased in square brackets.
*/
private String setHyperLinks( String line )
{
int start, end = 0;
StringBuffer sb = new StringBuffer();
int idx = 0;
while( idx < line.length() )
{
start = line.indexOf('[', end);
// System.out.println(line);
// System.out.println("idx="+idx+", start="+start+", end="+end);
if( start < 0 || start == line.length() )
{
// No more hyperlinks.
sb.append( line.substring( idx ) );
break;
}
sb.append( line.substring( idx, start ) );
// Words starting with multiple [[s are not hyperlinks.
if( start < (line.length()-1) && line.charAt( start+1 ) == '[' )
{
// Find where the neverending roll of '['s stops...
for( end = start+1; end < line.length() && line.charAt(end) == '['; end++ );
sb.append( line.substring( start+1, end ) );
idx = end;
continue;
}
else
{
end = line.indexOf( ']', start );
if( end != -1 )
{
// Everything between these two is a link
String link = line.substring( start+1, end );
String reallink;
int cutpoint;
if( (cutpoint = link.indexOf('|')) != -1 )
{
reallink = link.substring( cutpoint+1 ).trim();
link = link.substring( 0, cutpoint );
}
else
{
reallink = link.trim();
}
int interwikipoint = -1;
// Yes, we now have the components separated.
// link = the text the link should have
// reallink = the url or page name.
// In many cases these are the same. [link|reallink].
if( PluginManager.isPluginLink( link ) )
{
String included;
try
{
included = m_engine.getPluginManager().execute( m_context, link );
}
catch( PluginException e )
{
log.error( "Failed to insert plugin", e );
log.error( "Root cause:",e.getRootThrowable() );
included = "<FONT COLOR=\"#FF0000\">Plugin insertion failed: "+e.getMessage()+"</FONT>";
}
sb.append( included );
}
else if( VariableManager.isVariableLink( link ) )
{
String value;
try
{
value = m_engine.getVariableManager().parseAndGetValue( m_context, link );
}
catch( NoSuchVariableException e )
{
value = "<FONT COLOR=\"#FF0000\">"+e.getMessage()+"</FONT>";
}
catch( IllegalArgumentException e )
{
value = "<FONT COLOR=\"#FF0000\">"+e.getMessage()+"</FONT>";
}
sb.append( value );
}
else if( isExternalLink( reallink ) )
{
// It's an external link, out of this Wiki
callMutatorChain( m_externalLinkMutatorChain, reallink );
if( isImageLink( reallink ) )
{
// Image links are handled differently:
// 1. If the text is a WikiName of an existing page,
// it gets linked.
// 2. If the text is an external link, then it is inlined.
// 3. Otherwise it becomes an ALT text.
String possiblePage = cleanLink( link );
String matchedLink;
if( isExternalLink( link ) && (cutpoint != -1) )
{
sb.append( makeLink( IMAGELINK, reallink, link ) );
}
else if( (matchedLink = linkExists( possiblePage )) != null &&
(cutpoint != -1) )
{
// System.out.println("Orig="+link+", Matched: "+matchedLink);
callMutatorChain( m_localLinkMutatorChain, possiblePage );
sb.append( makeLink( IMAGEWIKILINK, reallink, link ) );
}
else
{
sb.append( makeLink( IMAGE, reallink, link ) );
}
}
else
{
sb.append( makeLink( EXTERNAL, reallink, link ) );
}
}
else if( (interwikipoint = reallink.indexOf(":")) != -1 )
{
// It's an interwiki link
// InterWiki links also get added to external link chain
// after the links have been resolved.
// FIXME: There is an interesting issue here: We probably should
// URLEncode the wikiPage, but we can't since some of the
// Wikis use slashes (/), which won't survive URLEncoding.
// Besides, we don't know which character set the other Wiki
// is using, so you'll have to write the entire name as it appears
// in the URL. Bugger.
String extWiki = reallink.substring( 0, interwikipoint );
String wikiPage = reallink.substring( interwikipoint+1 );
String urlReference = m_engine.getInterWikiURL( extWiki );
if( urlReference != null )
{
urlReference = TextUtil.replaceString( urlReference, "%s", wikiPage );
callMutatorChain( m_externalLinkMutatorChain, urlReference );
sb.append( makeLink( INTERWIKI, urlReference, link ) );
}
else
{
sb.append( link+" <FONT COLOR=\"#FF0000\">(No InterWiki reference defined in properties for Wiki called '"+extWiki+"'!)</FONT>");
}
}
else if( reallink.startsWith("
{
// It defines a local footnote
sb.append( makeLink( LOCAL, reallink, link ) );
}
else if( isNumber( reallink ) )
{
// It defines a reference to a local footnote
sb.append( makeLink( LOCALREF, reallink, link ) );
}
else
{
// It's an internal Wiki link
reallink = cleanLink( reallink );
callMutatorChain( m_localLinkMutatorChain, reallink );
String matchedLink;
if( (matchedLink = linkExists( reallink )) != null )
{
sb.append( makeLink( READ, matchedLink, link ) );
}
else
{
sb.append( makeLink( EDIT, reallink, link ) );
}
}
}
else
{
log.error("Unterminated link");
break;
}
} // else
idx = end+1;
} // while
return sb.toString();
}
/**
* Checks if this line is a heading line.
*/
private String setHeadings( String line )
{
if( line.startsWith("!!!") )
{
line = TextUtil.replaceString( line, 0, 3, "<H2>" ) + "</H2>";
}
else if( line.startsWith("!!") )
{
line = TextUtil.replaceString( line, 0, 2, "<H3>" ) + "</H3>";
}
else if( line.startsWith("!") )
{
line = TextUtil.replaceString( line, 0, 1, "<H4>" ) + "</H4>";
}
return line;
}
private String setDefinitionList( String line )
{
if( line.startsWith(";") )
{
int breakIndex = line.indexOf(':');
if( breakIndex > 0 )
{
StringBuffer res = new StringBuffer();
res.append("<DL>\n<DT>"+line.substring(1,breakIndex)+"</DT>");
res.append("<DD>"+line.substring(breakIndex+1)+"</DD>");
res.append("\n</DL>");
line = res.toString();
}
}
return line;
}
/**
* Translates horizontal rulers.
*/
private String setHR( String line )
{
StringBuffer buf = new StringBuffer();
int start = line.indexOf("
if( start != -1 )
{
int i;
buf.append( line.substring( 0, start ) );
for( i = start; i<line.length() && line.charAt(i) == '-'; i++ )
{
}
buf.append("<HR />");
buf.append( line.substring( i ) );
return buf.toString();
}
return line;
}
/**
* Closes all annoying lists and things that the user might've
* left open.
*/
private String closeAll()
{
StringBuffer buf = new StringBuffer();
if( m_isbold )
{
buf.append("</B>");
m_isbold = false;
}
if( m_isitalic )
{
buf.append("</I>");
m_isitalic = false;
}
if( m_isTypedText )
{
buf.append("</TT>");
m_isTypedText = false;
}
for( ; m_listlevel > 0; m_listlevel
{
buf.append( "</UL>\n" );
}
for( ; m_numlistlevel > 0; m_numlistlevel
{
buf.append( "</OL>\n" );
}
if( m_iscode )
{
buf.append("</PRE>\n");
m_iscode = false;
}
if( m_istable )
{
buf.append( "</TABLE>" );
m_istable = false;
}
return buf.toString();
}
/**
* Sets bold text.
*/
private String setBold( String line )
{
StringBuffer buf = new StringBuffer();
for( int i = 0; i < line.length(); i++ )
{
if( line.charAt(i) == '_' && i < line.length()-1 )
{
if( line.charAt(i+1) == '_' )
{
buf.append( m_isbold ? "</B>" : "<B>" );
m_isbold = !m_isbold;
i++;
}
else buf.append( "_" );
}
else buf.append( line.charAt(i) );
}
return buf.toString();
}
/**
* Counts how many consecutive characters of a certain type exists on the line.
* @param line String of chars to check.
* @param startPos Position to start reading from.
* @param char Character to check for.
*/
private int countChar( String line, int startPos, char c )
{
int count;
for( count = 0; (startPos+count < line.length()) && (line.charAt(count+startPos) == c); count++ );
return count;
}
/**
* Returns a new String that has char c n times.
*/
private String repeatChar( char c, int n )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < n; i++ ) sb.append(c);
return sb.toString();
}
/**
* {{text}} = <TT>text</TT>
*/
private String setTT( String line )
{
StringBuffer buf = new StringBuffer();
for( int i = 0; i < line.length(); i++ )
{
if( line.charAt(i) == '{' && !m_isTypedText )
{
int count = countChar( line, i, '{' );
if( count == 2 )
{
buf.append( "<TT>" );
m_isTypedText = true;
}
else
{
buf.append( repeatChar( '{', count ) );
}
i += count-1;
}
else if( line.charAt(i) == '}' && m_isTypedText )
{
int count = countChar( line, i, '}' );
if( count == 2 )
{
buf.append( "</TT>" );
m_isTypedText = false;
}
else
{
buf.append( repeatChar( '}', count ) );
}
i += count-1;
}
else
{
buf.append( line.charAt(i) );
}
}
return buf.toString();
}
private String setItalic( String line )
{
StringBuffer buf = new StringBuffer();
for( int i = 0; i < line.length(); i++ )
{
if( line.charAt(i) == '\'' && i < line.length()-1 )
{
if( line.charAt(i+1) == '\'' )
{
buf.append( m_isitalic ? "</I>" : "<I>" );
m_isitalic = !m_isitalic;
i++;
}
else buf.append( "'" );
}
else buf.append( line.charAt(i) );
}
return buf.toString();
}
private void fillBuffer()
throws IOException
{
int pre;
String postScript = ""; // Gets added at the end of line.
StringBuffer buf = new StringBuffer();
String line = m_in.readLine();
if( line == null )
{
m_data = new StringReader("");
return;
}
String trimmed = line.trim();
// Stupid hack to enable multi-line plugin entries. This should not be.
// Then again, this line-based parsing shouldn't be, either.
// We simply read stuff in until we encounter the line that closes the
// plugin. May potentially cause long lines, especially if a close tag
// is missing. ebu 2002-11-01
int pluginStart = -1;
int pluginEnd = -1;
if( (pluginStart = line.indexOf( "[{" )) != -1 && (pluginEnd = line.indexOf( "}]", pluginStart )) == -1 )
{
StringBuffer sb = new StringBuffer( line );
boolean pluginClosed = false;
while( !pluginClosed )
{
String additional = m_in.readLine();
if( additional != null )
{
sb.append( additional );
if( additional.indexOf( "}]" ) != -1 )
pluginClosed = true;
}
else
{
log.error( "Unclosed plugin" );
}
}
line = sb.toString();
}
// Replace the most obvious items that could possibly
// break the resulting HTML code.
line = TextUtil.replaceEntities( line );
if( !m_iscode )
{
// Tables
if( trimmed.startsWith("|") )
{
StringBuffer tableLine = new StringBuffer();
if( !m_istable )
{
buf.append( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n" );
m_istable = true;
}
buf.append( "<TR>" );
// The following piece of code will go through the line character
// by character, and replace all references to the table markers (|)
// by a <TD>, EXCEPT when '|' can be found inside a link.
boolean islink = false;
for( int i = 0; i < line.length(); i++ )
{
char c = line.charAt(i);
switch( c )
{
case '|':
if( !islink )
{
if( i < line.length()-1 && line.charAt(i+1) == '|' )
{
// It's a heading.
tableLine.append( "<TH>" );
i++;
}
else
{
// It's a normal thingy.
tableLine.append( "<TD>" );
}
}
else
{
tableLine.append( c );
}
break;
case '[':
islink = true;
tableLine.append( c );
break;
case ']':
islink = false;
tableLine.append( c );
break;
default:
tableLine.append( c );
break;
}
} // for
line = tableLine.toString();
postScript = "</TR>";
}
else if( !trimmed.startsWith("|") && m_istable )
{
buf.append( "</TABLE>" );
m_istable = false;
}
// FIXME: The following two blocks of code are temporary
// solutions for code going all wonky if you do multiple #*:s inside
// each other.
// A real solution is needed - this only closes down the other list
// before the other one gets started.
if( line.startsWith("*") )
{
for( ; m_numlistlevel > 0; m_numlistlevel
{
buf.append("</OL>\n");
}
}
if( line.startsWith("
{
for( ; m_listlevel > 0; m_listlevel
{
buf.append("</UL>\n");
}
}
// Make a bulleted list
if( line.startsWith("*") )
{
// Close all other lists down.
int numBullets = countChar( line, 0, '*' );
if( numBullets > m_listlevel )
{
for( ; m_listlevel < numBullets; m_listlevel++ )
buf.append("<UL>\n");
}
else if( numBullets < m_listlevel )
{
for( ; m_listlevel > numBullets; m_listlevel
buf.append("</UL>\n");
}
buf.append("<LI>");
line = line.substring( numBullets );
}
else if( line.startsWith(" ") && m_listlevel > 0 && trimmed.length() != 0 )
{
// This is a continuation of a previous line.
}
else if( line.startsWith("#") && m_listlevel > 0 )
{
// We don't close all things for the other list type.
}
else
{
// Close all lists down.
for( ; m_listlevel > 0; m_listlevel
{
buf.append("</UL>\n");
}
}
// Ordered list
if( line.startsWith("
{
// Close all other lists down.
if( m_numlistlevel == 0 )
{
for( ; m_listlevel > 0; m_listlevel
{
buf.append("</UL>\n");
}
}
int numBullets = countChar( line, 0, '
if( numBullets > m_numlistlevel )
{
for( ; m_numlistlevel < numBullets; m_numlistlevel++ )
buf.append("<OL>\n");
}
else if( numBullets < m_numlistlevel )
{
for( ; m_numlistlevel > numBullets; m_numlistlevel
buf.append("</OL>\n");
}
buf.append("<LI>");
line = line.substring( numBullets );
}
else if( line.startsWith(" ") && m_numlistlevel > 0 && trimmed.length() != 0 )
{
// This is a continuation of a previous line.
}
else if( line.startsWith("*") && m_numlistlevel > 0 )
{
// We don't close things for the other list type.
}
else
{
// Close all lists down.
for( ; m_numlistlevel > 0; m_numlistlevel
{
buf.append("</OL>\n");
}
}
// Do the standard settings
if( m_camelCaseLinks )
{
line = setCamelCaseLinks( line );
}
line = setDefinitionList( line );
line = setHeadings( line );
line = setHR( line );
line = setBold( line );
line = setItalic( line );
line = setTT( line );
line = TextUtil.replaceString( line, "\\\\", "<BR>" );
line = setHyperLinks( line );
// Is this an empty line?
if( trimmed.length() == 0 )
{
buf.append( "<P>" );
}
if( (pre = line.indexOf("{{{")) != -1 )
{
line = TextUtil.replaceString( line, pre, pre+3, "<PRE>" );
m_iscode = true;
}
}
if( (pre = line.indexOf("}}}")) != -1 )
{
line = TextUtil.replaceString( line, pre, pre+3, "</PRE>" );
m_iscode = false;
}
buf.append( line );
buf.append( postScript );
buf.append( "\n" );
m_data = new StringReader( buf.toString() );
}
public int read()
throws IOException
{
int val = m_data.read();
if( val == -1 )
{
fillBuffer();
val = m_data.read();
if( val == -1 )
{
m_data = new StringReader( closeAll() );
val = m_data.read();
}
}
return val;
}
public int read( char[] buf, int off, int len )
throws IOException
{
return m_data.read( buf, off, len );
}
public boolean ready()
throws IOException
{
log.debug("ready ? "+m_data.ready() );
if(!m_data.ready())
{
fillBuffer();
}
return m_data.ready();
}
public void close()
{
}
}
|
package com.ecyrd.jspwiki.auth;
import java.util.*;
import java.security.Principal;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import java.security.Principal;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.TranslatorReader;
import com.ecyrd.jspwiki.util.ClassUtil;
import com.ecyrd.jspwiki.util.HttpUtil;
import com.ecyrd.jspwiki.auth.modules.*;
/**
* Manages user accounts, logins/logouts, passwords, etc.
*
* @author Janne Jalkanen
* @author Erik Bunn
*/
public class UserManager
{
static Category log = Category.getInstance( UserManager.class );
/** The name the UserProfile is stored in a Session by. */
public static final String WIKIUSER = "currentUser";
/** If true, logs the IP address of the editor on saving. */
public static final String PROP_STOREIPADDRESS= "jspwiki.storeIPAddress";
public static final String PROP_AUTHENTICATOR = "jspwiki.authenticator";
public static final String PROP_USERDATABASE = "jspwiki.userdatabase";
public static final String PROP_ADMINISTRATOR = "jspwiki.auth.administrator";
/** If true, logs the IP address of the editor */
private boolean m_storeIPAddress = true;
private HashMap m_groups = new HashMap();
// FIXME: These should probably be localized.
// FIXME: All is used as a catch-all.
public static final String GROUP_GUEST = "Guest";
public static final String GROUP_NAMEDGUEST = "NamedGuest";
public static final String GROUP_KNOWNPERSON = "KnownPerson";
private static final String DEFAULT_DATABASE = "com.ecyrd.jspwiki.auth.modules.WikiDatabase";
/**
* The default administrator group is called "AdminGroup"
*/
private static final String DEFAULT_ADMINISTRATOR = "AdminGroup";
private WikiAuthenticator m_authenticator;
private UserDatabase m_database;
private WikiEngine m_engine;
private String m_administrator;
/**
* Creates an UserManager instance for the given WikiEngine and
* the specified set of properties. All initialization for the
* modules is done here.
*/
public UserManager( WikiEngine engine, Properties props )
throws WikiException
{
m_engine = engine;
m_storeIPAddress = TextUtil.getBooleanProperty( props,
PROP_STOREIPADDRESS,
m_storeIPAddress );
m_administrator = props.getProperty( PROP_ADMINISTRATOR,
DEFAULT_ADMINISTRATOR );
WikiGroup all = new AllGroup();
all.setName( "All" );
m_groups.put( GROUP_GUEST, new AllGroup() );
// m_groups.put( "All", all );
m_groups.put( GROUP_NAMEDGUEST, new NamedGroup() );
m_groups.put( GROUP_KNOWNPERSON, new KnownGroup() );
String authClassName = props.getProperty( PROP_AUTHENTICATOR );
if( authClassName != null )
{
try
{
Class authenticatorClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.modules",
authClassName );
m_authenticator = (WikiAuthenticator)authenticatorClass.newInstance();
m_authenticator.initialize( props );
log.info("Initialized "+authClassName+" for authentication.");
}
catch( ClassNotFoundException e )
{
log.fatal( "Authenticator "+authClassName+" cannot be found", e );
throw new WikiException("Authenticator cannot be found");
}
catch( InstantiationException e )
{
log.fatal( "Authenticator "+authClassName+" cannot be created", e );
throw new WikiException("Authenticator cannot be created");
}
catch( IllegalAccessException e )
{
log.fatal( "You are not allowed to access this authenticator class", e );
throw new WikiException("You are not allowed to access this authenticator class");
}
}
String dbClassName = props.getProperty( PROP_USERDATABASE,
DEFAULT_DATABASE );
try
{
Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.modules",
dbClassName );
m_database = (UserDatabase)dbClass.newInstance();
m_database.initialize( m_engine, props );
}
catch( ClassNotFoundException e )
{
log.fatal( "UserDatabase "+dbClassName+" cannot be found", e );
throw new WikiException("UserDatabase cannot be found");
}
catch( InstantiationException e )
{
log.fatal( "UserDatabase "+dbClassName+" cannot be created", e );
throw new WikiException("UserDatabase cannot be created");
}
catch( IllegalAccessException e )
{
log.fatal( "You are not allowed to access this user database class", e );
throw new WikiException("You are not allowed to access this user database class");
}
}
/**
* Convenience shortcut to UserDatabase.getUserProfile().
*/
public UserProfile getUserProfile( String name )
{
WikiPrincipal up = m_database.getPrincipal( name );
if( !(up instanceof UserProfile) )
{
log.info( name + " is not a user!" );
up = null;
}
return( (UserProfile)up );
}
/**
* Returns the UserDatabase employed by this UserManager.
*/
public UserDatabase getUserDatabase()
{
return( m_database );
}
/**
* Returns the WikiAuthenticator object employed by this UserManager.
*/
public WikiAuthenticator getAuthenticator()
{
return( m_authenticator );
}
/**
* Returns true, if the user or the group represents a super user,
* which should be allowed access to everything.
*
* @param p Principal to check for administrator access.
* @return true, if the principal is an administrator.
*/
public boolean isAdministrator( WikiPrincipal p )
{
// Direct name matches are returned always.
if( p.getName().equals( m_administrator ) )
{
return true;
}
// Try to get the super group and check if the user is a part
// of it.
WikiGroup superPrincipal = getWikiGroup( m_administrator );
System.out.println("superprincipal="+superPrincipal);
if( superPrincipal == null )
{
log.warn("No supergroup '"+m_administrator+"' exists; you should create one.");
return false;
}
return superPrincipal.isMember( p );
}
/**
* Returns a WikiGroup instance for a given name. WikiGroups are cached,
* so there is basically a singleton across the Wiki for a group.
* The reason why this class caches them instead of the WikiGroup
* class itself is that it is the business of the User Manager to
* handle such issues.
*
* @param name Name of the group. This is case-sensitive.
* @return A WikiGroup instance.
*/
// FIXME: Someone should really check when groups cease to be used,
// and release groups that are not being used.
// FIXME: Error handling is still deficient.
public WikiGroup getWikiGroup( String name )
{
WikiGroup group;
synchronized( m_groups )
{
group = (WikiGroup) m_groups.get( name );
if( group == null )
{
WikiPrincipal p = m_database.getPrincipal( name );
if( !(p instanceof WikiGroup) )
{
log.info( name+" is not a group!" );
}
else
{
group = (WikiGroup) p;
}
}
}
return group;
}
/**
* Returns a list of all WikiGroups this Principal is a member
* of.
*/
// FIXME: This is not a very good solution; UserProfile
// should really cache the information.
// FIXME: Should really query the page manager.
public List getGroupsForPrincipal( Principal user )
throws NoSuchPrincipalException
{
List list = null;
// Add the groups ONLY if the user has been authenticated.
// FIXME: This is probably the wrong place, since this prevents
// us from querying stuff later on.
if( user instanceof UserProfile && ((UserProfile)user).isAuthenticated() )
{
list = m_database.getGroupsForPrincipal( user );
}
if( list == null ) list = new ArrayList();
// Add the default groups.
synchronized( m_groups )
{
for( Iterator i = m_groups.values().iterator(); i.hasNext(); )
{
WikiGroup g = (WikiGroup) i.next();
if( g.isMember( user ) )
{
log.debug("User "+user.getName()+" is a member of "+g.getName());
list.add( g );
}
}
}
return list;
}
/**
* Attempts to find a Principal from the list of known principals.
*/
public Principal getPrincipal( String name )
{
Principal p = getWikiGroup( name );
if( p == null )
{
p = getUserProfile( name );
if( p == null )
{
log.debug("No such principal defined: "+name+", using UndefinedPrincipal");
p = new UndefinedPrincipal( name );
}
}
return p;
}
/**
* Attempts to perform a login for the given username/password
* combination. Also sets the attribute UserManager.WIKIUSER in the current session,
* which can then be used to fetch the current UserProfile. Or you can be lazy and
* just call getUserProfile()...
*
* @param username The user name. This is an user name, not a WikiName. In most cases
* they are the same, but in some cases, they might not be.
* @param password The password.
* @return true, if the username/password is valid.
*/
public boolean login( String username, String password, HttpSession session )
{
if( m_authenticator == null ) return false;
if( session == null )
{
log.error("No session provided, cannot log in.");
return false;
}
UserProfile wup = getUserProfile( username );
if( wup != null )
wup.setPassword( password );
boolean isValid = m_authenticator.authenticate( wup );
if( isValid )
{
wup.setLoginStatus( UserProfile.PASSWORD );
session.setAttribute( WIKIUSER, wup );
log.info("Logged in user "+username);
}
else
{
log.info("Username "+username+" attempted to log in with the wrong password.");
}
return isValid;
}
/**
* Logs a web user out, clearing the session.
*
* @param session The current HTTP session for this user.
*/
public void logout( HttpSession session )
{
if( session != null )
{
UserProfile wup = (UserProfile)session.getAttribute( WIKIUSER );
if( wup != null )
{
log.info( "logged out user " + wup.getName() );
wup.setLoginStatus( UserProfile.NONE );
}
session.invalidate();
}
}
public UserProfile getUserProfile( HttpServletRequest request )
{
// First, see if we already have a user profile.
HttpSession session = request.getSession( true );
UserProfile wup = (UserProfile)session.getAttribute( UserManager.WIKIUSER );
if( wup != null )
{
return wup;
}
// Try to get a limited login. This will be inserted into the request.
wup = limitedLogin( request );
if( wup != null )
{
return wup;
}
log.error( "Unable to get a default UserProfile!" );
return null;
}
/**
* Performs a "limited" login: sniffs for a user name from a cookie or the
* client, and creates a limited user profile based on it.
*/
protected UserProfile limitedLogin( HttpServletRequest request )
{
UserProfile wup = null;
String role = null;
// First, checks whether container has done authentication for us.
String uid = request.getRemoteUser();
if( uid != null )
{
wup = getUserProfile( uid );
if( wup != null )
{
wup.setLoginStatus( UserProfile.CONTAINER );
HttpSession session = request.getSession( true );
session.setAttribute( WIKIUSER, wup );
}
}
else
{
// See if a cookie exists, and create a default account.
uid = HttpUtil.retrieveCookieValue( request, WikiEngine.PREFS_COOKIE_NAME );
log.debug("Stored username="+uid);
if( uid != null )
{
wup = UserProfile.parseStringRepresentation( uid );
if( wup != null )
{
log.debug("wup="+wup);
wup.setLoginStatus( UserProfile.COOKIE );
}
}
else
{
// No username either, so fall back to the IP address.
if( m_storeIPAddress )
{
uid = request.getRemoteAddr();
}
if( uid == null )
{
uid = "unknown"; // FIXME: Magic
}
wup = getUserProfile( uid );
if( wup != null )
wup.setLoginStatus( UserProfile.NONE );
}
}
// If the UserDatabase declined to give us a UserPrincipal,
// we manufacture one here explicitly.
if( wup == null )
{
wup = new UserProfile();
wup.setName( GROUP_GUEST );
wup.setLoginStatus( UserProfile.NONE );
}
// FIXME:
// We cannot store the UserProfile into the session, because of the following:
// Assume that Edit.jsp is protected through container auth.
// User without a cookie arrives through Wiki.jsp. A
// UserProfile is created, which essentially contains his IP
// address. If this is stored in the session, then, when the user
// tries to access the Edit.jsp page and container does auth, he will
// always be then known by his IP address, regardless of what the
// request.getRemoteUser() says.
// So, until this is solved, we create a new UserProfile on each
// access. Ouch.
// Limited login hasn't been authenticated. Just to emphasize the point:
// wup.setPassword( null );
// HttpSession session = request.getSession( true );
// session.setAttribute( WIKIUSER, wup );
return wup;
}
/**
* Sets the username cookie.
*
* @since 2.1.47.
*/
public void setUserCookie( HttpServletResponse response, String name )
{
UserProfile profile = getUserProfile( TranslatorReader.cleanLink(name) );
Cookie prefs = new Cookie( WikiEngine.PREFS_COOKIE_NAME,
profile.getStringRepresentation() );
prefs.setMaxAge( 1001*24*60*60 ); // 1001 days is default.
response.addCookie( prefs );
}
}
|
package net.runelite.client.plugins.agility;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Set;
import static net.runelite.api.ObjectID.*;
import static net.runelite.api.NullObjectID.*;
public class Obstacles
{
public static final Set<Integer> COURSE_OBSTACLE_IDS = ImmutableSet.of(
// Gnome
OBSTACLE_NET_23134, TREE_BRANCH_23559, TREE_BRANCH_23560, OBSTACLE_NET_23135, OBSTACLE_PIPE_23138,
OBSTACLE_PIPE_23139, LOG_BALANCE_23145, BALANCING_ROPE_23557,
// Brimhaven
PLANK_3572, PLANK_3571, PLANK_3570, ROPE_SWING, PILLAR_3578, LOW_WALL, LOG_BALANCE, LOG_BALANCE_3557,
BALANCING_LEDGE_3561, BALANCING_LEDGE, MONKEY_BARS_3564, BALANCING_ROPE, HAND_HOLDS_3583,
// Draynor
ROUGH_WALL, TIGHTROPE, TIGHTROPE_10075, NARROW_WALL, WALL_10084, GAP_10085, CRATE_10086,
// Al-Kharid
ROUGH_WALL_10093, TIGHTROPE_10284, CABLE, ZIP_LINE, TROPICAL_TREE_10357, ROOF_TOP_BEAMS,
TIGHTROPE_10583, GAP_10352,
// Pyramid
STAIRS_10857, LOW_WALL_10865, LEDGE_10860, PLANK_10868, GAP_10882, LEDGE_10886, STAIRS_10857, GAP_10884,
GAP_10859, GAP_10861, LOW_WALL_10865, GAP_10859, LEDGE_10888, PLANK_10868, CLIMBING_ROCKS_10851, DOORWAY_10855,
// Varrock
ROUGH_WALL_10586, CLOTHES_LINE, GAP_10642, WALL_10777, GAP_10778, GAP_10779, GAP_10780, LEDGE_10781, EDGE,
// Penguin
STEPPING_STONE_21120, STEPPING_STONE_21126, STEPPING_STONE_21128, STEPPING_STONE_21129,
STEPPING_STONE_21130, STEPPING_STONE_21131, STEPPING_STONE_21132, STEPPING_STONE_21133,
ICICLES, ICE, ICE_21149, ICE_21150, ICE_21151, ICE_21152, ICE_21153, ICE_21154, ICE_21155, ICE_21156,
// Barbarian
ROPESWING_23131, LOG_BALANCE_23144, OBSTACLE_NET_20211, BALANCING_LEDGE_23547, LADDER_16682, CRUMBLING_WALL_1948,
// Canifis
TALL_TREE_10819, GAP_10820, GAP_10821, GAP_10828, GAP_10822, POLEVAULT, GAP_10823, GAP_10832,
// Ape atoll
STEPPING_STONE_15412, TROPICAL_TREE_15414, MONKEYBARS_15417, SKULL_SLOPE_15483, ROPE_15487, TROPICAL_TREE_16062,
// Falador
ROUGH_WALL_10833, TIGHTROPE_10834, HAND_HOLDS_10836, GAP_11161, GAP_11360, TIGHTROPE_11361,
TIGHTROPE_11364, GAP_11365, LEDGE_11366, LEDGE_11367, LEDGE_11368, LEDGE_11370, EDGE_11371,
// Wilderness
OBSTACLE_PIPE_23137, ROPESWING_23132, STEPPING_STONE_23556, LOG_BALANCE_23542, ROCKS_23640,
// Seers
WALL_11373, GAP_11374, TIGHTROPE_11378, GAP_11375, GAP_11376, EDGE_11377,
// Dorgesh-Kaan
CABLE_22569, CABLE_22572, LADDER_22564, JUTTING_WALL_22552, TUNNEL_22557, PYLON_22664,
CONSOLE, BOILER_22635, STAIRS_22650, STAIRS_22651, STAIRS_22609, STAIRS_22608,
// Pollniveach
BASKET_11380, MARKET_STALL_11381, BANNER_11382, GAP_11383, TREE_11384, ROUGH_WALL_11385,
MONKEYBARS, TREE_11389, DRYING_LINE,
// Rellaka
ROUGH_WALL_11391, GAP_11392, TIGHTROPE_11393, GAP_11395, GAP_11396, TIGHTROPE_11397, PILE_OF_FISH,
// Ardougne
GAP_11406, GAP_11429, GAP_11430, STEEP_ROOF, GAP_11630, PLANK_11631, WOODEN_BEAMS
);
public static final Set<Integer> SHORTCUT_OBSTACLE_IDS = ImmutableSet.of(
// Grand Exchange
UNDERWALL_TUNNEL_16529, UNDERWALL_TUNNEL_16530,
// South Varrock
STEPPING_STONE_16533, FENCE_16518, ROCKS_16549, ROCKS_16550,
// Falador
WALL_17049, CRUMBLING_WALL_24222, UNDERWALL_TUNNEL, UNDERWALL_TUNNEL_16528, CREVICE_16543,
// Draynor
UNDERWALL_TUNNEL_19032, UNDERWALL_TUNNEL_19036,
// South Lumbridge
BROKEN_RAFT, STEPPING_STONE_16513,
// Trollheim
ROCKS_3803, ROCKS_3804, ROCKS_16523, ROCKS_16524, ROCKS_3748, ROCKS_16545, ROCKS_16521, ROCKS_16522,
ROCKS_16464,
// North Camelot
LOG_BALANCE_16540, LOG_BALANCE_16541, LOG_BALANCE_16542,
// Rellekka
BROKEN_FENCE,
// Ardougne
LOG_BALANCE_16546, LOG_BALANCE_16547, LOG_BALANCE_16548,
// Yanille
CASTLE_WALL, HOLE_16520, WALL_17047,
// Observatory
NULL_31852,
// Gnome Stronghold
ROCKS_16534, ROCKS_16535,
// Karamja Volcano
STRONG_TREE_17074,
// Shilo Village
STEPPING_STONE_16466,
// Vine east of Shilo Village
NULL_26884, NULL_26886,
// Stepping stones east of Shilo Village
STEPPING_STONES, STEPPING_STONES_23646, STEPPING_STONES_23647,
// Middle of Karamja
A_WOODEN_LOG,
// Slayer Tower
SPIKEY_CHAIN, SPIKEY_CHAIN_16538,
// Fremennik Slayer Cave
STRANGE_FLOOR_16544, CREVICE_16539,
// Wilderness
STEPPING_STONE_14918, STEPPING_STONE_14917, ROCKY_HANDHOLDS_26404, ROCKY_HANDHOLDS_26405, ROCKY_HANDHOLDS_26406,
// Seers' Village Coal Mine
LOG_BALANCE_23274,
// Arceuus Essence Mine
ROCKS_27984, ROCKS_27985, BOULDER_27990, ROCKS_27987, ROCKS_27988,
// Wintertodt
GAP_29326,
// Gnome Stronghold Slayer Underground
TUNNEL_30174, TUNNEL_30175,
// Taverley Underground
OBSTACLE_PIPE_16509, STRANGE_FLOOR, ROCKS, ROCKS_14106, LOOSE_RAILING_28849,
// Heroes Guild
CREVICE_9739, CREVICE_9740,
// Fossil Island
HOLE_31481, HOLE_31482, LADDER_30938, LADDER_30939, LADDER_30940, LADDER_30941, ROPE_ANCHOR, ROPE_ANCHOR_30917,
RUBBER_CAP_MUSHROOM,
ROCKS_31757, ROCKS_31758, ROCKS_31759, PILLAR_31809,
// West Brimhaven
ROPESWING_23568, ROPESWING_23569,
// Brimhaven Dungeon
VINE_26880, VINE_26882, PIPE_21728, STEPPING_STONE_19040, PIPE_21727, LOG_BALANCE_20882, LOG_BALANCE_20884,
STEPPING_STONE_21738, STEPPING_STONE_21739, TIGHTGAP,
// Lumbridge
STILE_12982,
// Edgeville Dungeon
MONKEYBARS_23566, OBSTACLE_PIPE_16511,
// Miscellania
STEPPING_STONE_11768,
// Kalphite
CREVICE_16465,
// Eagles' Peak
ROCKS_19849,
// Catherby
CROSSBOW_TREE_17062, ROCKS_17042,
// Cairn Isle
ROCKS_2231,
// South Kourend
STEPPING_STONE_29728, STEPPING_STONE_29729, STEPPING_STONE_29730,
// Cosmic Temple
JUTTING_WALL_17002,
// Arandar
ROCKS_16514, ROCKS_16515, LOG_BALANCE_3933,
// South River Salve
STEPPING_STONE_13504,
DARK_TUNNEL_10047,
// Ectofuntus
WEATHERED_WALL, WEATHERED_WALL_16526,
// Mos Le'Harmless
STEPPING_STONE_19042,
// North River Salve
ROCKS_16998, ROCKS_16999,
// West Zul-Andra
STEPPING_STONE_10663,
// Yanille Agility Dungeon
BALANCING_LEDGE_23548, OBSTACLE_PIPE_23140, MONKEYBARS_23567, PILE_OF_RUBBLE_23563, PILE_OF_RUBBLE_23564,
// High Level Wilderness Dungeon
CREVICE_19043,
// Revenant Caves
PILLAR_31561,
// Elf Camp Isafdar Tirranwn
LOG_BALANCE_3931, LOG_BALANCE_3930, LOG_BALANCE_3929, LOG_BALANCE_3932, DENSE_FOREST_3938, DENSE_FOREST_3939,
DENSE_FOREST_3998, DENSE_FOREST_3999, DENSE_FOREST, LEAVES, LEAVES_3924, LEAVES_3925, STICKS, TRIPWIRE,
// Gu'Tanoth bridge
GAP, GAP_2831,
// Lumbridge Swamp Caves
STEPPING_STONE_5948, STEPPING_STONE_5949,
// Morytania Pirate Ship
ROCK_16115,
// Agility Pyramid Entrance
CLIMBING_ROCKS_11948, CLIMBING_ROCKS_11949
);
public static final Set<Integer> TRAP_OBSTACLE_IDS = ImmutableSet.of(
// Agility pyramid
NULL_3550, NULL_10872, NULL_10873
);
public static final List<Integer> TRAP_OBSTACLE_REGIONS = ImmutableList.of(12105, 13356);
}
|
package com.ecyrd.jspwiki.auth;
import java.util.*;
import java.security.Principal;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import java.security.Principal;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.TranslatorReader;
import com.ecyrd.jspwiki.util.ClassUtil;
import com.ecyrd.jspwiki.util.HttpUtil;
import com.ecyrd.jspwiki.auth.modules.*;
/**
* Manages user accounts, logins/logouts, passwords, etc.
*
* @author Janne Jalkanen
* @author Erik Bunn
*/
public class UserManager
{
static Category log = Category.getInstance( UserManager.class );
/** The name the UserProfile is stored in a Session by. */
public static final String WIKIUSER = "currentUser";
/** If true, logs the IP address of the editor on saving. */
public static final String PROP_STOREIPADDRESS= "jspwiki.storeIPAddress";
public static final String PROP_AUTHENTICATOR = "jspwiki.authenticator";
public static final String PROP_USERDATABASE = "jspwiki.userdatabase";
public static final String PROP_ADMINISTRATOR = "jspwiki.auth.administrator";
/** If true, logs the IP address of the editor */
private boolean m_storeIPAddress = true;
private HashMap m_groups = new HashMap();
// FIXME: These should probably be localized.
// FIXME: All is used as a catch-all.
public static final String GROUP_GUEST = "Guest";
public static final String GROUP_NAMEDGUEST = "NamedGuest";
public static final String GROUP_KNOWNPERSON = "KnownPerson";
private static final String DEFAULT_DATABASE = "com.ecyrd.jspwiki.auth.modules.WikiDatabase";
/**
* The default administrator group is called "AdminGroup"
*/
private static final String DEFAULT_ADMINISTRATOR = "AdminGroup";
private WikiAuthenticator m_authenticator;
private UserDatabase m_database;
private WikiEngine m_engine;
private String m_administrator;
/**
* Creates an UserManager instance for the given WikiEngine and
* the specified set of properties. All initialization for the
* modules is done here.
*/
public UserManager( WikiEngine engine, Properties props )
throws WikiException
{
m_engine = engine;
m_storeIPAddress = TextUtil.getBooleanProperty( props,
PROP_STOREIPADDRESS,
m_storeIPAddress );
m_administrator = props.getProperty( PROP_ADMINISTRATOR,
DEFAULT_ADMINISTRATOR );
WikiGroup all = new AllGroup();
all.setName( "All" );
m_groups.put( GROUP_GUEST, new AllGroup() );
// m_groups.put( "All", all );
m_groups.put( GROUP_NAMEDGUEST, new NamedGroup() );
m_groups.put( GROUP_KNOWNPERSON, new KnownGroup() );
String authClassName = props.getProperty( PROP_AUTHENTICATOR );
if( authClassName != null )
{
try
{
Class authenticatorClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.modules",
authClassName );
m_authenticator = (WikiAuthenticator)authenticatorClass.newInstance();
m_authenticator.initialize( props );
log.info("Initialized "+authClassName+" for authentication.");
}
catch( ClassNotFoundException e )
{
log.fatal( "Authenticator "+authClassName+" cannot be found", e );
throw new WikiException("Authenticator cannot be found");
}
catch( InstantiationException e )
{
log.fatal( "Authenticator "+authClassName+" cannot be created", e );
throw new WikiException("Authenticator cannot be created");
}
catch( IllegalAccessException e )
{
log.fatal( "You are not allowed to access this authenticator class", e );
throw new WikiException("You are not allowed to access this authenticator class");
}
}
String dbClassName = props.getProperty( PROP_USERDATABASE,
DEFAULT_DATABASE );
try
{
Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.modules",
dbClassName );
m_database = (UserDatabase)dbClass.newInstance();
m_database.initialize( m_engine, props );
}
catch( ClassNotFoundException e )
{
log.fatal( "UserDatabase "+dbClassName+" cannot be found", e );
throw new WikiException("UserDatabase cannot be found");
}
catch( InstantiationException e )
{
log.fatal( "UserDatabase "+dbClassName+" cannot be created", e );
throw new WikiException("UserDatabase cannot be created");
}
catch( IllegalAccessException e )
{
log.fatal( "You are not allowed to access this user database class", e );
throw new WikiException("You are not allowed to access this user database class");
}
}
/**
* Convenience shortcut to UserDatabase.getUserProfile().
*/
public UserProfile getUserProfile( String name )
{
WikiPrincipal up = m_database.getPrincipal( name );
if( !(up instanceof UserProfile) )
{
log.info( name + " is not a user!" );
up = null;
}
return( (UserProfile)up );
}
/**
* Returns the UserDatabase employed by this UserManager.
*/
public UserDatabase getUserDatabase()
{
return( m_database );
}
/**
* Returns the WikiAuthenticator object employed by this UserManager.
*/
public WikiAuthenticator getAuthenticator()
{
return( m_authenticator );
}
/**
* Returns true, if the user or the group represents a super user,
* which should be allowed access to everything.
*
* @param p Principal to check for administrator access.
* @return true, if the principal is an administrator.
*/
public boolean isAdministrator( WikiPrincipal p )
{
// Direct name matches are returned always.
if( p.getName().equals( m_administrator ) )
{
return true;
}
// Try to get the super group and check if the user is a part
// of it.
WikiGroup superPrincipal = getWikiGroup( m_administrator );
System.out.println("superprincipal="+superPrincipal);
if( superPrincipal == null )
{
log.warn("No supergroup '"+m_administrator+"' exists; you should create one.");
return false;
}
return superPrincipal.isMember( p );
}
/**
* Returns a WikiGroup instance for a given name. WikiGroups are cached,
* so there is basically a singleton across the Wiki for a group.
* The reason why this class caches them instead of the WikiGroup
* class itself is that it is the business of the User Manager to
* handle such issues.
*
* @param name Name of the group. This is case-sensitive.
* @return A WikiGroup instance.
*/
// FIXME: Someone should really check when groups cease to be used,
// and release groups that are not being used.
// FIXME: Error handling is still deficient.
public WikiGroup getWikiGroup( String name )
{
WikiGroup group;
synchronized( m_groups )
{
group = (WikiGroup) m_groups.get( name );
if( group == null )
{
WikiPrincipal p = m_database.getPrincipal( name );
if( !(p instanceof WikiGroup) )
{
log.info( name+" is not a group!" );
}
else
{
group = (WikiGroup) p;
}
}
}
return group;
}
/**
* Returns a list of all WikiGroups this Principal is a member
* of.
*/
// FIXME: This is not a very good solution; UserProfile
// should really cache the information.
// FIXME: Should really query the page manager.
public List getGroupsForPrincipal( Principal user )
throws NoSuchPrincipalException
{
List list = null;
// Add the groups ONLY if the user has been authenticated.
// FIXME: This is probably the wrong place, since this prevents
// us from querying stuff later on.
if( user instanceof UserProfile && ((UserProfile)user).isAuthenticated() )
{
list = m_database.getGroupsForPrincipal( user );
}
if( list == null ) list = new ArrayList();
// Add the default groups.
synchronized( m_groups )
{
for( Iterator i = m_groups.values().iterator(); i.hasNext(); )
{
WikiGroup g = (WikiGroup) i.next();
if( g.isMember( user ) )
{
log.debug("User "+user.getName()+" is a member of "+g.getName());
list.add( g );
}
}
}
return list;
}
/**
* Attempts to find a Principal from the list of known principals.
*/
public Principal getPrincipal( String name )
{
Principal p = getWikiGroup( name );
if( p == null )
{
p = getUserProfile( name );
if( p == null )
{
log.debug("No such principal defined: "+name+", using UndefinedPrincipal");
p = new UndefinedPrincipal( name );
}
}
return p;
}
/**
* Attempts to perform a login for the given username/password
* combination. Also sets the attribute UserManager.WIKIUSER in the current session,
* which can then be used to fetch the current UserProfile. Or you can be lazy and
* just call getUserProfile()...
*
* @param username The user name. This is an user name, not a WikiName. In most cases
* they are the same, but in some cases, they might not be.
* @param password The password.
* @return true, if the username/password is valid.
*/
public boolean login( String username, String password, HttpSession session )
{
if( m_authenticator == null ) return false;
if( session == null )
{
log.error("No session provided, cannot log in.");
return false;
}
UserProfile wup = getUserProfile( username );
wup.setPassword( password );
boolean isValid = m_authenticator.authenticate( wup );
if( isValid )
{
wup.setLoginStatus( UserProfile.PASSWORD );
session.setAttribute( WIKIUSER, wup );
log.info("Logged in user "+username);
}
else
{
log.info("Username "+username+" attempted to log in with the wrong password.");
}
return isValid;
}
/**
* Logs a web user out, clearing the session.
*
* @param session The current HTTP session for this user.
*/
public void logout( HttpSession session )
{
if( session != null )
{
UserProfile wup = (UserProfile)session.getAttribute( WIKIUSER );
if( wup != null )
{
log.info( "logged out user " + wup.getName() );
wup.setLoginStatus( UserProfile.NONE );
}
session.invalidate();
}
}
public UserProfile getUserProfile( HttpServletRequest request )
{
// First, see if we already have a user profile.
HttpSession session = request.getSession( true );
UserProfile wup = (UserProfile)session.getAttribute( UserManager.WIKIUSER );
if( wup != null )
{
return wup;
}
// Try to get a limited login. This will be inserted into the request.
wup = limitedLogin( request );
if( wup != null )
{
return wup;
}
log.error( "Unable to get a default UserProfile!" );
return null;
}
/**
* Performs a "limited" login: sniffs for a user name from a cookie or the
* client, and creates a limited user profile based on it.
*/
protected UserProfile limitedLogin( HttpServletRequest request )
{
UserProfile wup = null;
String role = null;
// First, checks whether container has done authentication for us.
String uid = request.getRemoteUser();
if( uid != null )
{
wup = getUserProfile( uid );
wup.setLoginStatus( UserProfile.CONTAINER );
HttpSession session = request.getSession( true );
session.setAttribute( WIKIUSER, wup );
}
else
{
// See if a cookie exists, and create a default account.
uid = HttpUtil.retrieveCookieValue( request, WikiEngine.PREFS_COOKIE_NAME );
log.debug("Stored username="+uid);
if( uid != null )
{
wup = UserProfile.parseStringRepresentation( uid );
log.debug("wup="+wup);
wup.setLoginStatus( UserProfile.COOKIE );
}
else
{
// No username either, so fall back to the IP address.
if( m_storeIPAddress )
{
uid = request.getRemoteAddr();
}
if( uid == null )
{
uid = "unknown"; // FIXME: Magic
}
wup = getUserProfile( uid );
wup.setLoginStatus( UserProfile.NONE );
}
}
// FIXME:
// We cannot store the UserProfile into the session, because of the following:
// Assume that Edit.jsp is protected through container auth.
// User without a cookie arrives through Wiki.jsp. A
// UserProfile is created, which essentially contains his IP
// address. If this is stored in the session, then, when the user
// tries to access the Edit.jsp page and container does auth, he will
// always be then known by his IP address, regardless of what the
// request.getRemoteUser() says.
// So, until this is solved, we create a new UserProfile on each
// access. Ouch.
// Limited login hasn't been authenticated. Just to emphasize the point:
// wup.setPassword( null );
// HttpSession session = request.getSession( true );
// session.setAttribute( WIKIUSER, wup );
return wup;
}
/**
* Sets the username cookie.
*
* @since 2.1.47.
*/
public void setUserCookie( HttpServletResponse response, String name )
{
UserProfile profile = getUserProfile( TranslatorReader.cleanLink(name) );
Cookie prefs = new Cookie( WikiEngine.PREFS_COOKIE_NAME,
profile.getStringRepresentation() );
prefs.setMaxAge( 1001*24*60*60 ); // 1001 days is default.
response.addCookie( prefs );
}
}
|
package com.quickblox.sample.chat.ui.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.quickblox.sample.chat.R;
import com.quickblox.sample.chat.utils.UiUtils;
import com.quickblox.sample.chat.utils.chat.ChatHelper;
import com.quickblox.sample.core.ui.adapter.BaseListAdapter;
import com.quickblox.sample.core.utils.ResourceUtils;
import com.quickblox.users.model.QBUser;
import java.util.List;
public class UsersAdapter extends BaseListAdapter<QBUser> {
public UsersAdapter(Context context, List<QBUser> users) {
super(context, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
QBUser user = getItem(position);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_user, parent, false);
holder = new ViewHolder();
holder.userImageView = (ImageView) convertView.findViewById(R.id.image_user);
holder.loginTextView = (TextView) convertView.findViewById(R.id.text_user_login);
holder.userCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox_user);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (isUserMe(user)) {
holder.loginTextView.setText(context.getString(R.string.placeholder_username_you, user.getFullName()));
} else {
holder.loginTextView.setText(user.getFullName());
}
if (isAvailableForSelection(user)) {
holder.loginTextView.setTextColor(ResourceUtils.getColor(R.color.text_color_black));
} else {
holder.loginTextView.setTextColor(ResourceUtils.getColor(R.color.text_color_medium_grey));
}
holder.userImageView.setBackgroundDrawable(UiUtils.getColorCircleDrawable(position));
holder.userCheckBox.setVisibility(View.GONE);
return convertView;
}
protected boolean isUserMe(QBUser user) {
QBUser currentUser = ChatHelper.getCurrentUser();
return currentUser != null && currentUser.getId().equals(user.getId());
}
protected boolean isAvailableForSelection(QBUser user) {
QBUser currentUser = ChatHelper.getCurrentUser();
return currentUser == null || !currentUser.getId().equals(user.getId());
}
protected static class ViewHolder {
ImageView userImageView;
TextView loginTextView;
CheckBox userCheckBox;
}
}
|
package com.ecyrd.jspwiki.auth;
import java.util.*;
import java.security.Principal;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.TranslatorReader;
import com.ecyrd.jspwiki.util.ClassUtil;
import com.ecyrd.jspwiki.util.HttpUtil;
/**
* Manages user accounts, logins/logouts, passwords, etc.
*
* @author Janne Jalkanen
* @author Erik Bunn
*/
public class UserManager
{
static Logger log = Logger.getLogger( UserManager.class );
/** The name the UserProfile is stored in a Session by. */
public static final String WIKIUSER = "currentUser";
/** If true, logs the IP address of the editor on saving. */
public static final String PROP_STOREIPADDRESS= "jspwiki.storeIPAddress";
public static final String PROP_AUTHENTICATOR = "jspwiki.authenticator";
public static final String PROP_USERDATABASE = "jspwiki.userdatabase";
public static final String PROP_ADMINISTRATOR = "jspwiki.auth.administrator";
/** If true, logs the IP address of the editor */
private boolean m_storeIPAddress = true;
private HashMap m_groups = new HashMap();
// FIXME: These should probably be localized.
// FIXME: All is used as a catch-all.
public static final String GROUP_GUEST = "Guest";
public static final String GROUP_NAMEDGUEST = "NamedGuest";
public static final String GROUP_KNOWNPERSON = "KnownPerson";
private static final String DEFAULT_DATABASE = "com.ecyrd.jspwiki.auth.modules.WikiDatabase";
/**
* The default administrator group is called "AdminGroup"
*/
private static final String DEFAULT_ADMINISTRATOR = "AdminGroup";
private WikiAuthenticator m_authenticator;
private UserDatabase m_database;
private WikiEngine m_engine;
private String m_administrator;
private boolean m_useAuth = false;
/**
* Creates an UserManager instance for the given WikiEngine and
* the specified set of properties. All initialization for the
* modules is done here.
*/
public UserManager( WikiEngine engine, Properties props )
throws WikiException
{
m_engine = engine;
m_storeIPAddress = TextUtil.getBooleanProperty( props,
PROP_STOREIPADDRESS,
m_storeIPAddress );
m_administrator = props.getProperty( PROP_ADMINISTRATOR,
DEFAULT_ADMINISTRATOR );
m_useAuth = TextUtil.getBooleanProperty( props,
AuthorizationManager.PROP_USEOLDAUTH,
false );
if( !m_useAuth ) return;
WikiGroup all = new AllGroup();
all.setName( "All" );
m_groups.put( GROUP_GUEST, new AllGroup() );
// m_groups.put( "All", all );
m_groups.put( GROUP_NAMEDGUEST, new NamedGroup() );
m_groups.put( GROUP_KNOWNPERSON, new KnownGroup() );
String authClassName = props.getProperty( PROP_AUTHENTICATOR );
if( authClassName != null )
{
try
{
Class authenticatorClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.modules",
authClassName );
m_authenticator = (WikiAuthenticator)authenticatorClass.newInstance();
m_authenticator.initialize( props );
log.info("Initialized "+authClassName+" for authentication.");
}
catch( ClassNotFoundException e )
{
log.fatal( "Authenticator "+authClassName+" cannot be found", e );
throw new WikiException("Authenticator cannot be found");
}
catch( InstantiationException e )
{
log.fatal( "Authenticator "+authClassName+" cannot be created", e );
throw new WikiException("Authenticator cannot be created");
}
catch( IllegalAccessException e )
{
log.fatal( "You are not allowed to access this authenticator class", e );
throw new WikiException("You are not allowed to access this authenticator class");
}
}
String dbClassName = props.getProperty( PROP_USERDATABASE,
DEFAULT_DATABASE );
try
{
Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.modules",
dbClassName );
m_database = (UserDatabase)dbClass.newInstance();
m_database.initialize( m_engine, props );
}
catch( ClassNotFoundException e )
{
log.fatal( "UserDatabase "+dbClassName+" cannot be found", e );
throw new WikiException("UserDatabase cannot be found");
}
catch( InstantiationException e )
{
log.fatal( "UserDatabase "+dbClassName+" cannot be created", e );
throw new WikiException("UserDatabase cannot be created");
}
catch( IllegalAccessException e )
{
log.fatal( "You are not allowed to access this user database class", e );
throw new WikiException("You are not allowed to access this user database class");
}
}
/**
* Convenience shortcut to UserDatabase.getUserProfile().
*/
public UserProfile getUserProfile( String name )
{
if( m_database == null ) return null;
WikiPrincipal up = m_database.getPrincipal( name );
if( !(up instanceof UserProfile) )
{
log.info( name + " is not a user!" );
up = null;
}
return( (UserProfile)up );
}
/**
* Returns the UserDatabase employed by this UserManager.
*/
public UserDatabase getUserDatabase()
{
return( m_database );
}
/**
* Returns the WikiAuthenticator object employed by this UserManager.
*/
public WikiAuthenticator getAuthenticator()
{
return( m_authenticator );
}
/**
* Returns true, if the user or the group represents a super user,
* which should be allowed access to everything.
*
* @param p Principal to check for administrator access.
* @return true, if the principal is an administrator.
*/
public boolean isAdministrator( WikiPrincipal p )
{
// Direct name matches are returned always.
if( p.getName().equals( m_administrator ) )
{
return true;
}
// Try to get the super group and check if the user is a part
// of it.
WikiGroup superPrincipal = getWikiGroup( m_administrator );
if( superPrincipal == null )
{
// log.warn("No supergroup '"+m_administrator+"' exists; you should create one.");
return false;
}
return superPrincipal.isMember( p );
}
/**
* Returns a WikiGroup instance for a given name. WikiGroups are cached,
* so there is basically a singleton across the Wiki for a group.
* The reason why this class caches them instead of the WikiGroup
* class itself is that it is the business of the User Manager to
* handle such issues.
*
* @param name Name of the group. This is case-sensitive.
* @return A WikiGroup instance.
*/
// FIXME: Someone should really check when groups cease to be used,
// and release groups that are not being used.
// FIXME: Error handling is still deficient.
public WikiGroup getWikiGroup( String name )
{
WikiGroup group;
synchronized( m_groups )
{
group = (WikiGroup) m_groups.get( name );
if( group == null )
{
WikiPrincipal p = m_database.getPrincipal( name );
if( !(p instanceof WikiGroup) )
{
log.info( name+" is not a group!" );
}
else
{
group = (WikiGroup) p;
}
}
}
return group;
}
/**
* Returns a list of all WikiGroups this Principal is a member
* of.
*/
// FIXME: This is not a very good solution; UserProfile
// should really cache the information.
// FIXME: Should really query the page manager.
public List getGroupsForPrincipal( Principal user )
throws NoSuchPrincipalException
{
List list = null;
// Add the groups ONLY if the user has been authenticated.
// FIXME: This is probably the wrong place, since this prevents
// us from querying stuff later on.
if( user instanceof UserProfile && ((UserProfile)user).isAuthenticated() )
{
if( m_database != null )
list = m_database.getGroupsForPrincipal( user );
}
if( list == null ) list = new ArrayList();
// Add the default groups.
synchronized( m_groups )
{
for( Iterator i = m_groups.values().iterator(); i.hasNext(); )
{
WikiGroup g = (WikiGroup) i.next();
if( g.isMember( user ) )
{
log.debug("User "+user.getName()+" is a member of "+g.getName());
list.add( g );
}
}
}
return list;
}
/**
* Attempts to find a Principal from the list of known principals.
*/
public Principal getPrincipal( String name )
{
Principal p = getWikiGroup( name );
if( p == null )
{
p = getUserProfile( name );
if( p == null )
{
log.debug("No such principal defined: "+name+", using UndefinedPrincipal");
p = new UndefinedPrincipal( name );
}
}
return p;
}
/**
* Attempts to perform a login for the given username/password
* combination. Also sets the attribute UserManager.WIKIUSER in the current session,
* which can then be used to fetch the current UserProfile. Or you can be lazy and
* just call getUserProfile()...
*
* @param username The user name. This is an user name, not a WikiName. In most cases
* they are the same, but in some cases, they might not be.
* @param password The password.
* @return true, if the username/password is valid.
* @throws PasswordException, if password has expired
*/
public boolean login( String username, String password, HttpSession session )
throws WikiSecurityException
{
if( m_authenticator == null ) return false;
if( session == null )
{
log.error("No session provided, cannot log in.");
return false;
}
UserProfile wup = getUserProfile( username );
if( wup != null )
{
wup.setPassword( password );
boolean isValid = false;
boolean expired = false;
try
{
isValid = m_authenticator.authenticate( wup );
}
catch( PasswordExpiredException e )
{
isValid = true;
expired = true;
}
if( isValid )
{
wup.setLoginStatus( UserProfile.PASSWORD );
session.setAttribute( WIKIUSER, wup );
log.info("Logged in user "+username);
if( expired ) throw new PasswordExpiredException(""); //FIXME!
}
else
{
log.info("Username "+username+" attempted to log in with the wrong password.");
}
return isValid;
}
return false;
}
/**
* Logs a web user out, clearing the session.
*
* @param session The current HTTP session for this user.
*/
public void logout( HttpSession session )
{
if( session != null )
{
UserProfile wup = (UserProfile)session.getAttribute( WIKIUSER );
if( wup != null )
{
log.info( "logged out user " + wup.getName() );
wup.setLoginStatus( UserProfile.NONE );
}
session.invalidate();
}
}
public UserProfile getUserProfile( HttpServletRequest request )
{
// First, see if we already have a user profile.
HttpSession session = request.getSession( true );
UserProfile wup = (UserProfile)session.getAttribute( UserManager.WIKIUSER );
if( wup != null )
{
return wup;
}
// Try to get a limited login. This will be inserted into the request.
wup = limitedLogin( request );
if( wup != null )
{
return wup;
}
log.error( "Unable to get a default UserProfile!" );
return null;
}
/**
* Performs a "limited" login: sniffs for a user name from a cookie or the
* client, and creates a limited user profile based on it.
*/
protected UserProfile limitedLogin( HttpServletRequest request )
{
UserProfile wup = null;
String role = null;
// First, checks whether container has done authentication for us.
String uid = request.getRemoteUser();
if( uid != null )
{
wup = getUserProfile( uid );
if( wup != null )
{
wup.setLoginStatus( UserProfile.CONTAINER );
HttpSession session = request.getSession( true );
session.setAttribute( WIKIUSER, wup );
}
}
else
{
// See if a cookie exists, and create a default account.
uid = HttpUtil.retrieveCookieValue( request, WikiEngine.PREFS_COOKIE_NAME );
log.debug("Stored username="+uid);
if( uid != null )
{
try
{
wup = UserProfile.parseStringRepresentation( uid );
if( wup != null )
{
wup.setLoginStatus( UserProfile.COOKIE );
}
}
catch( NoSuchElementException e )
{
// We fail silently, as the cookie is invalid.
}
}
}
// If the UserDatabase declined to give us a UserPrincipal,
// we manufacture one here explicitly.
if( wup == null )
{
wup = new UserProfile();
wup.setLoginName( GROUP_GUEST );
wup.setLoginStatus( UserProfile.NONE );
// No username either, so fall back to the IP address.
if( m_storeIPAddress )
{
wup.setName( request.getRemoteHost() );
}
else
{
wup.setName( wup.getLoginName() );
}
}
// FIXME:
// We cannot store the UserProfile into the session, because of the following:
// Assume that Edit.jsp is protected through container auth.
// User without a cookie arrives through Wiki.jsp. A
// UserProfile is created, which essentially contains his IP
// address. If this is stored in the session, then, when the user
// tries to access the Edit.jsp page and container does auth, he will
// always be then known by his IP address, regardless of what the
// request.getRemoteUser() says.
// So, until this is solved, we create a new UserProfile on each
// access. Ouch.
// Limited login hasn't been authenticated. Just to emphasize the point:
// wup.setPassword( null );
// HttpSession session = request.getSession( true );
// session.setAttribute( WIKIUSER, wup );
return wup;
}
/**
* Sets the username cookie.
*
* @since 2.1.47.
*/
public void setUserCookie( HttpServletResponse response, String name )
{
UserProfile profile = getUserProfile( TranslatorReader.cleanLink(name) );
Cookie prefs = new Cookie( WikiEngine.PREFS_COOKIE_NAME,
profile.getStringRepresentation() );
prefs.setMaxAge( 1001*24*60*60 ); // 1001 days is default.
response.addCookie( prefs );
}
}
|
package org.apache.lucene.wordnet;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Document;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class Syns2Index
{
private static final Analyzer ana = new StandardAnalyzer();
/**
* Takes optional arg of prolog file name.
*/
public static void main(String[] args)
throws Throwable
{
// get command line arguments
String prologFilename = null;
String indexDir = null;
if (args.length == 2)
{
prologFilename = args[0];
indexDir = args[1];
}
else
{
usage();
System.exit(1);
}
// ensure that the prolog file is readable
if (! (new File(prologFilename)).canRead())
{
System.err.println("Error: cannot read Prolog file: " + prologFilename);
System.exit(1);
}
// exit if the target index directory already exists
if ((new File(indexDir)).isDirectory())
{
System.err.println("Error: index directory already exists: " + indexDir);
System.err.println("Please specify a name of a non-existent directory");
System.exit(1);
}
System.out.println("Opening Prolog file " + prologFilename);
final FileInputStream fis = new FileInputStream(prologFilename);
final DataInputStream dis = new DataInputStream(fis);
String line;
// maps a word to all the "groups" it's in
final Map word2Nums = new HashMap();
// maps a group to all the words in it
final Map num2Words = new HashMap();
// number of rejected words
int ndecent = 0;
// status output
int mod = 1;
int row = 1;
// parse prolog file
while ((line = dis.readLine()) != null)
{
String oline = line;
// occasional progress
if ((++row) % mod == 0)
{
mod *= 2;
System.out.println("" + row + " " + line + " " + word2Nums.size()
+ " " + num2Words.size() + " ndecent=" + ndecent);
}
// syntax check
if (! line.startsWith("s("))
{
System.err.println("OUCH: " + line);
System.exit(1);
}
// parse line
line = line.substring(2);
int comma = line.indexOf(',');
String num = line.substring(0, comma);
int q1 = line.indexOf('\'');
line = line.substring(q1 + 1);
int q2 = line.indexOf('\'');
String word = line.substring(0, q2).toLowerCase();
// make sure is a normal word
if (! isDecent(word))
{
ndecent++;
continue; // don't store words w/ spaces
}
// 1/2: word2Nums map
// append to entry or add new one
List lis =(List) word2Nums.get(word);
if (lis == null)
{
lis = new LinkedList();
lis.add(num);
word2Nums.put(word, lis);
}
else
lis.add(num);
// 2/2: num2Words map
lis = (List) num2Words.get(num);
if (lis == null)
{
lis = new LinkedList();
lis.add(word);
num2Words.put(num, lis);
}
else
lis.add(word);
}
// close the streams
fis.close();
dis.close();
// create the index
index(indexDir, word2Nums, num2Words);
}
/**
* Checks to see if a word contains only alphabetic characters by
* checking it one character at a time.
*
* @param s string to check
* @return <code>true</code> if the string is decent
*/
private static boolean isDecent(String s)
{
int len = s.length();
for (int i = 0; i < len; i++)
{
if (!Character.isLetter(s.charAt(i)))
{
return false;
}
}
return true;
}
/**
* Forms a Lucene index based on the 2 maps.
*
* @param indexDir the direcotry where the index should be created
* @param word2Nums
* @param num2Words
*/
private static void index(String indexDir, Map word2Nums, Map num2Words)
throws Throwable
{
int row = 0;
int mod = 1;
// override the specific index if it already exists
IndexWriter writer = new IndexWriter(indexDir, ana, true);
writer.setUseCompoundFile(true);
Iterator i1 = word2Nums.keySet().iterator();
while (i1.hasNext()) // for each word
{
String g = (String) i1.next();
Document doc = new Document();
int n = index(word2Nums, num2Words, g, doc);
if (n > 0)
{
doc.add(Field.Keyword("word", g));
if ((++row % mod) == 0)
{
System.out.println("row=" + row + " doc= " + doc);
mod *= 2;
}
writer.addDocument(doc);
} // else degenerate
}
writer.optimize();
writer.close();
}
/**
* Given the 2 maps fills a document for 1 word.
*/
private static int index(Map word2Nums, Map num2Words, String g, Document doc)
throws Throwable
{
List keys = (List) word2Nums.get(g); // get list of key
Iterator i2 = keys.iterator();
Set already = new TreeSet(); // keep them sorted
// pass 1: fill up 'already' with all words
while (i2.hasNext()) // for each key
{
already.addAll((List) num2Words.get(i2.next())); // get list of words
}
int num = 0;
already.remove(g); // of course a word is it's own syn
Iterator it = already.iterator();
while (it.hasNext())
{
String cur = (String) it.next();
// don't store things like 'pit bull' -> 'american pit bull'
if (!isDecent(cur))
{
continue;
}
num++;
doc.add(Field.UnIndexed("syn" , cur));
}
return num;
}
private static void usage()
{
System.out.println("\n\n" +
"java org.apache.lucene.wordnet.Syn2Index <prolog file> <index dir>\n\n");
}
}
|
package com.ecyrd.jspwiki.tags;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiPage;
import com.ecyrd.jspwiki.WikiProvider;
/**
* Writes a diff link. Body of the link becomes the link text.
* <P><B>Attributes</B></P>
* <UL>
* <LI>page - Page name to refer to. Default is the current page.</LI>
* <LI>version - The older of these versions. May be an integer to
* signify a version number, or the text "latest" to signify the latest version.
* If not specified, will default to "latest". May also be "previous" to signify
* a version prior to this particular version.</LI>
* <LI>newVersion - The newer of these versions. Can also be "latest", or "previous". Defaults to "latest".</LI>
* </UL>
*
* If the page does not exist, this tag will fail silently, and not evaluate
* its body contents.
*
* @author Janne Jalkanen
* @since 2.0
*/
public class DiffLinkTag
extends WikiLinkTag
{
public static final String VER_LATEST = "latest";
public static final String VER_PREVIOUS = "previous";
public static final String VER_CURRENT = "current";
private String m_version = VER_LATEST;
private String m_newVersion = VER_LATEST;
public final String getVersion()
{
return m_version;
}
public void setVersion( String arg )
{
m_version = arg;
}
public final String getNewVersion()
{
return m_newVersion;
}
public void setNewVersion( String arg )
{
m_newVersion = arg;
}
public final int doWikiStartTag()
throws IOException
{
WikiEngine engine = m_wikiContext.getEngine();
String pageName = m_pageName;
if( m_pageName == null )
{
if( m_wikiContext.getPage() != null )
{
pageName = m_wikiContext.getPage().getName();
}
else
{
return SKIP_BODY;
}
}
JspWriter out = pageContext.getOut();
String encodedlink = engine.encodeName( pageName );
int r1 = 0;
int r2 = 0;
// In case the page does not exist, we fail silently.
if(!engine.pageExists(pageName))
{
return SKIP_BODY;
}
if( VER_LATEST.equals(getVersion()) )
{
WikiPage latest = engine.getPage( pageName,
WikiProvider.LATEST_VERSION );
r1 = latest.getVersion();
}
else if( VER_PREVIOUS.equals(getVersion()) )
{
r1 = m_wikiContext.getPage().getVersion() - 1;
r1 = (r1 < 1 ) ? 1 : r1;
}
else if( VER_CURRENT.equals(getVersion()) )
{
r1 = m_wikiContext.getPage().getVersion();
}
else
{
r1 = Integer.parseInt( getVersion() );
}
if( VER_LATEST.equals(getNewVersion()) )
{
WikiPage latest = engine.getPage( pageName,
WikiProvider.LATEST_VERSION );
r2 = latest.getVersion();
}
else if( VER_PREVIOUS.equals(getNewVersion()) )
{
r2 = m_wikiContext.getPage().getVersion() - 1;
r2 = (r2 < 1 ) ? 1 : r2;
}
else if( VER_CURRENT.equals(getNewVersion()) )
{
r2 = m_wikiContext.getPage().getVersion();
}
else
{
r2 = Integer.parseInt( getNewVersion() );
}
switch( m_format )
{
case ANCHOR:
out.print("<a href=\""+engine.getBaseURL()+"Diff.jsp?page="+encodedlink+"&r1="+r1+"&r2="+r2+"\">");
break;
case URL:
out.print( engine.getBaseURL()+"Diff.jsp?page="+encodedlink+"&r1="+r1+"&r2="+r2 );
break;
}
return EVAL_BODY_INCLUDE;
}
}
|
package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
public class GetPciDeviceCandidatesForAttachingVmAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public GetPciDeviceCandidatesForAttachingVmResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String vmInstanceUuid;
@Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.util.List types;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = true)
public String sessionId;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
GetPciDeviceCandidatesForAttachingVmResult value = res.getResult(GetPciDeviceCandidatesForAttachingVmResult.class);
ret.value = value == null ? new GetPciDeviceCandidatesForAttachingVmResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
Map<String, Parameter> getParameterMap() {
return parameterMap;
}
RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "GET";
info.path = "/vm-instances/{vmInstanceUuid}/candidate-pci-devices";
info.needSession = true;
info.needPoll = false;
info.parameterName = "";
return info;
}
}
|
package com.github.bleuzen.blizcord;
public class Values {
static final boolean DEV = false;
public static final String BOT_VERSION = "0.10.2" + (DEV ? "-dev" : "");
public static final String BOT_NAME = "Blizcord";
public static final String BOT_DEVELOPER = "Bleuzen <supgesu@gmail.com>";
public static final String BOT_GITHUB_REPO = "Bleuzen/Blizcord";
public static final String DISCORD_GET_TOKEN = "https://discordapp.com/developers/applications/me";
public static final String SEARCH_PREFIX_YOUTUBE = "ytsearch:";
public static final int MAX_MESSAGE_LENGHT = 2000; // Discord's message length limit is 2000
public static final int EXIT_CODE_RESTART_GUI = 2;
public static final String OS_LINUX = "linux";
public static final String OS_WINDOWS = "windows";
public static final String UNKNOWN_OS = "unknown";
public static final String CONFIG_FILE_EXTENSION = "json";
public static final String DEFAULT_CONFIG_FILENAME = "config." + CONFIG_FILE_EXTENSION;
public static final String CONFIG_COMMENT = "
public static final int SET_VOLUME_SUCCESSFULLY = 0;
public static final int SET_VOLUME_ERROR_CUSTOM_VOLUME_NOT_ALLOWED = 1;
public static final int SET_VOLUME_ERROR_INVALID_NUMBER = 2;
public static final int MAX_VOLUME = 200;
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.presenters;
import android.os.AsyncTask;
import com.kyloth.serleena.common.EmergencyContact;
import com.kyloth.serleena.common.GeoPoint;
import com.kyloth.serleena.common.ImmutableList;
import com.kyloth.serleena.common.ListAdapter;
import com.kyloth.serleena.model.ISerleenaDataSource;
import com.kyloth.serleena.presentation.IContactsPresenter;
import com.kyloth.serleena.presentation.IContactsView;
import com.kyloth.serleena.presentation.ISerleenaActivity;
import com.kyloth.serleena.sensors.ILocationManager;
import com.kyloth.serleena.sensors.ILocationObserver;
import java.util.ArrayList;
/**
* Concretizza IContactsPresenter
*
* @author Filippo Sestini <sestini.filippo@gmail.com>
* @version 1.0.0
*/
public class ContactsPresenter implements IContactsPresenter,
ILocationObserver {
private static int UPDATE_INTERVAL_SECONDS = 180;
private IContactsView view;
private ISerleenaActivity activity;
private ILocationManager locMan;
private ImmutableList<EmergencyContact> contacts;
int index;
public ContactsPresenter(IContactsView view, ISerleenaActivity activity) {
if (view == null)
throw new IllegalArgumentException("Illegal null view");
if (activity == null)
throw new IllegalArgumentException("Illegal null activity");
this.view = view;
this.activity = activity;
locMan = activity.getSensorManager().getLocationSource();
view.attachPresenter(this);
resetView();
}
/**
* Implementa IContactsPresenter.nextContact().
*
* Se non vi sono contatti da visualizzare, il metodo non ha effetto.
*/
@Override
public void nextContact() {
if (contacts != null && contacts.size() > 0) {
index = (index + 1) % contacts.size();
EmergencyContact c = contacts.get(index);
view.displayContact(c.name(), c.value());
}
}
/**
* Implementa IPresenter.resume().
*
* Si registra al sensore di posizione.
*/
@Override
public void resume() {
locMan.attachObserver(this, UPDATE_INTERVAL_SECONDS);
}
/**
* Implementa IPresenter.pause().
*
* Rilascia le risorse non necessarie annullando la registrazione al sensore
* di posizione.
*/
@Override
public void pause() {
locMan.detachObserver(this);
}
}
|
package com.hp.hpl.jena.n3.test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.hp.hpl.jena.n3.RelURI;
import com.hp.hpl.jena.n3.RelURI.JenaURIException;
import com.hp.hpl.jena.n3.RelURI.RelativeURIException;
/** com.hp.hpl.jena.query.util.test.TestCaseURI
*
* @author Andy Seaborne
* @version $Id: TestRelURI.java,v 1.2 2007-03-21 16:52:51 andy_seaborne Exp $
*/
public class TestRelURI extends TestCase
{
public static TestSuite suite()
{
TestSuite ts = new TestSuite(TestRelURI.class) ;
ts.setName("TestURI") ;
return ts ;
}
public void testCodec01()
{ execCodecTest("") ; }
public void testCodec02()
{ execCodecTest("a") ; }
public void testCodec03()
{ execCodecTest("a_") ; }
public void testCodec04()
{ execCodecTest("_a") ; }
public void testCodec05()
{ execCodecTest(" ") ; }
public void testCodec06()
{ execCodecTest("a b") ; }
public void testCodec07()
{ execCodecTest("a ") ; }
public void testCodec08()
{ execCodecTest(" a") ; }
public void testCodec09()
{ execCodecTest("__") ; }
public void testCodec10()
{ execCodecTest("_20") ; }
public void testCodec11()
{ execCodecTest("ab_20xy") ; }
public void testCodec12()
{ execCodecTest("ab_5F20xy") ; }
public void testCodec13()
{ execCodecTest("ab_5Fxy") ; }
public void testURI_1() { execTest("", "http:
public void testURI_2() { execTest("", "http:
public void testURI_3() { execTest("", "http:
public void testURI_4() { execTest("", "http:
public void testURI_5() { execTest("", "http:
public void testURI_relX_1() { execTest("x", "http:
public void testURI_relX_2() { execTest("x", "http:
public void testURI2_relHashX_1() { execTest("
public void testURI2_relHashX_2() { execTest("
public void testURI_blank_1() { execTest("", "http:
public void testURI_blank_2() { execTest("", "http:
public void testURI_hash_1() { execTest("
public void testURI_hash_2() { execTest("
public void testBaseHash_1() { execTest("x", "http://example.org/ns
public void testBaseHash_2() { execTest("x", "http://example.org
public void testBaseHash_3() { execException("#", "base:x", RelativeURIException.class) ; }
// // Java5: exception
// // Java6 & GNUclasspath: correctly get "base:
// public void testBaseHash_4() { execTest("#", "base:", "base:#") ; }
public void testScheme_1() { execTest("x", "base:", "base:x") ; }
public void testScheme_2() { execTest("/x", "base:", "base:/x") ; }
public void testScheme_3() { execTestMatch("x", "file:", "^file:
public void testScheme_4() { execTestMatch("file:x", null, "^file:
public void testURI_file_1() { execTestMatch("file:x", "http://example.org/ns", "^file:///.*/x$") ; }
public void testURI_file_2() { execTest("x", "file:///A/B/C", "file:///A/B/x") ; }
public void testURI_file_3() { execTest("x", "file:///A/B/", "file:///A/B/x") ; }
public void testURI_abs_1() { execTest("http:
public void testURI_abs_2() { execTest("file:
public void testURI_abs_3() { execTest("tag:foo", "http://example.org/ns", "tag:foo") ; }
public void testURI_abs_4() { execTest("tag:/foo", "http://example.org/ns", "tag:/foo") ; }
public void testURI_abs_5() { execTest("tag:/foo/", "http://example.org/ns", "tag:/foo/") ; }
public void testURI_abs_6() { execTest("scheme99:/foo/", "http://example.org/ns", "scheme99:/foo/") ; }
// Null base
public void testURI_nullBase_1() { execTest("scheme99:/foo/", null, "scheme99:/foo/") ; }
public void testURI_nullBase_2() { execException("foo", null, JenaURIException.class) ; }
public void testHierURI_1() { execTest("../foo", "file:///dir/file", "file:///foo") ; }
public void testHierURI_2() { execTest("../foo", "http:
public void testHierURI_3() { execTest("../foo", "http:
public void testHierURI_4() { execTest("../foo", "http:
public void testHierURI_5() { execTest("../foo", "http:
public void testHierURI_6() { execTest(".", "http:
public void testHierURI_7() { execTest(".", "http:
public void testHierURI_8() { execTest(".", "http:
public void testHierURI_9() { execTest(".", "file:///dir/file", "file:///dir/") ; }
public void testFileURI_1() { execFileTest("file:///foo", "file:///foo") ; }
public void testFileURI_2() { execFileTest("file://foo", "file://foo") ; }
public void testFileURI_3() { execFileTest("file:/foo", "file:///foo") ; }
public void testBaseEmpty() { execException("x", "", JenaURIException.class) ; }
public void testBaseNull() { execException("x", null, JenaURIException.class) ; }
public void testRelBase_1() { execException("x", "ns", RelativeURIException.class) ; }
public void testRelBase_2() { execException("x", "/ns", RelativeURIException.class) ; }
public void testURI_opaque_1() { execException("#x", "tag:A", RelativeURIException.class) ; }
public void testURI_opaque_2() { execException("#x", "urn:x-jena:A", RelativeURIException.class) ; }
public void testURI_opaque_3() { execException("#x", "urn:x-jena:A", RelativeURIException.class) ; }
// Should these be errors? Yes.
//public void testURI_file_4() { execTest("x", "file:A", "file:Ax") ; }
public void testURI_file_4() { execException("x", "file:A", RelativeURIException.class) ; }
public void testURI_file_5() { execTest("#x", "file:A", "file:A#x") ; }
//public void testURI_file_5() { execException("#x", "file:A", RelativeURIException.class) ; }
//public void testURI_file_6() { execTest("foo", "file:///xyz abc/", "file:///xyz abc/foo" ) ; }
public void testURI_file_7() { execTestMatch("file:foo", "file:xyz", "^file:///.*foo$") ; }
public void testURI_file_8() { execTestMatch("file:foo", "file:a b", "^file:///.*foo$") ; }
// File URLs - test aren't exact as the depend where they are run.
public void testFileURI_rel_1() { execTestFileRelURI("file:foo") ; }
public void testFileURI_rel_2() { execTestFileRelURI("file:foo/bar") ; }
public void testFileURI_rel_3() { execTestFileRelURI("file:foo/") ; }
public void testFileURI_rel_4() { execTestFileRelURI("file:foo/bar/") ; }
public void testURI_global_null_1()
{
String tmp = RelURI.getBaseURI() ;
try {
RelURI.setBaseURI("rel") ;
execTestGlobal("x", "rel1/rel2") ;
fail("Didn't get RelativeURIException") ;
} catch (JenaURIException ex) {}
RelURI.setBaseURI(tmp) ;
}
public void testURI_global_null_2()
{
String tmp = RelURI.getBaseURI() ;
RelURI.setBaseURI("file:
execTestGlobal("x", "file:///A/B/x") ;
RelURI.setBaseURI(tmp) ;
}
private void execCodecTest(String s)
{
String a = RelURI.CodecHex.encode(s) ;
String b = RelURI.CodecHex.decode(a) ;
assertEquals("Input: ("+s+") Encoded: ("+a+") Decoded: ("+b+")", s, b) ;
}
private void execTest(String u, String base, String result)
{
String res = RelURI.resolve(u, base) ;
if (result == null )
{
assertNull("("+u+","+base+") => <null> :: Got: "+res, res) ;
return ;
}
assertNotNull("("+u+","+base+") => "+result+" :: Got: <null>", res) ;
assertTrue("("+u+","+base+") => "+result+" :: Got: "+res, res.equals(result)) ;
}
// A test for resolved names that depend on where the tests are run.
private void execTestMatch(String u, String base, String resultPattern)
{
String res = RelURI.resolve(u, base) ;
if (resultPattern == null )
{
assertNull("("+u+","+base+") => <null> :: Got: "+res, res) ;
return ;
}
boolean r = res.matches(resultPattern) ;
assertTrue("Does not match: "+res+" -- "+resultPattern, r) ;
}
private void execFileTest(String fn1, String fn2)
{
String s = RelURI.resolveFileURL(fn1) ;
assertEquals(s,fn2) ;
}
private void execTestFileRelURI(String fn)
{
String relName = fn.substring("file:".length()) ;
String s = RelURI.resolveFileURL(fn) ;
assertTrue("Lost relative name: ("+fn+"=>"+s+")", s.endsWith(relName) ) ;
assertTrue("Not absolute: ("+fn+"=>"+s+")", s.startsWith("file:
}
private void execException(String u, String base, Class ex)
{
// 1.5.0-ism
//String s = ex.getSimpleName() ;
String s = ex.getName() ;
// Tidy it up.
int i = s.lastIndexOf('.') ;
if ( i >= 0 )
s = s.substring(i+1) ;
try {
String res = RelURI.resolve(u, base) ;
if ( res == null )
fail("("+u+","+base+") => <null> :: Expected exception: " +s) ;
else
fail("("+u+","+base+") => "+res+" :: Expected exception: " +s) ;
} catch (Exception ex2)
{
// Shoudl test whether ex2 is a subclass of ex
assertEquals(ex, ex2.getClass()) ;
}
}
private void execTestGlobal(String u, String result)
{
String res = RelURI.resolve(u) ;
if (result == null )
{
assertNull("("+u+") => <null> :: Got: "+res, res) ;
return ;
}
assertNotNull("("+u+") => "+result+" :: Got: <null>", res) ;
assertTrue("("+u+") => "+result+" :: Got: "+res, res.equals(result)) ;
}
}
|
package com.redpois0n.gscrot.ui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class ImagePanel extends JPanel {
public static final Color COLOR_GRAY = new Color(211, 211, 211);
private BufferedImage image;
public ImagePanel() {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if ((x + y) % 2 == 1) {
g.setColor(COLOR_GRAY);
} else {
g.setColor(Color.white);
}
g.fillRect(x * 10, y * 10, 10, 10);
}
}
if (image != null) {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
while (imageWidth > getWidth()) {
imageWidth /= 2;
imageHeight /= 2;
}
while (imageHeight > getHeight()) {
imageWidth /= 2;
imageHeight /= 2;
}
g.drawImage(image, width / 2 - imageWidth / 2, height / 2 - imageHeight / 2, imageWidth, imageHeight, null);
}
}
public void setImage(BufferedImage image) {
this.image = image;
repaint();
}
}
|
package com.tlamatini.test;
// hahahah
import static org.junit.Assert.*;
import java.sql.Date;
import java.util.ArrayList;
import org.junit.Test;
import com.tlamatini.datos.ConexionDB;
import com.tlamatini.modelo.Producto;
import com.tlamatini.persistencia.DAOProducto;
public class DAOProductoTest {
int idProducto = 12;
String nombre = "PruebaJUnit";
String descripcion = "agregaProducto y buscaProducto";
Date fechaCaducidad = new Date(2020/02/02); // 01:02:03;
Date fechaCaducidad2 = new Date(2012/02/02);
double costoUnitario = 1.1;
int cantidad = 40;
String nombreProveedor = "emp";
int topeMayoreo = 40;
int mes = 1;
ConexionDB conexion = new ConexionDB();
DAOProducto daoProducto = new DAOProducto(conexion);
Producto producto = new Producto(idProducto, cantidad);
Producto producto1 = new Producto(12, cantidad);
Producto[] productos = daoProducto.buscaProducto("PruebaJUnit");
Producto[] producto2 = daoProducto.buscaProductosPorFecha(fechaCaducidad);
Producto[] producto3 = daoProducto.buscaProducto(nombre);
Producto[] producto4 = daoProducto.masVendido(mes);
ArrayList<Producto> listaProducto = new ArrayList<Producto>();
ArrayList<Producto> listaProductos = daoProducto.sumaProducto(listaProducto);
@Test
public final void testAgregaProducto() {
assertTrue(daoProducto.agregaProducto(producto));
}
@Test
public final void testBuscaProductoInt() {
assertEquals(productos.length, daoProducto.buscaProducto(producto.getNombre()).length);
}
@Test
public final void testBuscaTodos() {
assertEquals(productos.length, daoProducto.buscaProducto(producto.getNombre()).length);
}
@Test
public final void testBuscaProductosPorFecha() {
assertEquals(producto2.length, daoProducto.buscaProductosPorFecha(fechaCaducidad).length);
}
@Test
public final void testBuscaProductoString() {
assertEquals(producto3.length, daoProducto.buscaProducto(nombre).length);
}
/*
@Test
public final void testBorraProducto() {
assertTrue(daoProducto.borraProducto(producto));
}
*/
@Test
public final void testMasVendido() {
assertEquals(producto4.length, daoProducto.masVendido(mes).length);
}
@Test
public final void testModificaProducto() {
assertTrue(daoProducto.modificaProducto(producto));
}
@Test
public final void testSumaProducto() {
fail("Not yet implemented"); // TODO
}
@Test
public final void testOrdenaProducto() {
fail("Not yet implemented"); // TODO
}
}
|
package com.tomoto.glass.njslyr;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.util.Log;
// Workaround for TTS callbacks (seemingly) not implemented
public class TTSWatcher {
private Handler handler;
private TextToSpeech tts;
private Listener listener;
private Timer timer;
private TTSWatcherTimerTask timerTask;
private boolean speaking;
public static interface Listener {
void onStart();
void onStop(boolean force);
}
private class TTSWatcherTimerTask extends TimerTask {
// 0: idle
// 1: waiting for start
// 2: waiting for finish
private int state = 0;
private long startedTime;
private long timeout;
public void disable() {
state = 0;
}
public void start(long timeout) {
state = 1;
this.timeout = timeout;
this.startedTime = System.currentTimeMillis();
}
@Override
public void run() {
switch (state) {
case 0:
break;
case 1:
Log.d("Gouranga", "Waiting for speech to start");
if (tts.isSpeaking()) {
state = 2;
} else if (timeout > 0 && System.currentTimeMillis() - startedTime > timeout) {
endSpeech();
}
break;
case 2:
Log.d("Gouranga", "Waiting for speech to finish");
if (!tts.isSpeaking()) {
endSpeech();
}
break;
}
}
private void endSpeech() {
handler.post(new Runnable() {
@Override
public void run() {
stopWatching(false);
}
});
state = 0;
}
};
public TTSWatcher(TextToSpeech tts, Listener listener) {
this.handler = new Handler();
this.tts = tts;
this.listener = listener;
this.timer = new Timer("TTSWatcher", true);
this.timerTask = new TTSWatcherTimerTask();
this.timer.schedule(timerTask, 1000, 1000);
this.speaking = false;
}
public void shutdown() {
timer.cancel();
tts.shutdown();
}
public void speak(String text, int queueMode, HashMap<String, String> params) {
if (Pattern.compile("[aiueoAIUEO0-9]").matcher(text).find()) {
// readable
tts.speak(text, queueMode, params);
startWatching(0);
} else {
startWatching(1000);
}
}
public void stop() {
tts.stop();
stopWatching(true);
}
private synchronized void startWatching(long timeout) {
if (speaking) {
stopWatching(true);
}
timerTask.start(timeout);
// timer.schedule(timerTask, 1000, 1000);
speaking = true;
listener.onStart();
}
private synchronized void stopWatching(boolean force) {
if (speaking) {
timerTask.disable();
speaking = false;
listener.onStop(force);
}
}
}
|
package com.xruby.runtime.builtin;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import com.xruby.runtime.lang.*;
import com.xruby.runtime.lang.annotation.RubyAllocMethod;
import com.xruby.runtime.lang.annotation.RubyLevelClass;
import com.xruby.runtime.lang.annotation.RubyLevelMethod;
@RubyLevelClass(name="Time")
public class RubyTime extends RubyBasic {
private final Calendar date_;
private RubyTime(Calendar date){
super(RubyRuntime.TimeClass);
date_ = date;
}
RubyTime(long time){
super(RubyRuntime.TimeClass);
date_ = Calendar.getInstance();
date_.setTimeInMillis(time);
}
RubyTime() {
super(RubyRuntime.TimeClass);
date_ = Calendar.getInstance();
}
@RubyAllocMethod
public static RubyTime alloc(RubyValue receiver) {
return ObjectFactory.createTime();
}
public final long getTime() {
return date_.getTimeInMillis();
}
private final int getUsec() {
long t = getTime();
if (t > 0 && t < 1000) {
return (int) (t * 1000);
}
float t1 = ((float)t / 1000);
float t2 = (long)t1;
return (int)((t1 - t2) * 1000000);
}
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy");
return sdf.format(date_.getTime());
}
@RubyLevelMethod(name="year")
public RubyValue year() {
return ObjectFactory.createFixnum(date_.get(Calendar.YEAR));
}
@RubyLevelMethod(name="month")
public RubyValue month() {
return ObjectFactory.createFixnum(date_.get(Calendar.MONTH));
}
@RubyLevelMethod(name="day")
public RubyValue day() {
return ObjectFactory.createFixnum(date_.get(Calendar.DATE));
}
@RubyLevelMethod(name="to_f")
public RubyFloat to_f() {
return ObjectFactory.createFloat((double)getTime() / 1000);
}
@RubyLevelMethod(name="to_i", alias="tv_sec")
public RubyFixnum to_i() {
return ObjectFactory.createFixnum((int) (getTime() / 1000));
}
@RubyLevelMethod(name="usec", alias="tv_usec")
public RubyFixnum usec() {
return ObjectFactory.createFixnum(this.getUsec());
}
@RubyLevelMethod(name="to_s")
public RubyString to_s() {
return ObjectFactory.createString(this.toString());
}
@RubyLevelMethod(name="+")
public RubyTime plus(RubyValue value) {
double timeAdd = value.toFloat();
return ObjectFactory.createTime(getTime() + (long)(timeAdd * 1000));
}
@RubyLevelMethod(name="-")
public RubyValue minus(RubyValue value) {
if (value instanceof RubyTime) {
RubyTime time2 = (RubyTime)value;
long timeInteval = getTime() - time2.getTime();
if (timeInteval % 1000 == 0) {
return ObjectFactory.createFixnum((int) (timeInteval / 1000));
}
return ObjectFactory.createFloat((double) timeInteval / 1000);
}
double time = value.toFloat();
return ObjectFactory.createTime((getTime() - (long)(time * 1000)));
}
@RubyLevelMethod(name="<=>")
public RubyFixnum cmp(RubyValue value) {
long time1 = getTime();
long time2 = RubyTypesUtil.convertToTime(value).getTime();
if (time1 < time2) {
return ObjectFactory.FIXNUM_NEGATIVE_ONE;
} else if (time1 > time2) {
return ObjectFactory.FIXNUM1;
}
return ObjectFactory.FIXNUM0;
}
@RubyLevelMethod(name="zone")
public RubyString zone() {
String name = date_.getTimeZone().getDisplayName();
if (name.equals("Greenwich Mean Time")) {
name = "UTC";
}
return ObjectFactory.createString(name);
}
@RubyLevelMethod(name="utc", alias="gm")
public static RubyTime utc(RubyValue receiver, RubyArray args) {
return createTime(args, TimeZone.getTimeZone("GMT"));
}
@RubyLevelMethod(name="gmt?")
public RubyValue gmt_question() {
return ObjectFactory.createBoolean(date_.getTimeZone().hasSameRules(TimeZone.getTimeZone("GMT")));
}
@RubyLevelMethod(name="localtime")
public RubyValue localtime() {
date_.setTimeZone(TimeZone.getDefault());
return this;
}
@RubyLevelMethod(name="mktime", alias="local")
public static RubyTime local(RubyValue receiver, RubyArray args) {
return createTime(args, TimeZone.getDefault());
}
private static RubyTime createTime(RubyArray args, TimeZone zone) {
if (null == args || args.size() == 0) {
throw new RubyException(RubyRuntime.ArgumentErrorClass, "wrong number of arguments (0 for 1)");
}
int i = 0;
int year = ((RubyFixnum) args.get(i++)).toInt();
int month = (args.size() <= i) ? 0 : ((RubyFixnum) args.get(i++)).toInt();
int day = (args.size() <= i) ? 0 : ((RubyFixnum) args.get(i++)).toInt();
int hour = (args.size() <= i) ? 0 : ((RubyFixnum) args.get(i++)).toInt();
int min = (args.size() <= i) ? 0 : ((RubyFixnum) args.get(i++)).toInt();
int sec = (args.size() <= i) ? 0 : ((RubyFixnum) args.get(i++)).toInt();
Calendar calendar = Calendar.getInstance(zone);
calendar.set(year, month, day, hour, min, sec);
return new RubyTime(calendar);
}
@RubyLevelMethod(name="at")
public static RubyTime at(RubyValue receiver, RubyValue value) {
double time = 0;
if (value instanceof RubyFixnum) {
time = value.toInt();
} else if (value instanceof RubyBignum) {
time = value.toFloat();
} else if (value instanceof RubyFloat) {
time = value.toFloat();
} else {
throw new RubyException(RubyRuntime.TypeErrorClass, "can't convert " + value.getRubyClass().getName() + " into Time");
}
return ObjectFactory.createTime((long) (time*1000));
}
@RubyLevelMethod(name="now")
public static RubyValue now(RubyValue receiver, RubyArray args, RubyBlock block) {
RubyClass r = (RubyClass) receiver;
return r.newInstance(args, block);
}
}
|
package br.com.pucrs;
import br.com.pucrs.collections.GeneralTree;
import br.com.pucrs.io.BookPrinter;
import br.com.pucrs.io.BookReader;
import java.io.IOException;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Número de argumentos inválido.");
System.out.println("Sintaxe: trabalho-3-algoritmos-e-estruturas-de-dados.jar [arquivo_entrada] [arquivo_saida]");
return;
}
BookReader reader = new BookReader();
BookPrinter printer = new BookPrinter();
GeneralTree<String> tree = new GeneralTree<>();
try {
tree = reader.readFile(Paths.get(args[0]));
System.out.printf("Carregando arquivo %s ... ok\n", args[0]);
System.out.println("Gerando a árvore... ok");
System.out.println(" Capitulos...: " + reader.getNroCapitulos());
System.out.println(" Seções......: " + reader.getNroSecoes());
System.out.println(" Subseções...: " + reader.getNroSubSecoes());
System.out.println(" Parágrafos..: " + reader.getNroParagrafos());
reader.clear();
} catch (IOException e) {
System.out.println("Erro na leitura do arquivo " + args[0]);
}
try {
printer.print(tree, Paths.get(args[1]));
System.out.println("Gerando o sumário... ok");
System.out.printf("Imprimindo o livro para o arquivo %s... ok.\n", args[1]);
} catch (IOException e) {
System.out.println("Erro na escrita do arquivo " + args[1]);
}
}
}
|
package io.spine.server.projection;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.Message;
import io.spine.core.Event;
import io.spine.core.Subscribe;
import io.spine.core.Version;
import io.spine.core.Versions;
import io.spine.server.entity.ThrowingValidatingBuilder;
import io.spine.server.entity.Transaction;
import io.spine.server.entity.TransactionListener;
import io.spine.server.entity.TransactionShould;
import io.spine.server.projection.ProjectionTransactionShould.PatchedProjectBuilder;
import io.spine.test.projection.Project;
import io.spine.test.projection.ProjectId;
import io.spine.test.projection.event.PrjProjectCreated;
import io.spine.test.projection.event.PrjTaskAdded;
import io.spine.validate.ConstraintViolation;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static com.google.common.collect.Lists.newLinkedList;
import static io.spine.protobuf.AnyPacker.unpack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Alex Tymchenko
*/
public class ProjectionTransactionShould
extends TransactionShould<ProjectId,
Projection<ProjectId, Project, PatchedProjectBuilder>,
Project,
PatchedProjectBuilder> {
private static final ProjectId ID = ProjectId.newBuilder()
.setId("projection-transaction-should-project")
.build();
@Override
protected Transaction<ProjectId,
Projection<ProjectId, Project, PatchedProjectBuilder>,
Project,
PatchedProjectBuilder>
createTx(Projection<ProjectId, Project, PatchedProjectBuilder> entity) {
return new ProjectionTransaction<>(entity);
}
@Override
protected Transaction<ProjectId,
Projection<ProjectId, Project, PatchedProjectBuilder>,
Project,
PatchedProjectBuilder>
createTxWithState(Projection<ProjectId, Project, PatchedProjectBuilder> entity,
Project state,
Version version) {
return new ProjectionTransaction<>(entity, state, version);
}
@Override
protected Transaction<ProjectId,
Projection<ProjectId, Project, PatchedProjectBuilder>,
Project,
PatchedProjectBuilder>
createTxWithListener(Projection<ProjectId, Project, PatchedProjectBuilder> entity,
TransactionListener<ProjectId,
Projection<ProjectId, Project, PatchedProjectBuilder>,
Project,
PatchedProjectBuilder> listener) {
return new ProjectionTransaction<>(entity, listener);
}
@Override
protected Projection<ProjectId, Project, PatchedProjectBuilder> createEntity() {
return new TestProjection(ID);
}
@Override
protected Projection<ProjectId, Project, PatchedProjectBuilder>
createEntity(List<ConstraintViolation> violations) {
return new TestProjection(ID, violations);
}
@Override
protected Project createNewState() {
return Project.newBuilder()
.setId(ID)
.setName("The new name for the projection state in this tx")
.build();
}
@Override
protected void checkEventReceived(Projection<ProjectId, Project, PatchedProjectBuilder> entity,
Event event) {
TestProjection aggregate = (TestProjection) entity;
Message actualMessage = unpack(event.getMessage());
assertTrue(aggregate.getReceivedEvents()
.contains(actualMessage));
}
@Override
protected Message createEventMessage() {
return PrjProjectCreated.newBuilder()
.setProjectId(ID)
.build();
}
@Override
protected Message createEventMessageThatFailsInHandler() {
return PrjTaskAdded.newBuilder()
.setProjectId(ID)
.build();
}
@Override
protected void breakEntityValidation(
Projection<ProjectId, Project, PatchedProjectBuilder> entity,
RuntimeException toThrow) {
entity.getBuilder()
.setShouldThrow(toThrow);
}
/**
* This test is ignored as the expected behavior has been changed for the projection
* transactions.
*
* <p>{@link #increment_version_on_event() Another test method} is created to test the new
* behavior. Please refer to it for more details.
*/
@Ignore
@Test
@Override
public void advance_version_from_event() {
}
/**
* Tests the version advancement strategy for the {@link Projection}s.
*
* <p>The versioning strategy is for {@link Projection} is
* {@link io.spine.server.entity.EntityVersioning#AUTO_INCREMENT AUTO_INCREMENT}. This test
* case substitutes {@link #advance_version_from_event()}, which tested the behavior of
* {@link io.spine.server.entity.EntityVersioning#FROM_EVENT FROM_EVENT} strategy.
*/
@SuppressWarnings("CheckReturnValue") // can ignore value of play() in this test
@Test
public void increment_version_on_event() {
Projection<ProjectId, Project, PatchedProjectBuilder> entity = createEntity();
Version oldVersion = entity.getVersion();
Event event = createEvent(createEventMessage());
Projection.play(entity, Collections.singleton(event));
Version expected = Versions.increment(oldVersion);
assertEquals(expected.getNumber(), entity.getVersion()
.getNumber());
assertNotEquals(event.getContext()
.getVersion(), entity.getVersion());
}
@SuppressWarnings({"MethodMayBeStatic", "unused"}) // Methods accessed via reflection.
static class TestProjection
extends Projection<ProjectId, Project, PatchedProjectBuilder> {
private final List<Message> receivedEvents = newLinkedList();
private final List<ConstraintViolation> violations;
private TestProjection(ProjectId id) {
this(id, null);
}
private TestProjection(ProjectId id, @Nullable List<ConstraintViolation> violations) {
super(id);
this.violations = violations;
}
@Override
protected List<ConstraintViolation> checkEntityState(Project newState) {
if (violations != null) {
return ImmutableList.copyOf(violations);
}
return super.checkEntityState(newState);
}
@Subscribe
public void event(PrjProjectCreated event) {
receivedEvents.add(event);
final Project newState = Project.newBuilder(getState())
.setId(event.getProjectId())
.build();
getBuilder().mergeFrom(newState);
}
@Subscribe
public void event(PrjTaskAdded event) {
throw new RuntimeException("that tests the projection tx behaviour");
}
private List<Message> getReceivedEvents() {
return ImmutableList.copyOf(receivedEvents);
}
}
/**
* Custom implementation of {@code ValidatingBuilder}, which allows to simulate an error
* during the state building.
*
* <p>Must be declared {@code public} to allow accessing from the
* {@linkplain io.spine.validate.ValidatingBuilders#newInstance(Class) factory method}.
*/
public static class PatchedProjectBuilder
extends ThrowingValidatingBuilder<Project, Project.Builder> {
public static PatchedProjectBuilder newBuilder() {
return new PatchedProjectBuilder();
}
}
}
|
package org.usergrid.security.providers;
import com.sun.jersey.api.client.WebResource;
import org.codehaus.jackson.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usergrid.management.ManagementService;
import org.usergrid.persistence.EntityManager;
import org.usergrid.persistence.Identifier;
import org.usergrid.persistence.entities.User;
import org.usergrid.security.tokens.exceptions.BadTokenException;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
/**
* Provider implementation for accessing Ping Identity
*
* @author zznate
*/
public class PingIdentityProvider extends AbstractProvider {
private Logger logger = LoggerFactory.getLogger(PingIdentityProvider.class);
private String apiUrl;
private String clientId;
private String clientSecret;
PingIdentityProvider(EntityManager entityManager, ManagementService managementService) {
super(entityManager, managementService);
}
@Override
public User createOrAuthenticate(String externalToken) throws BadTokenException {
Map<String, Object> pingUser = userFromResource(externalToken);
User user = null;
try {
user = managementService.getAppUserByIdentifier(entityManager.getApplication().getUuid(),
Identifier.fromEmail(pingUser.get("username").toString()));
} catch (Exception ex) {
ex.printStackTrace();
// TODO what to do here?
}
if ( user == null ) {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
properties.putAll(pingUser);
properties.put("activated", true);
try {
user = entityManager.create("user", User.class, properties);
} catch (Exception ex) {
throw new BadTokenException("Could not create user for that token", ex);
}
} else {
user.setProperty("expiration",pingUser.get("expiration"));
try {
entityManager.update(user);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return user;
}
@Override
void configure() {
try {
Map config = loadConfigurationFor();
if ( config != null ) {
apiUrl = (String)config.get("api_url");
clientId = (String)config.get("client_id");
clientSecret = (String)config.get("client_secret");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public Map<Object, Object> loadConfigurationFor() {
return loadConfigurationFor("pingIdentProvider");
}
@Override
public void saveToConfiguration(Map<String, Object> config) {
saveToConfiguration("pingIdentProvider", config);
}
@Override
Map<String, Object> userFromResource(String externalToken) {
JsonNode node = client.resource(apiUrl).queryParam("grant_type", "urn:pingidentity.com:oauth2:grant_type:validate_bearer")
.queryParam("client_secret",clientSecret)
.queryParam("client_id",clientId)
.queryParam("token",externalToken).type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(JsonNode.class);
// {"token_type":"urn:pingidentity.com:oauth2:validated_token","expires_in":5383,
// "client_id":"dev.app.appservices","access_token":{"subject":"svccastiron@burberry.com","client_id":"dev.app.appservices"}}
String rawEmail = node.get("access_token").get("subject").getTextValue();
Map<String,Object> userMap = new HashMap<String, Object>();
userMap.put("expiration", node.get("expires_in").getLongValue());
userMap.put("username", pingUsernameFrom(rawEmail));
userMap.put("email", rawEmail);
return userMap;
}
public static String pingUsernameFrom(String rawEmail) {
return String.format("pinguser_%s",rawEmail);
}
public static long extractExpiration(User user) {
Long expiration = (Long)user.getProperty("expiration");
if ( expiration == null ) {
return 7200;
}
return expiration.longValue();
}
}
|
package com.redshape.servlet.core.context.support;
import com.redshape.renderer.IRenderersFactory;
import com.redshape.servlet.core.IHttpRequest;
import com.redshape.servlet.core.IHttpResponse;
import com.redshape.servlet.core.SupportType;
import com.redshape.servlet.core.context.AbstractResponseContext;
import com.redshape.servlet.core.context.ContextId;
import com.redshape.servlet.core.controllers.ProcessingException;
import com.redshape.servlet.views.IView;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* @author nikelin
* @date 14:01
*/
public class AjaxContext extends AbstractResponseContext {
private static final Logger log = Logger.getLogger( AjaxContext.class );
private static final String MARKER_HEADER = "XMLHttpRequest";
private static final String DISABLE_PARAM = "Disable";
private Collection<String> blackList = new HashSet<String>();
private IRenderersFactory renderersFactory;
public AjaxContext() {
this(null);
}
public AjaxContext( IRenderersFactory renderersFactory ) {
super( ContextId.AJAX );
this.renderersFactory = renderersFactory;
}
public IRenderersFactory getRenderersFactory() {
return renderersFactory;
}
public Collection<String> getBlackList() {
return blackList;
}
public void setBlackList(Collection<String> blackList) {
this.blackList = blackList;
}
@Override
public boolean doExceptionsHandling() {
return true;
}
@Override
public boolean doRedirectionHandling() {
return false;
}
@Override
public SupportType isSupported(IView request) {
return SupportType.NO;
}
@Override
public SupportType isSupported(IHttpRequest request) {
String headerValue = request.getHeader("X-Requested-With");
if ( headerValue != null && headerValue.equals(AjaxContext.MARKER_HEADER) ) {
if ( !request.getParameter("_servletContextParam").equals(AjaxContext.DISABLE_PARAM) ) {
return SupportType.SHOULD;
} else {
return SupportType.NO;
}
} else {
return SupportType.NO;
}
}
protected Map<String, Object> prepareResult( Map<String, Object> params ) {
Map<String, Object> result = new HashMap<String, Object>();
for ( String key : params.keySet() ) {
if ( this.getBlackList().contains(key) ) {
continue;
}
result.put( key, params.get(key) );
}
return result;
}
@Override
public void proceedResponse(IView view, IHttpRequest request, IHttpResponse response) throws ProcessingException {
try {
JsonConfig config = new JsonConfig();
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
String responseContent = "";
if ( this.getRenderersFactory() == null ) {
JSONObject result = new JSONObject();
result.put("response", JSONObject.fromObject(view, config) );
responseContent = result.toString();
} else {
responseContent = this.getRenderersFactory().
<IView, String>forEntity(view)
.render(view);
}
log.info("Response: " + responseContent);
this.writeResponse( responseContent, response);
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
private void writeResponse(String responseData, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(responseData);
response.getWriter().flush();
response.getWriter().close();
}
}
|
package org.slc.sli.api.security.saml2;
import java.io.InputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import javax.xml.crypto.MarshalException;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerException;
import junit.framework.Assert;
import org.jdom.JDOMException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.slc.sli.api.test.WebContextTestExecutionListener;
/**
* Unit tests for the XML Signature Helper class.
*
* @author shalka
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext-test.xml" })
@TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class XmlSignatureHelperTest {
@Autowired
private DefaultSAML2Validator validator;
@Autowired
private XmlSignatureHelper signatureHelper;
private DocumentBuilder builder;
@Before
public void setUp() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
builder = dbf.newDocumentBuilder();
}
private Document getDocument(final String fileName) {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName);
try {
return builder.parse(is);
} catch (Exception e) {
return null;
}
}
@Test
public void checkSamlUntrusted() throws KeyStoreException, InvalidAlgorithmParameterException,
CertificateException, NoSuchAlgorithmException, MarshalException {
Document document = getDocument("adfs-invalid.xml");
Assert.assertTrue(!validator.isDocumentTrusted(document));
}
@Test
public void signSamlArtifactResolve() throws JDOMException, TransformerException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException,
KeyStoreException, CertificateException {
Document unsignedDocument = getDocument("artifact-resolve-unsigned.xml");
Document signedDom = signatureHelper.signSamlAssertion(unsignedDocument);
Assert.assertNotNull(signedDom);
boolean foundSignedInfo = false;
boolean foundSignatureValue = false;
boolean foundKeyInfo = false;
// traverse the saml to find the signature element and its child nodes
NodeList list = signedDom.getChildNodes();
if (list.item(0).getNodeName().equals("samlp:ArtifactResolve")) {
NodeList sublist = list.item(0).getChildNodes();
for (int i = 0; i < sublist.getLength(); i++) {
if (sublist.item(i).getNodeName().equals("Signature")) {
NodeList signatureList = sublist.item(i).getChildNodes();
for (int j = 0; j < signatureList.getLength(); j++) {
if (signatureList.item(j).getNodeName().equals("SignedInfo")) {
foundSignedInfo = true;
} else if (signatureList.item(j).getNodeName().equals("SignatureValue")) {
foundSignatureValue = true;
} else if (signatureList.item(j).getNodeName().equals("KeyInfo")) {
foundKeyInfo = true;
}
}
}
}
}
Assert.assertTrue("Should be true if Signature contains SignedInfo tag", foundSignedInfo);
Assert.assertTrue("Should be true if Signature contains SignatureValue tag", foundSignatureValue);
Assert.assertTrue("Should be true if Signature contains KeyInfo tag", foundKeyInfo);
Assert.assertTrue(validator.isDocumentTrusted(signedDom));
}
}
|
package brooklyn.entity.dns;
import static org.testng.Assert.assertTrue;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.ApplicationBuilder;
import brooklyn.entity.basic.DynamicGroup;
import brooklyn.entity.basic.Entities;
import brooklyn.entity.group.DynamicFabric;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.proxying.ImplementedBy;
import brooklyn.location.Location;
import brooklyn.location.LocationSpec;
import brooklyn.location.basic.SimulatedLocation;
import brooklyn.location.basic.SshMachineLocation;
import brooklyn.location.geo.HostGeoInfo;
import brooklyn.management.ManagementContext;
import brooklyn.management.internal.LocalManagementContext;
import brooklyn.test.entity.TestApplication;
import brooklyn.test.entity.TestEntity;
import brooklyn.util.internal.Repeater;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
public class AbstractGeoDnsServiceTest {
public static final Logger log = LoggerFactory.getLogger(AbstractGeoDnsServiceTest.class);
private static final String WEST_IP = "208.95.232.123";
private static final String EAST_IP = "216.150.144.82";
private static final double WEST_LATITUDE = 37.43472, WEST_LONGITUDE = -121.89500;
private static final double EAST_LATITUDE = 41.10361, EAST_LONGITUDE = -73.79583;
private ManagementContext managementContext;
private Location westParent;
private Location westChild;
private Location westChildWithLocation;
private Location eastParent;
private Location eastChild;
private Location eastChildWithLocation;
private TestApplication app;
private DynamicFabric fabric;
private DynamicGroup testEntities;
private GeoDnsTestService geoDns;
@BeforeMethod(alwaysRun=true)
public void setup() {
managementContext = new LocalManagementContext();
westParent = newSimulatedLocation("West parent", WEST_LATITUDE, WEST_LONGITUDE);
westChild = newSshMachineLocation("West child", WEST_IP, westParent);
westChildWithLocation = newSshMachineLocation("West child with location", WEST_IP, westParent, WEST_LATITUDE, WEST_LONGITUDE);
eastParent = newSimulatedLocation("East parent", EAST_LATITUDE, EAST_LONGITUDE);
eastChild = newSshMachineLocation("East child", EAST_IP, eastParent);
eastChildWithLocation = newSshMachineLocation("East child with location", EAST_IP, eastParent, EAST_LATITUDE, EAST_LONGITUDE);
Entities.manage(westParent, managementContext);
Entities.manage(eastParent, managementContext);
app = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext);
fabric = app.createAndManageChild(EntitySpec.create(DynamicFabric.class)
.configure(DynamicFabric.MEMBER_SPEC, EntitySpec.create(TestEntity.class)));
testEntities = app.createAndManageChild(EntitySpec.create(DynamicGroup.class)
.configure(DynamicGroup.ENTITY_FILTER, Predicates.instanceOf(TestEntity.class)));
geoDns = app.createAndManageChild(EntitySpec.create(GeoDnsTestService.class)
.configure(GeoDnsTestService.POLL_PERIOD, 10L));
geoDns.setTargetEntityProvider(testEntities);
}
@AfterMethod(alwaysRun=true)
public void tearDown() throws Exception {
if (app != null) Entities.destroyAll(app.getManagementContext());
}
private SimulatedLocation newSimulatedLocation(String name, double lat, double lon) {
return managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)
.displayName(name)
.configure("latitude", lat)
.configure("longitude", lon));
}
private Location newSshMachineLocation(String name, String address, Location parent) {
return managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
.parent(parent)
.displayName(name)
.configure("address", address));
}
private Location newSshMachineLocation(String name, String address, Location parent, double lat, double lon) {
return managementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
.parent(parent)
.displayName(name)
.configure("address", address)
.configure("latitude", lat)
.configure("longitude", lon));
}
@Test
public void testGeoInfoOnLocation() {
app.start( ImmutableList.of(westChildWithLocation, eastChildWithLocation) );
waitForTargetHosts(geoDns);
assertTrue(geoDns.getTargetHostsByName().containsKey("West child with location"), "targets="+geoDns.getTargetHostsByName());
assertTrue(geoDns.getTargetHostsByName().containsKey("East child with location"), "targets="+geoDns.getTargetHostsByName());
}
@Test
public void testGeoInfoOnParentLocation() {
app.start( ImmutableList.of(westChild, eastChild) );
waitForTargetHosts(geoDns);
assertTrue(geoDns.getTargetHostsByName().containsKey("West child"), "targets="+geoDns.getTargetHostsByName());
assertTrue(geoDns.getTargetHostsByName().containsKey("East child"), "targets="+geoDns.getTargetHostsByName());
}
//TODO
// @Test
// public void testMissingGeoInfo() {
// @Test
// public void testEmptyGroup() {
private static void waitForTargetHosts(final GeoDnsTestService service) {
new Repeater("Wait for target hosts")
.repeat()
.every(500, TimeUnit.MILLISECONDS)
.until(new Callable<Boolean>() {
public Boolean call() {
return service.getTargetHostsByName().size() == 2;
}})
.limitIterationsTo(20)
.run();
}
@ImplementedBy(GeoDnsTestServiceImpl.class)
public static interface GeoDnsTestService extends AbstractGeoDnsService {
public Map<String, HostGeoInfo> getTargetHostsByName();
}
public static class GeoDnsTestServiceImpl extends AbstractGeoDnsServiceImpl implements GeoDnsTestService {
public Map<String, HostGeoInfo> targetHostsByName = new LinkedHashMap<String, HostGeoInfo>();
public GeoDnsTestServiceImpl() {
}
@Override
public Map<String, HostGeoInfo> getTargetHostsByName() {
synchronized (targetHostsByName) {
return targetHostsByName;
}
}
@Override
protected boolean addTargetHost(Entity e) {
//ignore geo lookup, override parent menu
log.info("TestService adding target host {}", e);
if (e.getLocations().isEmpty()) {
return false;
}
Location l = Iterables.getOnlyElement(e.getLocations());
HostGeoInfo geoInfo = new HostGeoInfo("127.0.0.1", l.getDisplayName(),
(Double) l.findLocationProperty("latitude"), (Double) l.findLocationProperty("longitude"));
targetHosts.put(e, geoInfo);
return true;
}
@Override
protected void reconfigureService(Collection<HostGeoInfo> targetHosts) {
synchronized (targetHostsByName) {
targetHostsByName.clear();
for (HostGeoInfo host : targetHosts) {
if (host != null) targetHostsByName.put(host.displayName, host);
}
}
}
@Override
public String getHostname() {
return "localhost";
}
}
}
|
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app.debug;
import processing.app.Base;
import processing.app.Preferences;
import processing.app.Serial;
import processing.core.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import gnu.io.*;
public class ZPUinoUploader extends Uploader {
public ZPUinoUploader() {
}
// XXX: add support for uploading sketches using a programmer
public boolean uploadUsingPreferences(String buildPath, String className, int uploadOptions)
throws RunnerException {
this.verbose = verbose;
Map<String, String> boardPreferences = Base.getBoardPreferences();
String uploadUsing = boardPreferences.get("upload.using");
if (uploadUsing == null) {
// fall back on global preference
uploadUsing = Preferences.get("upload.using");
}
if (uploadOptions == uploadUsingProgrammer ) {
throw new RunnerException("ZPUino targets do not support upload using programmer");
}
if (uploadUsing.equals("bootloader")) {
return uploadViaBootloader(buildPath, className, uploadOptions==uploadToMemory);
} else {
Target t;
if (uploadUsing.indexOf(':') == -1) {
t = Base.getTarget(); // the current target (associated with the board)
} else {
String targetName = uploadUsing.substring(0, uploadUsing.indexOf(':'));
t = Base.targetsTable.get(targetName);
uploadUsing = uploadUsing.substring(uploadUsing.indexOf(':') + 1);
}
Collection params = getProgrammerCommands(t, uploadUsing);
params.add("-b" + buildPath + File.separator + Base.getFileNameWithoutExtension(new File(className)) + ".bin");
return zpuinoprogrammer(params);
}
}
private boolean uploadViaBootloader(String buildPath, String className, boolean toMemory)
throws RunnerException {
Map<String, String> boardPreferences = Base.getBoardPreferences();
List commandDownloader = new ArrayList();
String extraOptions = boardPreferences.get("upload.extraoptions");
String speed = boardPreferences.get("upload.speed");
if (speed!=null) {
commandDownloader.add("-s");
commandDownloader.add(speed);
}
commandDownloader.add(
"-d" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port"));
commandDownloader.add("-b" + buildPath + File.separator + Base.getFileNameWithoutExtension(new File(className)) + ".bin");
commandDownloader.add("-R"); // Reset
if (toMemory)
commandDownloader.add("-U");
// Append extra data file, if present
File smallfs = new File(buildPath,"smallfs.dat");
if (smallfs.exists()) {
if (toMemory) {
// Just warn user
System.err.println("SmallFS filesystem found, *NOT* programming FLASH because you're doing a memory upload");
} else {
System.out.println("SmallFS filesystem found, appending extra data file to FLASH");
commandDownloader.add("-e");
commandDownloader.add(smallfs.getPath());
}
}
if (extraOptions!=null) {
for (String i: PApplet.split(extraOptions," ")) {
commandDownloader.add(i);
}
}
return zpuinoprogrammer(commandDownloader);
}
public boolean burnBootloader(String targetName, String programmer) throws RunnerException {
return burnBootloader(getProgrammerCommands(Base.targetsTable.get(targetName), programmer));
}
public boolean burnBootloader() throws RunnerException {
throw new RunnerException("Not supported!");
}
private Collection getProgrammerCommands(Target target, String programmer) {
Map<String, String> programmerPreferences = target.getProgrammers().get(programmer);
List params = new ArrayList();
params.add("-c" + programmerPreferences.get("protocol"));
if ("usb".equals(programmerPreferences.get("communication"))) {
params.add("-Pusb");
} else if ("serial".equals(programmerPreferences.get("communication"))) {
params.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port"));
if (programmerPreferences.get("speed") != null) {
params.add("-b" + Integer.parseInt(programmerPreferences.get("speed")));
}
}
// XXX: add support for specifying the port address for parallel
// programmers, although avrdude has a default that works in most cases.
if (programmerPreferences.get("force") != null &&
programmerPreferences.get("force").toLowerCase().equals("true"))
params.add("-F");
if (programmerPreferences.get("delay") != null)
params.add("-i" + programmerPreferences.get("delay"));
return params;
}
protected boolean burnBootloader(Collection params)
throws RunnerException {
return false;
}
public boolean zpuinoprogrammer(Collection p1, Collection p2) throws RunnerException {
ArrayList p = new ArrayList(p1);
p.addAll(p2);
return zpuinoprogrammer(p);
}
public boolean zpuinoprogrammer(Collection params) throws RunnerException {
List commandDownloader = new ArrayList();
if (Base.isLinux()) {
commandDownloader.add("zpuinoprogrammer");
} else {
commandDownloader.add("zpuinoprogrammer.exe");
}
commandDownloader.addAll(params);
return executeUploadCommand(commandDownloader);
}
}
|
package org.demyo.web.interceptors;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.demyo.model.Reader;
import org.demyo.service.IReaderContext;
import org.demyo.service.IReaderService;
/**
* A {@link HandlerInterceptor} that sets the reader in the {@link IReaderContext} if possible.
* <p>
* If not, redirects to the selection URL.
* </p>
*/
public class ReaderInterceptor implements HandlerInterceptor {
private static final int COOKIE_EXPIRATION = 365 * 24 * 60 * 60;
private static final String READER_COOKIE = "demyo_reader_id";
private static final Logger LOGGER = LoggerFactory.getLogger(ReaderInterceptor.class);
@Autowired
private IReaderService service;
@Autowired
private IReaderContext context;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
final String path = request.getServletPath();
LOGGER.debug("Handling {}", path);
boolean hasReader = false;
// Special behaviours to avoid making a loop, and to avoid protecting the API
// Empty is for special weird cases in unit tests
// TODO: figure out if this causes issues once Vue is in production
if (path.matches("^/api/.*$") || path.isEmpty()) {
return true;
}
if (path.matches("^/readers/(\\d+)/select$")) {
Long readerId = parseReaderId(path.replaceAll("^/readers/(\\d+)/select$", "$1"));
LOGGER.debug("Selecting reader {}", readerId);
hasReader = loadReaderIfExists(readerId, request, response);
// The controller will take care of the redirection
}
// Load from cookie if possible
if (!hasReader) {
Cookie cookie = WebUtils.getCookie(request, READER_COOKIE);
String cookieValue = cookie == null ? null : cookie.getValue();
Long readerId = parseReaderId(cookieValue);
// If the reader is selected and exists. Also refreshes the cookie
hasReader = loadReaderIfExists(readerId, request, response);
}
// If the user is selected properly, continue
if (hasReader) {
LOGGER.debug("The current reader is: {}", context.getCurrentReader().getName());
return true;
}
// Clear the current reader already
context.clearCurrentReader();
// Check how many readers are in total
Reader uniqueReader = service.getUniqueReader();
if (uniqueReader != null) {
LOGGER.debug("Loaded the unique available reader");
// We have a unique reader we can use. Set it, and set the cookie
setReader(request, response, uniqueReader);
} else {
// We have multiple readers, the user should select by himself, except if we are already on the right page
if (!path.matches("^/readers(/(index)?)?")) {
// Don't use response.sendRedirect as it will prepend the server name etc.
// This is not ideal in an environment featuring reverse proxies
response.setStatus(HttpStatus.SEE_OTHER.value());
response.setHeader("Location", request.getContextPath() + "/readers/");
}
}
return true;
}
private boolean loadReaderIfExists(Long readerId, HttpServletRequest request, HttpServletResponse response) {
if (readerId != null && service.readerExists(readerId)) {
// He does. Perhaps we already loaded the reader
Reader currentReader = context.getCurrentReader();
if (currentReader != null && currentReader.getId().equals(readerId)) {
// Do nothing
LOGGER.debug("Reader {} is already loaded in the session", readerId);
} else {
loadReader(readerId, request, response);
}
return true;
}
return false;
}
private Long parseReaderId(String tentativeId) {
Long readerId = null;
if (tentativeId != null) {
try {
readerId = Long.parseLong(tentativeId);
} catch (RuntimeException e) {
LOGGER.warn("Invalid reader ID: {}", tentativeId);
}
}
return readerId;
}
/**
* Sets the reader in the context and cookie.
*/
private void setReader(HttpServletRequest request, HttpServletResponse response, Reader reader) {
Cookie cookieToSet = new Cookie(READER_COOKIE, reader.getId().toString());
cookieToSet.setMaxAge(COOKIE_EXPIRATION);
cookieToSet.setPath(request.getContextPath() + "/");
response.addCookie(cookieToSet);
context.setCurrentReader(reader);
}
/**
* Loads the reader and sets it in the context.
*/
private void loadReader(Long readerId, HttpServletRequest request, HttpServletResponse response) {
LOGGER.debug("Loading reader {}", readerId);
Reader reader = service.getByIdForView(readerId);
context.setCurrentReader(reader);
setReader(request, response, reader);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// Nothing to do
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// Nothing to do
}
}
|
package com.jetbrains.python.sdk;
import com.intellij.execution.process.CapturingProcessHandler;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.HashMap;
import com.jetbrains.python.remote.PythonRemoteSdkAdditionalData;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PySdkUtil {
protected static final Logger LOG = Logger.getInstance("#com.jetbrains.python.sdk.SdkVersionUtil");
private PySdkUtil() {
// explicitly none
}
/**
* Executes a process and returns its stdout and stderr outputs as lists of lines.
*
* @param homePath process run directory
* @param command command to execute and its arguments
* @return a tuple of (stdout lines, stderr lines, exit_code), lines in them have line terminators stripped, or may be null.
*/
@NotNull
public static ProcessOutput getProcessOutput(String homePath, @NonNls String[] command) {
return getProcessOutput(homePath, command, -1);
}
/**
* Executes a process and returns its stdout and stderr outputs as lists of lines.
* Waits for process for possibly limited duration.
*
* @param homePath process run directory
* @param command command to execute and its arguments
* @param timeout how many milliseconds to wait until the process terminates; non-positive means inifinity.
* @return a tuple of (stdout lines, stderr lines, exit_code), lines in them have line terminators stripped, or may be null.
*/
@NotNull
public static ProcessOutput getProcessOutput(String homePath, @NonNls String[] command, final int timeout) {
return getProcessOutput(homePath, command, null, timeout);
}
/**
* Executes a process and returns its stdout and stderr outputs as lists of lines.
* Waits for process for possibly limited duration.
*
* @param homePath process run directory
* @param command command to execute and its arguments
* @param addEnv items are prepended to same-named values of inherited process environment.
* @param timeout how many milliseconds to wait until the process terminates; non-positive means inifinity.
* @return a tuple of (stdout lines, stderr lines, exit_code), lines in them have line terminators stripped, or may be null.
*/
@NotNull
public static ProcessOutput getProcessOutput(String homePath,
@NonNls String[] command,
@Nullable @NonNls String[] addEnv,
final int timeout) {
return getProcessOutput(homePath, command, addEnv, timeout, null);
}
/**
* Executes a process and returns its stdout and stderr outputs as lists of lines.
* Waits for process for possibly limited duration.
*
* @param homePath process run directory
* @param command command to execute and its arguments
* @param addEnv items are prepended to same-named values of inherited process environment.
* @param timeout how many milliseconds to wait until the process terminates; non-positive means infinity.
* @param stdin the data to write to the process standard input stream
* @return a tuple of (stdout lines, stderr lines, exit_code), lines in them have line terminators stripped, or may be null.
*/
@NotNull
public static ProcessOutput getProcessOutput(String homePath,
@NonNls String[] command,
@Nullable @NonNls String[] addEnv,
final int timeout,
@Nullable byte[] stdin) {
final ProcessOutput failure_output = new ProcessOutput();
if (homePath == null || !new File(homePath).exists()) {
return failure_output;
}
try {
List<String> commands = new ArrayList<String>();
if (SystemInfo.isWindows && StringUtil.endsWithIgnoreCase(command[0], ".bat")) {
commands.add("cmd");
commands.add("/c");
}
Collections.addAll(commands, command);
String[] new_env = null;
if (addEnv != null) {
Map<String, String> env_map = new HashMap<String, String>(System.getenv());
// turn additional ent into map
Map<String, String> add_map = new HashMap<String, String>();
for (String env_item : addEnv) {
int pos = env_item.indexOf('=');
if (pos > 0) {
String key = env_item.substring(0, pos);
String value = env_item.substring(pos + 1, env_item.length());
add_map.put(key, value);
}
else {
LOG.warn(String.format("Invalid env value: '%s'", env_item));
}
}
// fuse old and new
for (Map.Entry<String, String> entry : add_map.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
final String old_value = env_map.get(key);
if (old_value != null) {
env_map.put(key, value + old_value);
}
else {
env_map.put(key, value);
}
}
new_env = new String[env_map.size()];
int i = 0;
for (Map.Entry<String, String> entry : env_map.entrySet()) {
new_env[i] = entry.getKey() + "=" + entry.getValue();
i += 1;
}
}
Process process = Runtime.getRuntime().exec(ArrayUtil.toStringArray(commands), new_env, new File(homePath));
CapturingProcessHandler processHandler = new CapturingProcessHandler(process);
if (stdin != null) {
final OutputStream processInput = processHandler.getProcessInput();
assert processInput != null;
processInput.write(stdin);
processInput.write(26); // EOF marker
processInput.flush();
}
return processHandler.runProcess(timeout);
}
catch (final IOException ex) {
LOG.warn(ex);
return new ProcessOutput() {
@Override
public String getStderr() {
String err = super.getStderr();
if (!StringUtil.isEmpty(err)) {
err += "\n" + ex.getMessage();
}
else {
err = ex.getMessage();
}
return err;
}
};
}
}
/**
* Finds the first match in a list os Strings.
*
* @param lines list of lines, may be null.
* @param regex pattern to match to.
* @return pattern's first matched group, or entire matched string if pattern has no groups, or null.
*/
@Nullable
public static String getFirstMatch(List<String> lines, Pattern regex) {
if (lines == null) return null;
for (String s : lines) {
Matcher m = regex.matcher(s);
if (m.matches()) {
if (m.groupCount() > 0) {
return m.group(1);
}
}
}
return null;
}
public static boolean isRemote(@Nullable Sdk sdk) {
return sdk != null && sdk.getSdkAdditionalData() instanceof PythonRemoteSdkAdditionalData;
}
}
|
package com.vrg.rapid;
import com.google.common.net.HostAndPort;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test public API
*/
public class ClusterTest {
@SuppressWarnings("FieldCanBeLocal")
@Nullable private static Logger grpcLogger = null;
private final ConcurrentHashMap<HostAndPort, Cluster> instances = new ConcurrentHashMap<>();
private final int basePort = 1234;
private final AtomicInteger portCounter = new AtomicInteger(basePort);
@BeforeClass
public static void beforeClass() {
// gRPC INFO logs clutter the test output
grpcLogger = Logger.getLogger("io.grpc");
grpcLogger.setLevel(Level.WARNING);
}
@Before
public void beforeTest() {
instances.clear();
// Tests need to opt out of the in-process channel
RpcServer.USE_IN_PROCESS_SERVER = true;
RpcClient.USE_IN_PROCESS_CHANNEL = true;
// Tests that depend on failure detection should set intervals by themselves
MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100000;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 100000;
}
@After
public void afterTest() throws InterruptedException {
for (final Cluster cluster: instances.values()) {
cluster.shutdown();
}
}
/**
* Test with a single node joining through a seed.
*/
@Test
public void singleNodeJoinsThroughSeed() throws IOException, InterruptedException, ExecutionException {
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(1, seedHost);
verifyClusterSize(1, seedHost);
extendCluster(1, seedHost);
verifyClusterSize(2, seedHost);
}
/**
* Test with K nodes joining the network through a single seed.
*/
@Test
public void tenNodesJoinSequentially() throws IOException, InterruptedException {
// Explicitly test netty
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final int numNodes = 10;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(1, seedHost); // Only bootstrap a seed.
verifyClusterSize(1, seedHost);
for (int i = 0; i < numNodes; i++) {
extendCluster(1, seedHost);
waitAndVerify( i + 2, 5, 100, seedHost);
}
}
/**
* Identical to the previous test, but with more than K nodes joining in serial.
*/
@Test
public void twentyNodesJoinSequentially() throws IOException, InterruptedException {
final int numNodes = 20;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(1, seedHost); // Only bootstrap a seed.
verifyClusterSize(1, seedHost);
for (int i = 0; i < numNodes; i++) {
extendCluster(1, seedHost);
waitAndVerify( i + 2, 5, 100, seedHost);
}
}
/**
* Identical to the previous test, but with more than K nodes joining in parallel.
* <p>
* The test starts with a single seed and all N - 1 subsequent nodes initiate their join protocol at the same
* time. This tests a single seed's ability to bootstrap a large cluster in one step.
*/
@Test
public void fiveHundredNodesJoinInParallel() throws IOException, InterruptedException {
final int numNodes = 500; // Includes the size of the cluster
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyClusterSize(numNodes, seedHost);
}
/**
* This test starts with a single seed, and a wave where 50 subsequent nodes initiate their join protocol
* concurrently. Following this, a subsequent wave begins where 100 nodes then start together.
*/
@Test
public void hundredNodesJoinFiftyNodeCluster() throws IOException, InterruptedException {
final int numNodesPhase1 = 50;
final int numNodesPhase2 = 100;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodesPhase1, seedHost);
verifyClusterSize(numNodesPhase1, seedHost);
extendCluster(numNodesPhase2, seedHost);
verifyClusterSize(numNodesPhase1 + numNodesPhase2, seedHost);
}
/**
* This test starts with a 4 node cluster. We then fail a single node to see if the monitoring mechanism
* identifies the failing node and arrives at a decision to remove it.
*/
@Test
public void oneFailureOutOfFourNodes() throws IOException, InterruptedException {
MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 1000;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
final int numNodes = 4;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyClusterSize(numNodes, seedHost);
final HostAndPort nodeToFail = HostAndPort.fromParts("127.0.0.1", basePort + 2);
failSomeNodes(Collections.singletonList(nodeToFail));
waitAndVerify(numNodes - 1, 10, 1000, seedHost);
}
/**
* This test starts with a 30 node cluster, then fails 5 nodes while an additional 10 join.
*/
@Test
public void concurrentNodeJoinsAndFails() throws IOException, InterruptedException {
MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 3000;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
final int numNodes = 30;
final int failingNodes = 5;
final int phaseTwojoiners = 10;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyClusterSize(numNodes, seedHost);
failSomeNodes(IntStream.range(basePort + 2, basePort + 2 + failingNodes)
.mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i))
.collect(Collectors.toList()));
extendCluster(phaseTwojoiners, seedHost);
waitAndVerify(numNodes - failingNodes + phaseTwojoiners, 20, 1000, seedHost);
}
/**
* This test starts with a 5 node cluster, then joins two waves of six nodes each.
*/
@Test
public void concurrentNodeJoinsNetty() throws IOException, InterruptedException {
MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 10000;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 10000;
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final int numNodes = 5;
final int phaseOneJoiners = 6;
final int phaseTwojoiners = 6;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyClusterSize(numNodes, seedHost);
final Random r = new Random();
for (int i = 0; i < phaseOneJoiners/2; i++) {
final List<HostAndPort> keysAsArray = new ArrayList<HostAndPort>(instances.keySet());
extendCluster(2, keysAsArray.get(r.nextInt(instances.size())));
Thread.sleep(50);
}
Thread.sleep(100);
for (int i = 0; i < phaseTwojoiners; i++) {
extendCluster(1, seedHost);
Thread.sleep(50);
}
waitAndVerify(numNodes + phaseOneJoiners + phaseTwojoiners, 20, 1000, seedHost);
}
/**
* This test starts with a 50 node cluster. We then fail 16 nodes to see if the monitoring mechanism
* identifies the crashed nodes, and arrives at a decision.
*
*/
@Test
public void sixteenFailuresOutOfFiftyNodes() throws IOException, InterruptedException {
MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 3000;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
final int numNodes = 50;
final int failingNodes = 16;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyClusterSize(numNodes, seedHost);
failSomeNodes(IntStream.range(basePort + 2, basePort + 2 + failingNodes)
.mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i))
.collect(Collectors.toList()));
waitAndVerify(numNodes - failingNodes, 20, 1000, seedHost);
}
/**
* Creates a cluster of size {@code numNodes} with a seed {@code seedHost}.
*
* @param numNodes cluster size
* @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point
* for subsequent joiners.
* @throws IOException Thrown if the Cluster.start() or join() methods throw an IOException when trying
* to register an RpcServer.
*/
private void createCluster(final int numNodes, final HostAndPort seedHost) throws IOException {
final Cluster seed = Cluster.start(seedHost);
instances.put(seedHost, seed);
assertEquals(seed.getMemberlist().size(), 1);
if (numNodes >= 2) {
extendCluster(numNodes - 1, seedHost);
}
}
/**
* Add {@code numNodes} instances to a cluster.
*
* @param numNodes cluster size
* @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point
* for subsequent joiners.
* @throws IOException Thrown if the Cluster.start() or join() methods throw an IOException when trying
* to register an RpcServer.
*/
private void extendCluster(final int numNodes, final HostAndPort seedHost) {
final ExecutorService executor = Executors.newWorkStealingPool(numNodes);
try {
final CountDownLatch latch = new CountDownLatch(numNodes);
for (int i = 0; i < numNodes; i++) {
executor.execute(() -> {
try {
final HostAndPort joiningHost =
HostAndPort.fromParts("127.0.0.1", portCounter.incrementAndGet());
final Cluster nonSeed = Cluster.join(seedHost, joiningHost);
instances.put(joiningHost, nonSeed);
} catch (final Exception e) {
e.printStackTrace();
fail();
} finally {
latch.countDown();
}
});
}
latch.await();
} catch (final Exception e) {
e.printStackTrace();
fail();
} finally {
executor.shutdown();
}
}
/**
* Fail a set of nodes in a cluster by calling shutdown().
*
* @param nodesToFail list of HostAndPort objects representing the nodes to fail
*/
private void failSomeNodes(final List<HostAndPort> nodesToFail) {
final ExecutorService executor = Executors.newWorkStealingPool(nodesToFail.size());
try {
final CountDownLatch latch = new CountDownLatch(nodesToFail.size());
for (final HostAndPort nodeToFail : nodesToFail) {
executor.execute(() -> {
try {
assertTrue(nodeToFail + " not in instances", instances.containsKey(nodeToFail));
instances.get(nodeToFail).shutdown();
instances.remove(nodeToFail);
} catch (final InterruptedException e) {
fail();
} finally {
latch.countDown();
}
});
}
latch.await();
} catch (final Exception e) {
e.printStackTrace();
fail();
} finally {
executor.shutdown();
}
}
/**
* Verify that all nodes in the cluster are of size {@code expectedSize} and have an identical
* list of members as the seed node.
*
* @param expectedSize expected size of each cluster
* @param seedHost seed node to validate the cluster view against
*/
private void verifyClusterSize(final int expectedSize, final HostAndPort seedHost) {
for (final Cluster cluster : instances.values()) {
assertEquals(cluster.getMemberlist().size(), expectedSize);
assertEquals(cluster.getMemberlist(), instances.get(seedHost).getMemberlist());
}
}
/**
* Verify whether the cluster has converged {@code maxTries} times with a delay of @{code intervalInMs}
* between attempts. This is used to give failure detector logic some time to kick in.
*
* @param expectedSize expected size of each cluster
* @param maxTries number of tries to check if the cluster has stabilized.
* @param intervalInMs the time duration between checks.
* @param seedNode the seed node to validate the cluster membership against
*/
private void waitAndVerify(final int expectedSize, final int maxTries, final int intervalInMs,
final HostAndPort seedNode)
throws InterruptedException {
int tries = maxTries;
while (--tries > 0) {
boolean ready = true;
for (final Cluster cluster : instances.values()) {
if (!(cluster.getMemberlist().size() == expectedSize
&& cluster.getMemberlist().equals(instances.get(seedNode).getMemberlist()))) {
ready = false;
}
}
if (!ready) {
Thread.sleep(intervalInMs);
} else {
break;
}
}
verifyClusterSize(expectedSize, seedNode);
}
}
|
package cz.bcx.coopgame.application;
import cz.bcx.coopgame.FrameBufferObject;
import cz.bcx.coopgame.StandardBatch;
import cz.bcx.coopgame.application.screen.ScreenManager;
import cz.bcx.coopgame.util.Color;
import org.lwjgl.glfw.GLFW;
public class Application {
///// INPUT EVENTS /////
public enum KeyAction {
PRESSED (GLFW.GLFW_PRESS),
RELEASED (GLFW.GLFW_RELEASE),
REPEAT (GLFW.GLFW_REPEAT);
private int keyAction;
KeyAction(int keyAction) {
this.keyAction = keyAction;
}
public static KeyAction getKeyAction(int action) {
for(KeyAction keyAction : KeyAction.values()) {
if(keyAction.keyAction == action) return keyAction;
}
return KeyAction.PRESSED;
}
}
public enum KeyModifier {
NONE (0x0000),
SHIFT (GLFW.GLFW_MOD_SHIFT),
CONTROL (GLFW.GLFW_MOD_CONTROL),
ALT (GLFW.GLFW_MOD_ALT),
SHIFT_CONTROL (SHIFT.keyModifier | CONTROL.keyModifier),
SHIFT_ALT (SHIFT.keyModifier | ALT.keyModifier),
SHIFT_CONTROL_ALT (SHIFT.keyModifier | CONTROL.keyModifier | ALT.keyModifier),
CONTROL_ALT (CONTROL.keyModifier | ALT.keyModifier);
//Fuck super key! Who uses super key anyway?
//Looking at you OSX users!
private int keyModifier;
KeyModifier(int keyModifier) {
this.keyModifier = keyModifier;
}
public static KeyModifier getModifier(int modifierValue) {
for(KeyModifier modifier : KeyModifier.values()) {
if(modifier.keyModifier == modifierValue) return modifier;
}
return NONE;
}
}
public static class KeyboardEvent {
public int key;
public KeyAction action;
public KeyModifier modifier;
public KeyboardEvent() {
this(-1, KeyAction.PRESSED, KeyModifier.NONE);
}
public KeyboardEvent(int key, KeyAction action, KeyModifier modifier) {
this.key = key;
this.action = action;
this.modifier = modifier;
}
public void set(int key, KeyAction action, KeyModifier modifier) {
this.key = key;
this.action = action;
this.modifier = modifier;
}
@Override
public String toString() {
return "[" + getClass().getSimpleName() + "] Key: " + key + ", KeyAction: " + action + ((modifier != KeyModifier.NONE) ? (", Modifier: " + modifier) : "");
}
}
///// Application /////
private static final int APPLICATION_BATCH_MAX_ENTITIES = 16; //TODO - Tweak
private final KeyboardEvent lastKeyboardEvent = new KeyboardEvent(0, KeyAction.PRESSED, KeyModifier.NONE);
private StandardBatch applicationBatch;
private ScreenManager screenManager;
private int windowWidth, windowHeight;
public Application(int windowWidth, int windowHeight) {
this.windowWidth = windowWidth;
this.windowHeight = windowHeight;
this.applicationBatch = new StandardBatch(APPLICATION_BATCH_MAX_ENTITIES);
this.screenManager = new ScreenManager(this);
}
public void onWindowResized(int width, int height) {
this.windowWidth = width;
this.windowHeight = height;
}
public void handleKeyboardEvent(int key, int action, int mods) {
lastKeyboardEvent.set(key, KeyAction.getKeyAction(action), KeyModifier.getModifier(mods));
screenManager.handleKeyboardEvent(lastKeyboardEvent);
}
public void update(float delta) {
screenManager.update(delta);
}
public void draw() {
//Draws screens to screen frame buffer
screenManager.getScreenFrameBuffer().bindFrameBuffer();
FrameBufferObject.clearFrameBuffer();
screenManager.draw();
screenManager.getScreenFrameBuffer().unbindFrameBuffer();
//Draws screen frame buffer to the screen
FrameBufferObject.clearFrameBuffer();
applicationBatch.begin();
applicationBatch.setColor(Color.WHITE);
applicationBatch.draw(screenManager.getScreenFrameBuffer().getColorTexture(), 0, 0, windowWidth, windowHeight, 0, 0, 1, 1);
applicationBatch.end();
}
public int getWindowWidth() {
return windowWidth;
}
public int getWindowHeight() {
return windowHeight;
}
public StandardBatch getApplicationBatch() {
return applicationBatch;
}
}
|
package datamanagement;
import java.util.List;
import java.util.HashMap;
import org.jdom.Element;
public class StudentUnitRecordManager
{
private static StudentUnitRecordManager manager_ = null;
private StudentUnitRecordMap recordMap_;
private HashMap<String, StudentUnitRecordList> ur; // What is this?
private HashMap<Integer, StudentUnitRecordList> sr; // And this?
public static StudentUnitRecordManager instance() // Change to getInstance() Affects multiple classes
{
if (manager_ == null)
manager_ = new StudentUnitRecordManager();
return manager_;
}
private StudentUnitRecordManager()
{
recordMap_ = new StudentUnitRecordMap();
ur = new HashMap<>();
sr = new HashMap<>();
}
public IStudentUnitRecord getStudentUnitRecord(Integer studentID,
String unitCode)
{
IStudentUnitRecord ir = recordMap_.get(studentID.toString() + unitCode);
return ir != null ? ir : createStudentUnitRecord(studentID, unitCode);
}
private IStudentUnitRecord createStudentUnitRecord(Integer uid, String sid)
{
IStudentUnitRecord ir;
for (Element el : (List<Element>) XMLManager.getXML().getDocument()
.getRootElement().getChild("studentUnitRecordTable")
.getChildren("record")) {
if (uid.toString().equals(el.getAttributeValue("sid"))
&& sid.equals(el.getAttributeValue("uid"))) {
ir = new StudentUnitRecord(new Integer(el.getAttributeValue("sid")),
el.getAttributeValue("uid"),
new Float(el.getAttributeValue("asg1")).floatValue(), new Float(
el.getAttributeValue("asg2")).floatValue(), new Float(
el.getAttributeValue("exam")).floatValue());
recordMap_.put(ir.getStudentID().toString() + ir.getUnitCode(), ir);
return ir;
}
}
throw new RuntimeException(
"DBMD: createStudent : student unit record not in file");
}
public StudentUnitRecordList getRecordsByUnit(String unitCode)
{
StudentUnitRecordList recs = ur.get(unitCode);
if (recs != null)
return recs;
recs = new StudentUnitRecordList();
for (Element el : (List<Element>) XMLManager.getXML().getDocument()
.getRootElement().getChild("studentUnitRecordTable")
.getChildren("record")) {
if (unitCode.equals(el.getAttributeValue("uid")))
recs.add(new StudentUnitRecordProxy(new Integer(el
.getAttributeValue("sid")), el.getAttributeValue("uid")));
}
if (recs.size() > 0)
ur.put(unitCode, recs); // be careful - this could be empty
return recs;
}
public StudentUnitRecordList getRecordsByStudent(Integer studentID)
{
StudentUnitRecordList recs = sr.get(studentID);
if (recs != null)
return recs;
recs = new StudentUnitRecordList();
for (Element el : (List<Element>) XMLManager.getXML().getDocument()
.getRootElement().getChild("studentUnitRecordTable")
.getChildren("record"))
if (studentID.toString().equals(el.getAttributeValue("sid")))
recs.add(new StudentUnitRecordProxy(new Integer(el
.getAttributeValue("sid")), el.getAttributeValue("uid")));
if (recs.size() > 0)
sr.put(studentID, recs); // be careful - this could be empty
return recs;
}
public void saveRecord(IStudentUnitRecord irec)
{
for (Element el : (List<Element>) XMLManager.getXML().getDocument()
.getRootElement().getChild("studentUnitRecordTable")
.getChildren("record")) {
if (irec.getStudentID().toString().equals(el.getAttributeValue("sid"))
&& irec.getUnitCode().equals(el.getAttributeValue("uid"))) {
el.setAttribute("asg1", new Float(irec.getAsg1()).toString());
el.setAttribute("asg2", new Float(irec.getAsg2()).toString());
el.setAttribute("exam", new Float(irec.getExam()).toString());
XMLManager.getXML().saveDocument(); // write out the XML file for
// continuous save
return;
}
}
throw new RuntimeException(
"DBMD: saveRecord : no such student record in data");
}
}
|
package de.gurkenlabs.litiengine.resources;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntBinaryOperator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBException;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.litiengine.environment.MapObjectSerializer;
import de.gurkenlabs.litiengine.environment.tilemap.IMap;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObject;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer;
import de.gurkenlabs.litiengine.environment.tilemap.IMapOrientation;
import de.gurkenlabs.litiengine.environment.tilemap.ITileLayer;
import de.gurkenlabs.litiengine.environment.tilemap.ITileset;
import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObjectLayer;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Tile;
import de.gurkenlabs.litiengine.environment.tilemap.xml.TileData;
import de.gurkenlabs.litiengine.environment.tilemap.xml.TileLayer;
import de.gurkenlabs.litiengine.environment.tilemap.xml.TmxException;
import de.gurkenlabs.litiengine.environment.tilemap.xml.TmxMap;
import de.gurkenlabs.litiengine.graphics.RenderType;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
import de.gurkenlabs.litiengine.util.io.XmlUtilities;
public final class Maps extends ResourcesContainer<IMap> {
private static final Logger log = Logger.getLogger(Maps.class.getName());
Maps() {
}
public static boolean isSupported(String fileName) {
String extension = FileUtilities.getExtension(fileName);
return extension != null && !extension.isEmpty() && extension.equalsIgnoreCase(TmxMap.FILE_EXTENSION);
}
/**
* Starts a process that allows the generation of maps from code.
* <p>
* Notice that you must call this within a try-with block or ensure that {@link MapGenerator#close()} is called before
* using the generated map instance.
* <p>
*
* <b>Example usage:</b>
*
* <pre>
* IMap map;
* try (MapGenerator generator = Resources.maps().generate("name", 50, 50, 16, 16, Resources.tilesets().get("tileset.tsx"))) {
* ITileLayer tileLayer = generator.addTileLayer(RenderType.GROUND, (x, y) -> {
* if (x == y) {
* // draw a diagonal in another tile color
* return 2;
* }
*
* // fill the entire map with this tile
* return 1;
* });
*
* // set an explicit tile at a location
* tileLayer.setTile(10, 10, 3);
*
* // add a collision box to the map
* generator.add(new CollisionBox(0, 64, 100, 10));
*
* map = generator.getMap();
* }
* </pre>
*
* @param orientation
* The orientation of the map to be generated.
* @param name
* The name of the map to be generated.
* @param width
* The width (in tiles).
* @param height
* The height (in tiles).
* @param tileWidth
* The width of a tile (in pixels).
* @param tileHeight
* The height of a tile (in pixels).
* @param tilesets
* Tilesets that will be used by the map.
* @return A <code>MapGenerator</code> instance used to add additional layers or objects to the map.
*/
public MapGenerator generate(IMapOrientation orientation, String name, int width, int height, int tileWidth, int tileHeight, ITileset... tilesets) {
TmxMap map = new TmxMap(orientation);
map.setTileWidth(tileWidth);
map.setTileHeight(tileHeight);
map.setWidth(width);
map.setHeight(height);
map.setName(name);
for (ITileset tileset : tilesets) {
map.getTilesets().add(tileset);
}
return new MapGenerator(map);
}
@Override
protected IMap load(URL resourceName) throws IOException, URISyntaxException {
TmxMap map;
try {
map = XmlUtilities.read(TmxMap.class, resourceName);
} catch (JAXBException e) {
throw new TmxException(e.getMessage(), e);
}
if (map == null) {
return null;
}
map.finish(resourceName);
return map;
}
@Override
protected String getAlias(String resourceName, IMap resource) {
if (resource == null || resource.getName() == null || resource.getName().isEmpty() || resource.getName().equalsIgnoreCase(resourceName)) {
return null;
}
return resource.getName();
}
/**
* This class provides the API to simplify the generation of map resources from code.
*/
public class MapGenerator implements AutoCloseable {
private final TmxMap map;
private MapGenerator(TmxMap map) {
this.map = map;
}
/**
* Gets the map generated by this instance.
* <p>
* Make sure this instance is closed before using the map in your game.
* </p>
*
* @return The map generated by this instance.
*
* @see #close()
*/
public IMap getMap() {
return this.map;
}
/**
* Adds a new tile tile layer to the generated map of this instance.
*
* <b>Example for a tileCallback:</b>
*
* <pre>
* (x, y) -> {
* if (x == y) {
* // draw a diagonal in another tile color
* return 2;
* }
*
* // fill the entire map with this tile
* return 1;
* }
* </pre>
*
* @param renderType
* The rendertype of the added layer.
* @param tileCallback
* The callback that defines which tile gid will be assigned at the specified x, y grid coordinates.
* @return The newly added tile layer.
*/
public ITileLayer addTileLayer(RenderType renderType, IntBinaryOperator tileCallback) {
List<Tile> tiles = new ArrayList<>();
for (int y = 0; y < this.map.getHeight(); y++) {
for (int x = 0; x < this.map.getWidth(); x++) {
int tile = tileCallback.applyAsInt(x, y);
tiles.add(new Tile(tile));
}
}
TileData data;
try {
data = new TileData(tiles, this.map.getWidth(), this.map.getHeight(), TileData.Encoding.CSV, TileData.Compression.NONE);
data.setValue(TileData.encode(data));
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
return null;
}
TileLayer layer = new TileLayer(data);
layer.setRenderType(renderType);
layer.setWidth(this.map.getWidth());
layer.setHeight(this.map.getHeight());
this.map.addLayer(layer);
return layer;
}
public IMapObject add(IEntity entity) {
return this.add(MapObjectSerializer.serialize(entity));
}
public IMapObject add(IMapObjectLayer layer, IEntity entity) {
IMapObject mapObject = MapObjectSerializer.serialize(entity);
return this.add(layer, mapObject);
}
public IMapObject add(IMapObject mapObject) {
IMapObjectLayer layer;
if (this.getMap().getMapObjectLayers().isEmpty()) {
layer = new MapObjectLayer();
layer.setName(MapObjectLayer.DEFAULT_MAPOBJECTLAYER_NAME);
this.getMap().addLayer(layer);
} else {
layer = this.getMap().getMapObjectLayer(0);
}
return this.add(layer, mapObject);
}
/**
* Adds the specified map object to the map of this instance.
*
* @param layer
* The layer to which the map object will be added.
* @param mapObject
* The mapObject to be added to the specified <code>MapObjectLayer</code>.
* @return The added map object.
*/
public IMapObject add(IMapObjectLayer layer, IMapObject mapObject) {
layer.addMapObject(mapObject);
return mapObject;
}
/**
* <b>It is crucial to call this before using the generated map of this instance.</b><br>
* <p>
* This will call the <code>finish</code> method on the map instance and make sure that the generated map is available
* over the resources API.
* </p>
*
* @see TmxMap#finish(URL)
* @see Maps#add(URL, IMap)
*/
@Override
public void close() {
try {
URL resource = Resources.getLocation(map.getName() + "." + TmxMap.FILE_EXTENSION);
this.map.finish(resource);
Maps.this.add(resource, this.map);
} catch (TmxException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
}
}
|
package de.ptb.epics.eve.ecp1.client;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import de.ptb.epics.eve.ecp1.client.interfaces.IChainStatusListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IConnectionStateListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IEngineStatusListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IErrorListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IMeasurementDataListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IPlayController;
import de.ptb.epics.eve.ecp1.client.interfaces.IPlayListController;
import de.ptb.epics.eve.ecp1.client.interfaces.IRequestListener;
import de.ptb.epics.eve.ecp1.client.model.MeasurementData;
import de.ptb.epics.eve.ecp1.client.model.Request;
import de.ptb.epics.eve.ecp1.intern.CancelRequestCommand;
import de.ptb.epics.eve.ecp1.intern.ChainStatusCommand;
import de.ptb.epics.eve.ecp1.intern.CurrentXMLCommand;
import de.ptb.epics.eve.ecp1.intern.EngineStatusCommand;
import de.ptb.epics.eve.ecp1.intern.ErrorCommand;
import de.ptb.epics.eve.ecp1.intern.GenericRequestCommand;
import de.ptb.epics.eve.ecp1.intern.IECP1Command;
import de.ptb.epics.eve.ecp1.intern.MeasurementDataCommand;
import de.ptb.epics.eve.ecp1.intern.PlayListCommand;
public class ECP1Client {
private Socket socket;
private Queue< byte[] > inQueue;
private Queue< IECP1Command > outQueue;
private InHandler inHandler;
private OutHandler outHandler;
private Thread inThread;
private Thread outThread;
private Thread dispatchThread;
private ECP1Client.InDispatcher dispatchHandler;
private String loginName;
private ECP1Client self;
private PlayListController playListController;
private final Queue< IEngineStatusListener > engineStatusListener;
private final Queue< IChainStatusListener > chainStatusListener;
private final Queue< IErrorListener > errorListener;
private final Queue< IMeasurementDataListener > measurementDataListener;
private final Queue< IRequestListener > requestListener;
private final Queue< IConnectionStateListener > connectionStateListener;
private PlayController playController;
private final Map< Integer, Request > requestMap;
private List< String > classNames;
private Map< Character, Constructor< ? extends IECP1Command > > commands;
private boolean running;
@SuppressWarnings("unchecked")
public ECP1Client() {
this.self = this;
this.inQueue = new ConcurrentLinkedQueue< byte[] >();
this.outQueue = new ConcurrentLinkedQueue< IECP1Command >();
this.playController = new PlayController( this );
this.playListController = new PlayListController( this );
this.engineStatusListener = new ConcurrentLinkedQueue< IEngineStatusListener >();
this.chainStatusListener = new ConcurrentLinkedQueue< IChainStatusListener >();
this.errorListener = new ConcurrentLinkedQueue< IErrorListener >();
this.measurementDataListener = new ConcurrentLinkedQueue< IMeasurementDataListener >();
this.requestListener = new ConcurrentLinkedQueue< IRequestListener >();
this.connectionStateListener = new ConcurrentLinkedQueue< IConnectionStateListener >();
this.requestMap = new HashMap< Integer, Request >();
this.classNames = new ArrayList< String >();
final String packageName = "de.ptb.epics.eve.ecp1.intern.";
this.classNames.add( packageName + "AddToPlayListCommand" );
this.classNames.add( packageName + "AnswerRequestCommand" );
this.classNames.add( packageName + "AutoPlayCommand" );
this.classNames.add( packageName + "BreakCommand" );
this.classNames.add( packageName + "CancelRequestCommand" );
this.classNames.add( packageName + "ChainStatusCommand" );
this.classNames.add( packageName + "CurrentXMLCommand" );
this.classNames.add( packageName + "EndProgramCommand" );
this.classNames.add( packageName + "EngineStatusCommand" );
this.classNames.add( packageName + "ErrorCommand" );
this.classNames.add( packageName + "GenericRequestCommand" );
this.classNames.add( packageName + "HaltCommand" );
this.classNames.add( packageName + "LiveDescriptionCommand" );
this.classNames.add( packageName + "MeasurementDataCommand" );
this.classNames.add( packageName + "PauseCommand" )
;
this.classNames.add( packageName + "PlayListCommand" );
this.classNames.add( packageName + "RemoveFromPlayListCommand" );
this.classNames.add( packageName + "ReorderPlayListCommand" );
this.classNames.add( packageName + "StartCommand" );
this.classNames.add( packageName + "StopCommand" );
this.commands = new HashMap< Character, Constructor< ? extends IECP1Command > >();
final Iterator< String > it = this.classNames.iterator();
final Class< IECP1Command > ecp1CommandInterface = IECP1Command.class;
final Class< byte[] > byteArrayClass = byte[].class;
final Class< ? >[] constructorParameterArray = new Class< ? >[1];
constructorParameterArray[0] = byteArrayClass;
while( it.hasNext() ) {
final String className = it.next();
try {
Class< ? extends IECP1Command > classObject = (Class< ? extends IECP1Command >) Class.forName( className );
if( !ecp1CommandInterface.isAssignableFrom( classObject ) ) {
System.err.println( "Error: " + className + " is not implementing IECP1Command!" );
continue;
}
final Field commandTypeIDField = classObject.getField( "COMMAND_TYPE_ID" );
final char id = commandTypeIDField.getChar( null );
final Constructor< ? extends IECP1Command > constructor = classObject.getConstructor( constructorParameterArray );
if( this.commands.get( id ) == null ) {
this.commands.put( id, constructor );
} else {
System.err.println( "Error: " + className + " and " + this.commands.get( id ).getDeclaringClass().getName() + "does have the same id = " + Integer.toHexString(id) + "!" );
}
//System.out.println( "The ID for " + className + " is " + Integer.toHexString(id) + "!" );
} catch( final ClassNotFoundException exception ) {
System.err.println( "Error: Can't find Class " + className + "!" );
} catch( final SecurityException exception ) {
exception.printStackTrace();
} catch( final NoSuchFieldException exception ) {
System.err.println( "Error: Can't find static Field COMMAND_TYPE_ID in " + className + "!" );
} catch( final IllegalArgumentException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
} catch( final IllegalAccessException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
} catch( final NoSuchMethodException exception ) {
System.err.println( "Error: Can't find Constructor for byte Array as Parameter in " + className + "!" );
}
}
}
public void close() throws IOException {
if( this.running ) {
this.inHandler.quit();
this.outHandler.quit();
this.running = false;
this.socket.shutdownInput();
this.socket.shutdownOutput();
this.socket.close();
Iterator< IConnectionStateListener > it = this.connectionStateListener.iterator();
while( it.hasNext() ) {
it.next().stackDisconnected();
}
}
}
public void connect( SocketAddress socketAddress, final String loginName ) throws IOException {
this.loginName = loginName;
this.socket = new Socket();
this.socket.connect( socketAddress );
this.inQueue.clear();
this.outQueue.clear();
this.running = true;
this.inHandler = new InHandler( this, this.socket.getInputStream(), this.inQueue );
this.outHandler = new OutHandler( this.socket.getOutputStream(), this.outQueue );
this.dispatchHandler = new ECP1Client.InDispatcher();
this.inThread = new Thread( this.inHandler );
this.outThread = new Thread( this.outHandler );
this.dispatchThread = new Thread( this.dispatchHandler );
this.inThread.start();
this.outThread.start();
this.dispatchThread.start();
Iterator< IConnectionStateListener > it = this.connectionStateListener.iterator();
while( it.hasNext() ) {
it.next().stackConnected();
}
}
public String getLoginName() {
return this.loginName;
}
public void addToOutQueue( final IECP1Command ecp1Command ) {
this.outQueue.add( ecp1Command );
}
public IPlayListController getPlayListController() {
return this.playListController;
}
public boolean addEngineStatusListener( final IEngineStatusListener engineStatusListener ) {
return this.engineStatusListener.add( engineStatusListener );
}
public boolean removeEngineStatusListener( final IEngineStatusListener engineStatusListener ) {
return this.engineStatusListener.remove( engineStatusListener );
}
public boolean addChainStatusListener( final IChainStatusListener chainStatusListener ) {
return this.chainStatusListener.add( chainStatusListener );
}
public boolean removeChainStatusListener( final IChainStatusListener chainStatusListener ) {
return this.chainStatusListener.remove( chainStatusListener );
}
public boolean addErrorListener( final IErrorListener errorListener ) {
return this.errorListener.add( errorListener );
}
public boolean removeErrorListener( final IErrorListener errorListener ) {
return this.errorListener.remove( errorListener );
}
public boolean addMeasurementDataListener( final IMeasurementDataListener measurementDataListener ) {
return this.measurementDataListener.add( measurementDataListener );
}
public boolean removeMeasurementDataListener( final IMeasurementDataListener measurementDataListener ) {
return this.measurementDataListener.remove( measurementDataListener );
}
public boolean addRequestListener( final IRequestListener requestListener ) {
return this.requestListener.add( requestListener );
}
public boolean removeRequestListener( final IRequestListener requestListener ) {
return this.requestListener.remove( requestListener );
}
public boolean addConnectionStateListener( final IConnectionStateListener requestListener ) {
return this.connectionStateListener.add( requestListener );
}
public boolean removeConnectionStateListener( final IConnectionStateListener requestListener ) {
return this.connectionStateListener.remove( requestListener );
}
private class InDispatcher implements Runnable {
public void run() {
while( running ) {
if( !inQueue.isEmpty() ) {
final byte[] packageArray = inQueue.poll();
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( packageArray );
final DataInputStream dataInputStream = new DataInputStream( byteArrayInputStream );
try {
dataInputStream.skip( 6 );
final char commandId = dataInputStream.readChar();
//System.err.println( "The ID of the current Command is: " + Integer.toHexString( commandId ) );
Constructor< ? extends IECP1Command > commandConstructor = commands.get( commandId );
if( commandConstructor != null ) {
final Object[] parameters = new Object[1];
parameters[0] = packageArray;
IECP1Command command = commandConstructor.newInstance( packageArray );
if( command instanceof EngineStatusCommand ) {
final Iterator< IEngineStatusListener > it = engineStatusListener.iterator();
final EngineStatusCommand engineStatusCommand = (EngineStatusCommand) command;
while( it.hasNext() ) {
it.next().engineStatusChanged( engineStatusCommand.getEngineStatus(), engineStatusCommand.getXmlName(), engineStatusCommand.getRepeatCount() );
}
playListController.reportAutoplay( engineStatusCommand.isAutoplay() );
} else if( command instanceof ChainStatusCommand ) {
final Iterator< IChainStatusListener > it = chainStatusListener.iterator();
final ChainStatusCommand chainStatusCommand = (ChainStatusCommand) command;
while( it.hasNext() ) {
it.next().chainStatusChanged( chainStatusCommand );
}
} else if( command instanceof ErrorCommand ) {
final Iterator< IErrorListener > it = errorListener.iterator();
final ErrorCommand errorCommand = (ErrorCommand) command;
final de.ptb.epics.eve.ecp1.client.model.Error error = new de.ptb.epics.eve.ecp1.client.model.Error( errorCommand );
while( it.hasNext() ) {
it.next().errorOccured( error );
}
} else if( command instanceof MeasurementDataCommand ) {
final Iterator< IMeasurementDataListener > it = measurementDataListener.iterator();
final MeasurementDataCommand measurementDataCommand = (MeasurementDataCommand) command;
final MeasurementData measurementData = new MeasurementData( measurementDataCommand );
while( it.hasNext() ) {
it.next().measurementDataTransmitted( measurementData );
}
} else if( command instanceof CurrentXMLCommand ) {
final CurrentXMLCommand currentXMLCommand = (CurrentXMLCommand)command;
playListController.reportCurrentXMLCommand( currentXMLCommand );
} else if( command instanceof PlayListCommand ) {
final PlayListCommand playListCommand = (PlayListCommand)command;
playListController.reportPlayListCommand( playListCommand );
} else if( command instanceof GenericRequestCommand ) {
final Iterator< IRequestListener > it = requestListener.iterator();
final GenericRequestCommand genericRequestCommand = (GenericRequestCommand)command;
final Request request = new Request( genericRequestCommand, self );
requestMap.put( request.getRequestId(), request );
while( it.hasNext() ) {
it.next().request( request );
}
} else if( command instanceof CancelRequestCommand ) {
final CancelRequestCommand cancelRequestCommand = (CancelRequestCommand)command;
final Request request = requestMap.get( cancelRequestCommand.getRequestId() );
if( request != null ) {
final Iterator< IRequestListener > it = requestListener.iterator();
while( it.hasNext() ) {
it.next().cancelRequest( request );
}
}
} else {
System.err.println( "Undispatchable Package with the Type " + command.getClass().getName() );
}
}
else {
System.err.println( "Unknown package type with the id: " + Integer.toHexString( commandId ) );
}
} catch( final IOException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
} catch( final IllegalArgumentException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
} catch( final InstantiationException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
} catch( final IllegalAccessException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
} catch( final InvocationTargetException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
}
} else {
try {
Thread.sleep( 10 );
} catch( final InterruptedException exception ) {
// TODO Auto-generated catch block
exception.printStackTrace();
}
}
}
}
}
public boolean isRunning() {
return this.running;
}
public IPlayController getPlayController() {
return this.playController;
}
public Queue<IRequestListener> getRequestListener() {
return requestListener;
}
}
|
package de.st_ddt.crazyutil.geo;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.Vector2D;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.bukkit.WorldEditAPI;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.CuboidRegionSelector;
import com.sk89q.worldedit.regions.CylinderRegion;
import com.sk89q.worldedit.regions.CylinderRegionSelector;
import com.sk89q.worldedit.regions.EllipsoidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.SphereRegionSelector;
public class WorldEditBridge
{
protected static WorldEditPlugin plugin;
protected final WorldEditAPI we;
public static WorldEditPlugin getWorldEditPlugin()
{
if (plugin == null)
plugin = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
return plugin;
}
public static WorldEditBridge getWorldEditBridge()
{
WorldEditPlugin plugin = getWorldEditPlugin();
if (plugin == null)
return null;
return new WorldEditBridge(plugin);
}
private WorldEditBridge(WorldEditPlugin plugin)
{
we = new WorldEditAPI(plugin);
}
public Geo getSavePlayerSelection(Player player)
{
try
{
return getPlayerSelection(player);
}
catch (WorldEditException e)
{
return null;
}
}
public Geo getPlayerSelection(Player player) throws WorldEditException
{
LocalWorld localWorld = we.getSession(player).getSelectionWorld();
Region region = we.getSession(player).getSelection(localWorld);
Geo geo = null;
World world = player.getWorld();
if (region instanceof CuboidRegion)
{
CuboidRegion region2 = (CuboidRegion) region;
Vector v1 = region2.getPos1();
Vector v2 = region2.getPos2();
Location location1 = new Location(world, v1.getX(), v1.getY(), v1.getZ());
Location location2 = new Location(world, v2.getX(), v2.getY(), v2.getZ());
geo = new Cuboid(world, location1, location2);
}
else if (region instanceof EllipsoidRegion)
{
EllipsoidRegion region2 = (EllipsoidRegion) region;
Vector v1 = region2.getCenter();
Vector v2 = region2.getRadius();
Location location1 = new Location(world, v1.getX(), v1.getY(), v1.getZ());
geo = new Sphere(location1, v2.length());
}
else if (region instanceof CylinderRegion)
{
CylinderRegion region2 = (CylinderRegion) region;
Vector v1 = region2.getCenter();
Vector2D v2 = region2.getRadius();
int height = region2.getMaximumY() - region2.getMinimumY() + 1;
Location location1 = new Location(world, v1.getX(), region2.getMinimumY(), v1.getZ());
geo = new Cylinder(location1, v2.length(), height);
}
return geo;
}
public void setPlayerSelection(Player player, Geo geo)
{
BukkitWorld bukkitWorld = new BukkitWorld(geo.getWorld());
RegionSelector selector = null;
if (geo instanceof Cuboid)
{
Cuboid region = (Cuboid) geo;
selector = new CuboidRegionSelector(bukkitWorld);
Location location1 = region.getLocation1();
Location location2 = region.getLocation2();
Vector v1 = new Vector(location1.getX(), location1.getY(), location1.getZ());
Vector v2 = new Vector(location2.getX(), location2.getY(), location2.getZ());
selector.selectPrimary(v1);
selector.selectSecondary(v2);
}
else if (geo instanceof Sphere)
{
Sphere region = (Sphere) geo;
selector = new SphereRegionSelector(bukkitWorld);
Location location1 = region.getCenter();
Vector v1 = new Vector(location1.getX(), location1.getY(), location1.getZ());
Vector v2 = new Vector(location1.getX() + region.getRadius(), location1.getY(), location1.getZ());
selector.selectPrimary(v1);
selector.selectSecondary(v2);
}
else if (geo instanceof Cylinder)
{
Cylinder region = (Cylinder) geo;
selector = new CylinderRegionSelector(bukkitWorld);
Location location1 = region.getCenter();
Vector v1 = new Vector(location1.getX(), location1.getY(), location1.getZ());
Vector v2 = new Vector(location1.getX() + region.getRadius(), location1.getY() + region.getHeight(), location1.getZ() + region.getRadius());
selector.selectPrimary(v1);
selector.selectSecondary(v2);
}
we.getSession(player).setRegionSelector(bukkitWorld, selector);
}
}
|
package detection.beaconDetector;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import peer.Peer;
import peer.RegisterCommunicationLayerException;
import peer.message.BroadcastMessage;
import peer.message.MessageSentListener;
import peer.messagecounter.MessageCounter;
import peer.peerid.PeerID;
import peer.peerid.PeerIDSet;
import util.WaitableThread;
import util.logger.Logger;
import config.Configuration;
import detection.NeighborDetector;
import detection.NeighborEventsListener;
import detection.message.BeaconMessage;
/**
* This class implements a neighbor detector using beacon sending. Beacons are
* sent using a fixed period of time unless another message was recently
* broadcasted from this peer.
*
* @author Unai Aguilera (unai.aguilera@gmail.com)
*
*/
public final class BeaconDetector implements NeighborDetector, MessageSentListener {
// This class is the thread which sends the beacons periodically
private class BeaconSendThread extends WaitableThread {
private final BeaconDetector beaconDetector;
private final Random r = new Random();
public BeaconSendThread(final BeaconDetector beaconDetector) {
this.beaconDetector = beaconDetector;
}
@Override
public void run() {
// send initial beacon
beaconDetector.sendBeacon();
while (!Thread.interrupted()) {
logger.trace("Peer " + peer.getPeerID() + " beacon thread running");
// Get the time elapsed since the last packet (beacon or not)
// was sent by this node
final long elapsedTime = System.currentTimeMillis() - lastSentTime.get();
// Clean old neighbors
beaconDetector.cleanOldNeighbors();
// Check if a beacon must be sent. Beacons are only sent if a
// packet was not previously broadcasted by this node in a
// period of time
final long sleepTime;
if (elapsedTime >= BEACON_TIME) {
// Send the beacon
beaconDetector.sendBeacon();
// Schedule next beacon sleeping the thread
sleepTime = BEACON_TIME;
} else
// Schedule timer for the difference of time (time for the
// next beacon)
sleepTime = BEACON_TIME - elapsedTime;
int randomSleep = r.nextInt(RANDOM_WAIT);
try {
Thread.sleep(sleepTime + randomSleep);
} catch (final InterruptedException e) {
finishThread();
return;
}
}
finishThread();
}
private void finishThread() {
logger.trace("Peer " + peer.getPeerID() + " beacon thread finalized");
this.threadFinished();
}
@Override
public void stopAndWait() {
logger.trace("Peer " + peer.getPeerID() + " interrupting beacon thread");
super.stopAndWait();
}
}
// Configuration properties
private int BEACON_TIME = 1000; // Default values
private int RANDOM_WAIT = 200;
// Stores the time of the last packet sent by this peer
private final AtomicLong lastSentTime = new AtomicLong();
private final Logger logger = Logger.getLogger(BeaconDetector.class);
// List of neighbor notification listeners
private final List<NeighborEventsListener> neighborNotificationListeners = new CopyOnWriteArrayList<NeighborEventsListener>();
// Map which contains current neighbors
private final Map<PeerID, Long> neighborsTable = new ConcurrentHashMap<PeerID, Long>();
// Reference to the peer
private final Peer peer;
private final MessageCounter msgCounter;
// Thread which sends beacons periodically
private BeaconSendThread beaconThread;
private BeaconMessage beaconMessage;
private long LOST_TIME;
private boolean init = false;
/**
* Constructor of the class. Configures internal properties using global
* configuration.
*
* @param peer
* the peer which provides communication capabilities
*/
public BeaconDetector(final Peer peer, final MessageCounter msgCounter) {
this.peer = peer;
this.msgCounter = msgCounter;
peer.addSentListener(this);
// Register the message heard listener
peer.setHearListener(this);
try {
peer.addCommunicationLayer(this, new HashSet<Class<? extends BroadcastMessage>>());
} catch (final RegisterCommunicationLayerException e) {
logger.error("Peer " + peer.getPeerID() + " had problem registering communication layer: " + e.getMessage());
}
}
@Override
public void addNeighborListener(final NeighborEventsListener listener) {
neighborNotificationListeners.add(listener);
}
@Override
public PeerIDSet getCurrentNeighbors() {
final PeerIDSet currentNeighbors = new PeerIDSet();
synchronized (neighborsTable) {
currentNeighbors.addPeers(neighborsTable.keySet());
}
return currentNeighbors;
}
@Override
public void init() {
try {
final String beaconTimeStr = Configuration.getInstance().getProperty("beaconDetector.beaconTime");
BEACON_TIME = Integer.parseInt(beaconTimeStr);
logger.info("Peer " + peer.getPeerID() + " set BEACON_TIME to " + BEACON_TIME);
final String randomWaitStr = Configuration.getInstance().getProperty("messageProcessor.randomWait");
RANDOM_WAIT = Integer.parseInt(randomWaitStr);
} catch (final Exception e) {
logger.error("Peer " + peer.getPeerID() + " had problem loading configuration: " + e.getMessage());
}
LOST_TIME = (BEACON_TIME + RANDOM_WAIT) * 2;
logger.trace("Peer " + peer.getPeerID() + " beacon time (" + BEACON_TIME + ")");
beaconMessage = new BeaconMessage(peer.getPeerID());
// Send initial beacon and schedule next
beaconThread = new BeaconSendThread(this);
beaconThread.start();
init = true;
}
@Override
public void messageReceived(final BroadcastMessage message, final long receptionTime) {
if (init) {
// Check that the message was received from an unknown neighbor
final boolean newNeighbor = !neighborsTable.containsKey(message.getSender());
// Update sender of the received message
neighborsTable.put(message.getSender(), Long.valueOf(System.currentTimeMillis()));
logger.trace("Peer " + peer.getPeerID() + " has updated neighbor " + message.getSender());
if (newNeighbor) {
PeerIDSet newNeighbors = new PeerIDSet();
newNeighbors.addPeer(message.getSender());
notifyAppearance(newNeighbors);
}
}
}
@Override
public void messageSent(final BroadcastMessage message, final long sentTime) {
// A message has been sent by this peer. Record sent time.
logger.trace("Peer " + peer.getPeerID() + " detected sent message");
lastSentTime.set(sentTime);
}
@Override
public void stop() {
beaconThread.stopAndWait();
}
// Cleans those neighbor not heard in a period of time specified by
// LOST_TIME
private void cleanOldNeighbors() {
final PeerIDSet removedPeers = new PeerIDSet();
synchronized (neighborsTable) {
// Remove those neighbors old enough
for (final Iterator<PeerID> it = neighborsTable.keySet().iterator(); it.hasNext();) {
final PeerID neighbor = it.next();
final long timestamp = neighborsTable.get(neighbor).longValue();
final long elapsedTime = System.currentTimeMillis() - timestamp;
if (elapsedTime >= LOST_TIME) {
logger.trace("Peer " + peer.getPeerID() + " removing neighbor " + neighbor + " elapsed time " + elapsedTime + " [" + System.currentTimeMillis() + " - " + timestamp + "]");
removedPeers.addPeer(neighbor);
it.remove();
}
}
}
// Notify neighbor removal to registered listeners
if (!removedPeers.isEmpty())
notifyDissappearance(removedPeers);
}
// Notify appearance of neighbors to listeners
private void notifyAppearance(final PeerIDSet neighbors) {
logger.debug("Peer " + peer.getPeerID() + " has new neighbors: " + neighbors);
logger.trace("Peer " + peer.getPeerID() + " current neighbors: " + getCurrentNeighbors());
for (final NeighborEventsListener listener : neighborNotificationListeners)
listener.appearedNeighbors(neighbors);
}
// Notify disappearance of neighbors to listeners
private void notifyDissappearance(final PeerIDSet neighbors) {
logger.debug("Peer " + peer.getPeerID() + " has lost neighbors: " + neighbors);
logger.trace("Peer " + peer.getPeerID() + " current neighbors: " + getCurrentNeighbors());
for (final NeighborEventsListener listener : neighborNotificationListeners)
listener.dissapearedNeighbors(neighbors);
}
// Send a beacon using broadcast provided by communication peer
private void sendBeacon() {
msgCounter.addSent(beaconMessage.getClass());
peer.broadcast(beaconMessage);
}
}
|
package cc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import cc.io._BufferedInputStream;
import cc.io._FileInputStream;
import cc.io._FileOutputStream;
import cc.test.R;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestActivity extends Activity
{
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// obviously does not exist so our exception will be caught.
Method multiCatchTest = getClass().getDeclaredMethod("doesNotExist");
} catch (SecurityException | NoSuchMethodException | IllegalArgumentException e) {
Toast.makeText(this,
"Multicatch exception was caught, yay",
Toast.LENGTH_LONG).show();
}
/* Java 8 won't work...
Comparator<Integer> cmp = (x, y) -> (x < y) ? -1 : ((x > y) ? 1 : 0);
if (cmp.compare(1, 2) == -1) {
Toast.makeText(this, "1 is less than 2", Toast.LENGTH_LONG).show();
}*/
String[] months = {
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC"};
int m = getRandomMonth(12);
Toast.makeText(this,
String.format(
"%s has %d days in its month.",
months[m],
getDaysInMonth(months[m])),
Toast.LENGTH_LONG).show();
// showing "try with resources"
try (_FileOutputStream fos = new _FileOutputStream("/sdcard/testfile.txt")) {
// integer literals work, yay
Toast.makeText(this,
String.format(
"Shown as 1_000 and 2_000 in the IDE, but shown as %d %d in Android as they should",
1_000, 2_000),
Toast.LENGTH_LONG).show();
// binary literal also works
byte[] writeData = {
(byte) 0b11011110, (byte) 0b10000000
};
fos.write(writeData);
Toast.makeText(this,
String.format(
"Written to testfile.txt: %s",
Arrays.toString(writeData)),
Toast.LENGTH_LONG).show();
} catch (IOException ioe) {
Toast.makeText(this,
String.format(
"Error: %s",
ioe.getMessage()),
Toast.LENGTH_LONG).show();
}
try (_FileInputStream fis = new _FileInputStream("/sdcard/testfile.txt")) {
// to show "diamonds" working
List<String> readData = new ArrayList<>(4);
int nextInt;
while ((nextInt = fis.read()) != -1) {
readData.add(String.valueOf(nextInt));
}
Toast.makeText(
this,
String.format(
"Read data from testfile.txt: %s",
readData.toString()),
Toast.LENGTH_LONG).show();
} catch (IOException ioe) {
Toast.makeText(this,
String.format(
"Error: %s",
ioe.getMessage()),
Toast.LENGTH_LONG).show();
}
}
/**
* Demonstrates that string switches are working.
*
* @param month
* @return
*/
public static int getDaysInMonth(String month)
{
switch (month) {
case "JAN":
return 31;
case "FEB":
return 28;
case "MAR":
return 31;
case "APR":
return 30;
case "MAY":
return 31;
case "JUN":
return 30;
case "JUL":
case "AUG":
return 31;
case "SEP":
return 30;
case "OCT":
return 31;
case "NOV":
return 30;
case "DEC":
return 31;
default:
return 0;
}
}
public static int getRandomMonth(int limit)
{
return (int) (Math.random() * limit);
}
}
|
package jwbroek.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class containing utility methods related to logging.
* @author jwbroek
*/
public final class LogUtil
{
/**
* The logger for this class.
*/
private final static Logger logger = Logger.getLogger(LogUtil.class.getCanonicalName());
/**
* This constructor need never be called as all members of this class are static.
*/
private LogUtil()
{
// Intentionally empty (except for logging). This class does not need to be instantiated.
LogUtil.logger.entering(LogUtil.class.getCanonicalName(), "TrackCutterCommand()");
LogUtil.logger.warning("jwbroek.util.LogUtil should not be instantiated.");
LogUtil.logger.exiting(LogUtil.class.getCanonicalName(), "TrackCutterCommand()");
}
/**
* Convenience method to log the stack trace of a Throwable to the specified Logger at the specified Level.
* @param logger Logger to log to.
* @param level Level to log at.
* @param throwable Throwable to log the stack strace of.
*/
public static void logStacktrace(final Logger logger, final Level level, final Throwable throwable)
{
LogUtil.logger.entering
( LogUtil.class.getCanonicalName()
, "logStacktrace(Logger,Level,Throwable)"
, new Object[] {logger, level, throwable}
);
// No need to do anything if the message isn't loggable.
if (logger.isLoggable(level))
{
final StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw));
logger.log(level, sw.toString());
}
LogUtil.logger.exiting(LogUtil.class.getCanonicalName(), "logStacktrace(Logger,Level,Throwable)");
}
/**
* Get the Level that is currently active on the specified Logger. Will search though parent Logger as necessary.
* @param logger The Logger to determine the Level of.
* @return The Level that is currently active on the specified Logger.
*/
public static Level getActiveLoggingLevel(Logger logger)
{
LogUtil.logger.entering(LogUtil.class.getCanonicalName(), "getActiveLoggingLevel(Logger)", logger);
Logger currentLogger = logger;
Level result = null;
do
{
result = logger.getLevel();
if (currentLogger.getUseParentHandlers())
{
currentLogger = currentLogger.getParent();
}
else
{
currentLogger = null;
}
} while (result==null && currentLogger != null);
LogUtil.logger.exiting(LogUtil.class.getCanonicalName(), "getActiveLoggingLevel(Logger)", result);
return result;
}
/**
* Get whether or not the information that is logged at the specified Level to the specified Logger
* will be handled by a Handler that is an instance of the specified class. Note that since loggers
* may be added and removed at any time, this information is not guaranteed to be correct at any moment.
* Also, even when this method return true, messages logged to the specified logger, at the specified level,
* may still not be logged by a handler of the specified type due to Filters that are configured.
* @param logger The Logger to check for.
* @param level The level to check for.
* @param handlerClass The class of Handler to check for.
* @return Whether or not the information that is logged at the specified Level to the specified Logger
* will be handled by a Handler that is an instance of the specified class.
*/
public static boolean hasHandlerActive(final Logger logger, final Level level, final Class handlerClass)
{
LogUtil.logger.entering
( LogUtil.class.getCanonicalName()
, "hasHandlerActive(Logger,Level,Class)"
, new Object[] {logger, level, handlerClass}
);
Logger currentLogger = logger;
boolean result = false;
loopOverLoggers:
while (currentLogger != null && currentLogger.isLoggable(level))
{
for (Handler handler : currentLogger.getHandlers())
{
// Handler is correct type of class and has low enough logging level.
if ( handlerClass.isInstance(handler)
&& handler.getLevel().intValue() <= level.intValue()
)
{
result = true;
break loopOverLoggers;
}
}
if (currentLogger.getUseParentHandlers())
{
currentLogger = currentLogger.getParent();
}
else
{
currentLogger = null;
}
}
LogUtil.logger.exiting(LogUtil.class.getCanonicalName(), "hasHandlerActive(Logger,Level,Class)", result);
return result;
}
/**
* Get a list of all currently active Handlers on the specified Logger. Note that handlers can be
* dynamically added and removed, so this information is not guaranteed to be correct at any moment.
* @param logger
* @return A list of all currently active Handlers on the specified Logger.
*/
public static Set<Handler> getAllActiveHandlers(final Logger logger)
{
LogUtil.logger.entering(LogUtil.class.getCanonicalName(), "getAllActiveHandlers(Logger)", logger);
final Set<Handler> handlers = new HashSet<Handler>();
Logger currentLogger = logger;
while (currentLogger != null)
{
handlers.addAll(Arrays.asList(currentLogger.getHandlers()));
if (currentLogger.getUseParentHandlers())
{
currentLogger = currentLogger.getParent();
}
else
{
currentLogger = null;
}
}
LogUtil.logger.exiting(LogUtil.class.getCanonicalName(), "getAllActiveHandlers(Logger)", handlers);
return handlers;
}
}
|
package hudson.remoting;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.List;
import java.util.Collections;
import java.util.logging.Logger;
import static java.util.logging.Level.SEVERE;
/**
* Slave agent engine that proactively connects to Hudson master.
*
* @author Kohsuke Kawaguchi
*/
public class Engine extends Thread {
/**
* Thread pool that sets {@link #CURRENT}.
*/
private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
public Thread newThread(final Runnable r) {
return defaultFactory.newThread(new Runnable() {
public void run() {
CURRENT.set(Engine.this);
r.run();
}
});
}
});
public final EngineListener listener;
private List<URL> candidateUrls;
private URL hudsonUrl;
private final String secretKey;
public final String slaveName;
private String credentials;
/**
* See Main#tunnel in the jnlp-agent module for the details.
*/
private String tunnel;
private boolean noReconnect;
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String slaveName) {
this.listener = listener;
this.candidateUrls = hudsonUrls;
this.secretKey = secretKey;
this.slaveName = slaveName;
if(candidateUrls.isEmpty())
throw new IllegalArgumentException("No URLs given");
}
public URL getHudsonUrl() {
return hudsonUrl;
}
public void setTunnel(String tunnel) {
this.tunnel = tunnel;
}
public void setCredentials(String creds) {
this.credentials = creds;
}
public void setNoReconnect(boolean noReconnect) {
this.noReconnect = noReconnect;
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
@Override
public void run() {
try {
boolean first = true;
while(true) {
if(first) {
first = false;
} else {
if(noReconnect)
return; // exit
}
listener.status("Locating server among " + candidateUrls);
Throwable firstError=null;
String port=null;
for (URL url : candidateUrls) {
String s = url.toExternalForm();
if(!s.endsWith("/")) s+='/';
URL salURL = new URL(s+"tcpSlaveAgentListener/");
// find out the TCP port
HttpURLConnection con = (HttpURLConnection)salURL.openConnection();
if (con instanceof HttpURLConnection && credentials != null) {
HttpURLConnection http = (HttpURLConnection) con;
String encoding = new sun.misc.BASE64Encoder().encode(credentials.getBytes());
http.setRequestProperty("Authorization", "Basic " + encoding);
}
try {
con.connect();
} catch (IOException x) {
if (firstError == null) {
firstError = new IOException("Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x);
}
continue;
}
port = con.getHeaderField("X-Hudson-JNLP-Port");
if(con.getResponseCode()!=200) {
if(firstError==null)
firstError = new Exception(salURL+" is invalid: "+con.getResponseCode()+" "+con.getResponseMessage());
continue;
}
if(port ==null) {
if(firstError==null)
firstError = new Exception(url+" is not Hudson");
continue;
}
// this URL works. From now on, only try this URL
hudsonUrl = url;
firstError = null;
candidateUrls = Collections.singletonList(hudsonUrl);
break;
}
if(firstError!=null) {
listener.error(firstError);
return;
}
final Socket s = connect(port);
listener.status("Handshaking");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Protocol:JNLP-connect");
dos.writeUTF(secretKey);
dos.writeUTF(slaveName);
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
String greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network?
if (!greeting.equals(GREETING_SUCCESS)) {
listener.error(new Exception("The server rejected the connection: "+greeting));
Thread.sleep(10*1000);
continue;
}
final Channel channel = new Channel("channel", executor,
in,
new BufferedOutputStream(s.getOutputStream()));
PingThread t = new PingThread(channel) {
protected void onDead() {
try {
if (!channel.isInClosed()) {
LOGGER.info("Ping failed. Terminating the socket.");
s.close();
}
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to terminate the socket", e);
}
}
};
t.start();
listener.status("Connected");
channel.join();
listener.status("Terminated");
t.interrupt(); // make sure the ping thread is terminated
listener.onDisconnect();
if(noReconnect)
return; // exit
// try to connect back to the server every 10 secs.
waitForServerToBack();
}
} catch (Throwable e) {
listener.error(e);
}
}
/**
* Read until '\n' and returns it as a string.
*/
private static String readLine(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true) {
int ch = in.read();
if (ch<0 || ch=='\n')
return baos.toString().trim(); // trim off possible '\r'
baos.write(ch);
}
}
/**
* Connects to TCP slave port, with a few retries.
*/
private Socket connect(String port) throws IOException, InterruptedException {
String host = this.hudsonUrl.getHost();
if(tunnel!=null) {
String[] tokens = tunnel.split(":",3);
if(tokens.length!=2)
throw new IOException("Illegal tunneling parameter: "+tunnel);
if(tokens[0].length()>0) host = tokens[0];
if(tokens[1].length()>0) port = tokens[1];
}
String msg = "Connecting to " + host + ':' + port;
listener.status(msg);
int retry = 1;
while(true) {
try {
Socket s = new Socket(host, Integer.parseInt(port));
s.setTcpNoDelay(true); // we'll do buffering by ourselves
return s;
} catch (IOException e) {
if(retry++>10)
throw e;
Thread.sleep(1000*10);
listener.status(msg+" (retrying:"+retry+")",e);
}
}
}
/**
* Waits for the server to come back.
*/
private void waitForServerToBack() throws InterruptedException {
while(true) {
Thread.sleep(1000*10);
try {
HttpURLConnection con = (HttpURLConnection)new URL(hudsonUrl,"tcpSlaveAgentListener/").openConnection();
con.connect();
if(con.getResponseCode()==200)
return;
} catch (IOException e) {
// retry
}
}
}
/**
* When invoked from within remoted {@link Callable} (that is,
* from the thread that carries out the remote requests),
* this method returns the {@link Engine} in which the remote operations
* run.
*/
public static Engine current() {
return CURRENT.get();
}
private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<Engine>();
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName());
public static final String GREETING_SUCCESS = "Welcome";
}
|
package checker;
import util.AST.*;
import util.AST.AST.Types;
import util.AST.Number;
import util.symbolsTable.IdentificationTable;
public class Checker implements Visitor{
private IdentificationTable idTable;
private int contadorParametros = 0;
public void check(Code code) throws SemanticException {
idTable = new IdentificationTable();
code.visit(this, null);
}
public Object visitAccept(Accept accept, Object args)
throws SemanticException {
return null;
}
public Object visitArithmeticExpression(ArithmeticExpression expression,
Object args) throws SemanticException {
return null;
}
public Object visitArithmeticFactor(ArithmeticFactor factor, Object args)
throws SemanticException {
return null;
}
public Object visitArithmeticParcel(ArithmeticParcel parcel, Object args)
throws SemanticException {
return null;
}
public Object visitArithmeticTerm(ArithmeticTerm term, Object args)
throws SemanticException {
return null;
}
public Object visitBooleanExpression(BooleanExpression expression,
Object args) throws SemanticException {
return null;
}
public Object visitBoolValue(BoolValue bool, Object args)
throws SemanticException {
return "PICBOOL";
}
public Object visitBreak(Break brk, Object args) throws SemanticException {
if (!(args instanceof Until)) {
throw new SemanticException("O comando BREAK só deve ser utilizado em loops");
}
return null;
}
public Object visitCode(Code code, Object args) throws SemanticException {
if (code.getGlobalDataDiv() != null) {
code.getGlobalDataDiv().visit(this, args);
}
code.getProgramDiv().visit(this, args);
return null;
}
public Object visitCommand(Command cmd, Object args)
throws SemanticException {
if (cmd instanceof IfStatement) {
return ((IfStatement) cmd).visit(this, args);
} else if (cmd instanceof Until) {
return ((Until) cmd).visit(this, args);
} else if (cmd instanceof Accept) {
return ((Accept) cmd).visit(this, args);
} else if (cmd instanceof Display) {
return ((Display) cmd).visit(this, args);
} else if (cmd instanceof FunctionCall) {
return ((FunctionCall) cmd).visit(this, args);
} else if (cmd instanceof Break) {
return ((Break) cmd).visit(this, args);
} else if (cmd instanceof Continue) {
return ((Continue) cmd).visit(this, args);
} else if (cmd instanceof Return) {
return ((Return) cmd).visit(this, args);
}
return null;
}
public Object visitContinue(Continue cont, Object args)
throws SemanticException {
if (!(args instanceof Until)) {
throw new SemanticException("O comando CONTINUE só deve ser utilizado em loops");
}
return null;
}
public Object visitDisplay(Display display, Object args)
throws SemanticException {
if (display.getIdentifier() != null) {
display.getIdentifier().visit(this, display);
} else {
display.getExpression().visit(this, display);
}
return null;
}
public Object visitExpression(Expression expression, Object args)
throws SemanticException {
return null;
}
public Object visitFunction(Function function, Object args)
throws SemanticException {
return null;
}
public Object visitFunctionCall(FunctionCall fcall, Object args)
throws SemanticException {
return null;
}
public Object visitGlobalDataDiv(GlobalDataDiv gdd, Object args)
throws SemanticException {
return null;
}
public Object visitIdentifier(Identifier id, Object args)
throws SemanticException {
if (args instanceof VarDeclaration) {
//TODO Verificar se tem que separar os tipos de declaracao
id.type = Types.VARIAVEL;
id.tipo = ((VarDeclaration) args).getType();
id.declaration = args;
idTable.enter(id.spelling, (AST)args);
} else if (args instanceof Function) {
id.type = Types.FUNCAO;
id.tipo = ((Function) args).getTipoRetorno();
id.declaration = args;
this.contadorParametros++;
idTable.enter(id.spelling, (AST) args);
} else if (args instanceof ArithmeticFactor){
if (idTable.retrieve(((ArithmeticFactor) args).getId().spelling) == null
&& ((ArithmeticFactor) args).getId() != null) {
throw new SemanticException("A variavel "
+ ((ArithmeticFactor) args).getId().spelling
+ " nao foi declarada!");
} else {
return ((ArithmeticFactor) args).getId().tipo;
}
} else {
id.type = Types.PARAMETRO;
id.declaration = args;
id.tipo = ((VarDeclaration) args).getType();
idTable.enter(id.spelling, (AST) args);
}
return null;
}
public Object visitIfStatement(IfStatement ifStatement, Object args)
throws SemanticException {
return null;
}
public Object visitMainProc(MainProc main, Object args)
throws SemanticException {
return null;
}
public Object visitNumber(Number number, Object args)
throws SemanticException {
return "PIC9";
}
public Object visitOpAdd(OpAdd opAdd, Object args) throws SemanticException {
return null;
}
public Object visitOpMult(OpMult opMult, Object args)
throws SemanticException {
return null;
}
public Object visitOpRelational(OpRelational opRel, Object args)
throws SemanticException {
return null;
}
public Object visitProgramDiv(ProgramDiv pdiv, Object args)
throws SemanticException {
return null;
}
public Object visitReturn(Return rtn, Object args) throws SemanticException {
if (args instanceof Function) {
if (((Function) args).getTipoRetorno().equals("VOID")) {
throw new SemanticException("Funcao VOID nao tem retorno");
} else if (true) {
}
}
return null;
}
public Object visitTerminal(Terminal term, Object args)
throws SemanticException {
return null;
}
public Object visitUntil(Until until, Object args) throws SemanticException {
until.getBooleanExpression().visit(this, args);
idTable.openScope();
for(Command cmd : until.getCommand()){
if (cmd instanceof Break) {
visitBreak((Break) cmd, args);
} else if (cmd instanceof Continue) {
visitContinue((Continue)cmd, args);
} else {
cmd.visit(this, until);
}
}
idTable.closeScope();
return null;
}
public Object visitVarDeclaration(VarDeclaration var, Object args)
throws SemanticException {
if (var instanceof VarPIC9Declaration) {
return ((VarPIC9Declaration) var).visit(this, args);
} else if (var instanceof VarPICBOOLDeclaration) {
return ((VarPICBOOLDeclaration) var).visit(this, args);
}
return null;
}
public Object visitVarPIC9Declaration(VarPIC9Declaration var9, Object args)
throws SemanticException {
if(idTable.retrieve(var9.getIdentifier().spelling) != null){
throw new SemanticException("Variavel " + var9.getIdentifier().spelling + " ja foi declarada");
} else {
var9.getIdentifier().visit(this, args);
}
return null;
}
public Object visitVarPICBOOLDeclaration(VarPICBOOLDeclaration varBool,
Object args) throws SemanticException {
if(idTable.retrieve(varBool.getIdentifier().spelling) != null){
throw new SemanticException("Variavel " + varBool.getIdentifier().spelling + " ja foi declarada");
} else {
varBool.getIdentifier().visit(this, args);
}
return null;
}
}
|
package checker;
import java.util.ArrayList;
import util.AST.*;
import util.AST.AST.Types;
import util.AST.Number;
import util.symbolsTable.IdentificationTable;
public class Checker implements Visitor{
private IdentificationTable idTable;
public void check(Code code) throws SemanticException {
idTable = new IdentificationTable();
code.visit(this, null);
}
public Object visitAccept(Accept accept, Object args)
throws SemanticException {
if(idTable.retrieve(accept.getIdentifier().spelling) == null){
throw new SemanticException("Variavel " + accept.getIdentifier().spelling + " nao declarada!");
} else {
if (accept.getIdIn() != null) {
if(!accept.getIdIn().visit(this, args).equals(accept.getIdentifier().type)){
throw new SemanticException(
"Tipos incompativeis. O valor atribuido nao eh do tipo da variavel!");
}
} else if (accept.getFunctionCall() != null) {
if(!accept.getFunctionCall().visit(this, args).equals(accept.getIdentifier().type)){
throw new SemanticException(
"Tipos incompativeis. O valor atribuido nao eh do tipo da variavel!");
}
} else if (accept.getExpression() != null) {
if(!accept.getFunctionCall().visit(this, args).equals(accept.getIdentifier().type)){
throw new SemanticException(
"Tipos incompativeis. O valor atribuido nao eh do tipo da variavel!");
}
} else {
throw new SemanticException("Valor nao informado!");
}
}
return null;
}
public Object visitArithmeticExpression(ArithmeticExpression expression,
Object args) throws SemanticException {
if (expression.getNumber() != null) {
return expression.getNumber().visit(this, args);
} else {
return expression.getArithmeticParcel().visit(this, args);
}
}
public Object visitArithmeticParcel(ArithmeticParcel parcel, Object args)
throws SemanticException {
ArithmeticTerm term = parcel.getArithmeticTerm();
ArithmeticParcel aExp = parcel.getArithmeticParcel();
Object temp = term.visit(this, args);
if (aExp == null) {
return term.visit(this, args);
} else if (aExp.visit(this, args) != null && aExp.visit(this, args).equals(temp)) {
return temp;
} else
throw new SemanticException("Tipos incompativeis ( "
+ term.visit(this, args) + " - "
+ aExp.visit(this, args) + " )");
}
public Object visitArithmeticTerm(ArithmeticTerm term, Object args)
throws SemanticException {
ArithmeticTerm termo = term.getArithmeticTerm();
ArithmeticFactor fac = term.getArithmeticFactor();
Object temp = fac.visit(this, args);
if (termo == null) {
return fac.visit(this, args);
} else if (termo.visit(this, args) != null && termo.visit(this, args).equals(temp)) {
return temp;
} else {
throw new SemanticException("Tipos incompativeis ( "
+ fac.visit(this, args) + " - "
+ termo.visit(this, args) + " )");
}
}
public Object visitArithmeticFactor(ArithmeticFactor factor, Object args)
throws SemanticException {
if (factor.getId() != null) {
return factor.getId().visit(this, factor);
} else if (factor.getNumber() != null) {
return "PIC9";
} else if (factor.getArithmeticParcel() != null) {
return factor.getArithmeticParcel().visit(this, args);
} else {
throw new SemanticException("Erro no visitArithmeticFactor");
}
}
public Object visitBooleanExpression(BooleanExpression expression,
Object args) throws SemanticException {
if (expression.getBooleanExpression_l() != null ||
(expression.getIdentifier_l() != null
&& ((VarDeclaration)idTable.retrieve(expression.getIdentifier_l().spelling) instanceof VarPICBOOLDeclaration)
&& ((VarPICBOOLDeclaration)idTable.retrieve(expression.getIdentifier_l().spelling)).getType().equals("PICBOOL"))) {
if(expression.getOpRelational().spelling.equals("=") || expression.getOpRelational().spelling.equals("<>")){
if (expression.getBooleanExpression_r() != null){
return "PICBOOL";
} else if (expression.getIdentifier_r() != null
&& expression.getIdentifier_r().type.equals("PICBOOL")) {
return "PICBOOL";
} else {
throw new SemanticException("Erro! Nao se pode comparar um booleano com um numero");
}
} else {
throw new SemanticException("Erro! Tipo de operador invalido");
}
} else if (expression.getArithmeticExpression_l() != null ||
(expression.getIdentifier_l() != null
&& ((VarDeclaration)idTable.retrieve(expression.getIdentifier_l().spelling) instanceof VarPIC9Declaration)
&& ((VarPIC9Declaration)idTable.retrieve(expression.getIdentifier_l().spelling)).getType().equals("PIC9"))) {
if (expression.getArithmeticExpression_r() != null
&& expression.getArithmeticExpression_r().visit(this, args).equals("PIC9")) {
return "PICBOOL";
} else if (expression.getIdentifier_r() != null
&& expression.getIdentifier_r().type.equals("PIC9")) {
return "PICBOOL";
} else {
throw new SemanticException("Erro! Nao se pode comparar um numero com um booleano");
}
} else {
throw new SemanticException("Erro no visitBooleanExpression!");
}
}
public Object visitBoolValue(BoolValue bool, Object args)
throws SemanticException {
return "PICBOOL";
}
public Object visitBreak(Break brk, Object args) throws SemanticException {
if (!(args instanceof Until)) {
throw new SemanticException("O comando BREAK só deve ser utilizado em loops");
}
return null;
}
public Object visitCode(Code code, Object args) throws SemanticException {
if (code.getGlobalDataDiv() != null) {
code.getGlobalDataDiv().visit(this, args);
}
code.getProgramDiv().visit(this, args);
return null;
}
public Object visitCommand(Command cmd, Object args)
throws SemanticException {
if (cmd instanceof IfStatement) {
return ((IfStatement) cmd).visit(this, args);
} else if (cmd instanceof Until) {
return ((Until) cmd).visit(this, args);
} else if (cmd instanceof Accept) {
return ((Accept) cmd).visit(this, args);
} else if (cmd instanceof Display) {
return ((Display) cmd).visit(this, args);
} else if (cmd instanceof FunctionCall) {
return ((FunctionCall) cmd).visit(this, args);
} else if (cmd instanceof Break) {
return ((Break) cmd).visit(this, args);
} else if (cmd instanceof Continue) {
return ((Continue) cmd).visit(this, args);
} else if (cmd instanceof Return) {
return ((Return) cmd).visit(this, args);
}
return null;
}
public Object visitContinue(Continue cont, Object args)
throws SemanticException {
if (!(args instanceof Until)) {
throw new SemanticException("O comando CONTINUE só deve ser utilizado em loops");
}
return null;
}
public Object visitDisplay(Display display, Object args)
throws SemanticException {
if (display.getIdentifier() != null) {
display.getIdentifier().visit(this, display);
} else {
display.getExpression().visit(this, display);
}
return null;
}
//TODO Analisar parte comentada pra ver se quer essa regra (nao ter comandos apos um retorno)
public Object visitFunction(Function function, Object args)
throws SemanticException {
function.getID().visit(this, function);
idTable.openScope();
if(function.getParams() != null)
for (Identifier param : function.getParams()) {
param.visit(this, args);
}
if(function.getVarDeclarations() != null)
for (VarDeclaration vDec : function.getVarDeclarations()) {
vDec.visit(this, function);
}
Object temp = null;
// ArrayList<Command> cmds = new ArrayList<Command>();
// for (Command cmd : function.getCommands()) {
// if (cmd instanceof Return) {
// temp = cmd;
// cmds.add(cmd);
// break;
// } else
// cmds.add(cmd);
// if (cmds.size() != function.getCommands().size())
// throw new SemanticException(
// "Nao deve haver comandos apos o retorno do procedimentos ou funcoes! [Regra extra]");
if(function.getVarDeclarations() != null){
for (VarDeclaration vDec : function.getVarDeclarations()) {
vDec.visit(this, function);
}
}
if(function.getCommands() != null)
for (Command cmd : function.getCommands()) {
if (temp != null) {
if (temp instanceof Return)
cmd.visit(this, function);
else
temp = cmd.visit(this, function);
} else
temp = cmd.visit(this, function);
}
if (temp == null && ((function.getTipoRetorno() != null && !function.getTipoRetorno().equals("VOID")))) {
throw new SemanticException("A Funcao " + function.getID().spelling
+ " precisa retornar um valor do tipo "
+ function.getTipoRetorno());
}
idTable.closeScope();
return null;
}
public Object visitFunctionCall(FunctionCall fcall, Object args)
throws SemanticException {
if (idTable.retrieve(fcall.getId().spelling) == null) {
throw new SemanticException("A funcao "
+ fcall.getId().spelling
+ " nao foi declarada!");
} else {
AST temp = idTable.retrieve(fcall.getId().spelling);
if (!(temp instanceof Function)) {
throw new SemanticException("Identificador "
+ fcall.getId().spelling
+ " nao representa uma Funcao!");
} else {
if (((Function) temp).getParamsTypes().size() != fcall.getParams().size()) {
throw new SemanticException(
"Quantidade de parametros passada diferente da quantidade de parametros requeridas pela Funcao!");
} else {
ArrayList<String> params = ((Function) temp).getParamsTypes();
for (int i = 0; i < params.size(); i++) {
if (params.get(i) != null && !params.get(i).equals(fcall.getParams().get(i).type)) {
throw new SemanticException(
"Tipo dos parametros informados não correspondem ao tipo esperado");
}
}
}
}
}
return null;
}
public Object visitGlobalDataDiv(GlobalDataDiv gdd, Object args)
throws SemanticException {
if(gdd.getVarDeclaration() != null)
for (VarDeclaration vDec : gdd.getVarDeclaration()) {
vDec.visit(this, null);
}
return null;
}
public Object visitIdentifier(Identifier id, Object args)
throws SemanticException {
if (args instanceof VarPIC9Declaration || args instanceof VarPICBOOLDeclaration) {
id.kind = Types.VARIAVEL;
id.type = ((VarDeclaration) args).getType();
id.declaration = args;
idTable.enter(id.spelling, (AST)args);
} else if (args instanceof Function) {
id.kind = Types.FUNCAO;
id.type = ((Function) args).getTipoRetorno();
id.declaration = args;
idTable.enter(id.spelling, (AST) args);
} else if (args instanceof ArithmeticFactor){
Object temp = idTable.retrieve(((ArithmeticFactor) args).getId().spelling);
if (temp == null && ((ArithmeticFactor) args).getId() != null) {
throw new SemanticException("A variavel "
+ ((ArithmeticFactor) args).getId().spelling
+ " nao foi declarada!");
} else {
if(temp instanceof VarPIC9Declaration) {
return ((VarPIC9Declaration) temp).getType();
} else {
return ((VarPICBOOLDeclaration) temp).getType();
}
}
}
return null;
}
public Object visitIfStatement(IfStatement ifStatement, Object args)
throws SemanticException {
Object temp = null;
if(ifStatement.getBooleanExpression() instanceof BooleanExpression){
((BooleanExpression) ifStatement.getBooleanExpression()).visit(this, args);
idTable.openScope();
if(ifStatement.getCommandIF() != null)
for (Command ifCmd : ifStatement.getCommandIF()) {
if (ifCmd instanceof Break) {
break;
} else
temp = ifCmd.visit(this, args);
}
idTable.closeScope();
idTable.openScope();
if(ifStatement.getCommandElse() != null)
for (Command elseCmd : ifStatement.getCommandElse()) {
if (elseCmd instanceof Break) {
break;
} else {
elseCmd.visit(this, args);
}
}
idTable.closeScope();
} else {
throw new SemanticException("Expressao da condicao do IF nao e booleana!");
}
return temp;
}
public Object visitMainProc(MainProc main, Object args)
throws SemanticException {
idTable.openScope();
if(main.getVarDeclarations() != null){
for (VarDeclaration vDec : main.getVarDeclarations()) {
vDec.visit(this, main);
}
}
if(main.getCommands() != null)
for (Command cmd : main.getCommands()) {
if (cmd instanceof Return) {
throw new SemanticException("Erro! A Main nao deve possuir retorno");
} else {
cmd.visit(this, main);
}
}
idTable.closeScope();
return null;
}
public Object visitNumber(Number number, Object args)
throws SemanticException {
return "PIC9";
}
public Object visitOpAdd(OpAdd opAdd, Object args) throws SemanticException {
return null;
}
public Object visitOpMult(OpMult opMult, Object args)
throws SemanticException {
return null;
}
public Object visitOpRelational(OpRelational opRel, Object args)
throws SemanticException {
return null;
}
public Object visitProgramDiv(ProgramDiv pdiv, Object args)
throws SemanticException {
if(pdiv.getArrayFunction() != null){
for (Function function : pdiv.getArrayFunction()) {
function.visit(this, null);
}
}
pdiv.getMainProc().visit(this, null);
return null;
}
public Object visitReturn(Return rtn, Object args) throws SemanticException {
if (args instanceof Function) {
if (((Function) args).getTipoRetorno() != null && ((Function) args).getTipoRetorno().equals("VOID")) {
throw new SemanticException("Funcao VOID nao tem retorno");
} else if (args instanceof Function && ((ArithmeticExpression) args).getArithmeticParcel() == null) {
if (rtn.getExpression().visit(this, args) != null && !(rtn.getExpression().visit(this, args).equals(((Function) args).getTipoRetorno()))) {
throw new SemanticException(
"Valor retornado incompativel com o tipo de retorno da funcao!");
} else {
Identifier id = ((ArithmeticParcel) args).getArithmeticTerm().getArithmeticFactor()
.getId();
AST temp = idTable.retrieve(id.spelling);
if (temp == null) {
throw new SemanticException("A variavel " + id.spelling
+ " nao foi declarada!");
}
}
} else if (rtn.getExpression().visit(this, args) != null && !(rtn.getExpression().visit(this, args).equals(((Function) args).getTipoRetorno()))) {
throw new SemanticException(
"Valor retornado incompativel com o tipo de retorno da funcao!");
}
} else {
throw new SemanticException(
"Comando de retorno deve estar dentro de uma funcao!");
}
return null;
}
public Object visitUntil(Until until, Object args) throws SemanticException {
until.getBooleanExpression().visit(this, args);
idTable.openScope();
if(until.getCommand() != null)
for(Command cmd : until.getCommand()){
if (cmd instanceof Break) {
visitBreak((Break) cmd, args);
} else if (cmd instanceof Continue) {
visitContinue((Continue)cmd, args);
} else {
cmd.visit(this, until);
}
}
idTable.closeScope();
return null;
}
public Object visitVarPIC9Declaration(VarPIC9Declaration var9, Object args)
throws SemanticException {
if(idTable.retrieve(var9.getIdentifier().spelling) != null){
throw new SemanticException("Variavel " + var9.getIdentifier().spelling + " ja foi declarada");
} else {
var9.getIdentifier().visit(this, var9);
}
return null;
}
public Object visitVarPICBOOLDeclaration(VarPICBOOLDeclaration varBool,
Object args) throws SemanticException {
if(idTable.retrieve(varBool.getIdentifier().spelling) != null){
throw new SemanticException("Variavel " + varBool.getIdentifier().spelling + " ja foi declarada");
} else {
varBool.getIdentifier().visit(this, varBool);
}
return null;
}
}
|
// This file is part of CL-EyeMulticam SDK
// Java JNI CLEyeMulticam wrapper
// It allows the use of multiple CL-Eye cameras in your own Java applications
package cl.eye;
//import processing.core.*;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import net.sf.jaer.aemonitor.AEListener;
import net.sf.jaer.aemonitor.AEMonitorInterface;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.hardwareinterface.HardwareInterface;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
public class CLCamera implements HardwareInterface {
protected final static Logger log = Logger.getLogger("CLEye");
protected static Preferences prefs=Preferences.userNodeForPackage(CLCamera.class);
/** Set true if library was loaded successfully. */
private static boolean libraryLoaded = false;
private final static String DLLNAME = "CLEyeMulticam";
private int cameraIndex = 0; // index of camera to open
private int cameraInstance = 0;
private boolean isOpened = false;
private int frameRateHz = prefs.getInt("CLCamera.frameRateHz",60);
private ColorMode colorMode = ColorMode.CLEYE_MONO_PROCESSED; // CLEYE_MONO_PROCESSED;
// static methods
static {
if (!isLibraryLoaded() && System.getProperty("os.name").startsWith("Windows")) {
try {
synchronized (CLCamera.class) { // prevent multiple access in class initializers like hardwareInterfaceFactory and SubClassFinder
// log.info("loading library " + System.mapLibraryName(DLLNAME));
// try {
// Thread.sleep(200);
// } catch (InterruptedException ex) {
System.loadLibrary(DLLNAME);
setLibraryLoaded(true);
}
log.info("CLEyeMulticam available");
} catch (UnsatisfiedLinkError e1) {
String lp = null;
try {
lp = System.getProperty("java.library.path");
} catch (Exception e) {
log.warning("caught " + e + " when trying to call System.getProperty(\"java.library.path\")");
}
log.warning("could not load the " + DLLNAME + " DLL; check native library path which is currently " + lp);
setLibraryLoaded(false);
}
}
}
public enum ColorMode {
CLEYE_MONO_PROCESSED(0), CLEYE_COLOR_PROCESSED(1),
CLEYE_MONO_RAW(2), CLEYE_COLOR_RAW(3), CLEYE_BAYER_RAW(4);
int code;
ColorMode(int code) {
this.code = code;
}
}
// camera color mode
public static final int CLEYE_MONO_PROCESSED = 0;
public static final int CLEYE_COLOR_PROCESSED = 1;
public static final int CLEYE_MONO_RAW = 2;
public static final int CLEYE_COLOR_RAW = 3;
public static final int CLEYE_BAYER_RAW = 4;
// camera resolution
public static final int CLEYE_QVGA = 0;
public static final int CLEYE_VGA = 1;
// camera sensor parameters
public static final int CLEYE_AUTO_GAIN = 0; // [0, 1]
public static final int CLEYE_GAIN = 1; // [0, 79]
public static final int CLEYE_AUTO_EXPOSURE = 2; // [0, 1]
public static final int CLEYE_EXPOSURE = 3; // [0, 511]
public static final int CLEYE_AUTO_WHITEBALANCE = 4; // [0, 1]
public static final int CLEYE_WHITEBALANCE_RED = 5; // [0, 255]
public static final int CLEYE_WHITEBALANCE_GREEN = 6; // [0, 255]
public static final int CLEYE_WHITEBALANCE_BLUE = 7; // [0, 255]
// camera linear transform parameters
public static final int CLEYE_HFLIP = 8; // [0, 1]
public static final int CLEYE_VFLIP = 9; // [0, 1]
public static final int CLEYE_HKEYSTONE = 10; // [-500, 500]
public static final int CLEYE_VKEYSTONE = 11; // [-500, 500]
public static final int CLEYE_XOFFSET = 12; // [-500, 500]
public static final int CLEYE_YOFFSET = 13; // [-500, 500]
public static final int CLEYE_ROTATION = 14; // [-500, 500]
public static final int CLEYE_ZOOM = 15; // [-500, 500]
// camera non-linear transform parameters
public static final int CLEYE_LENSCORRECTION1 = 16; // [-500, 500]
public static final int CLEYE_LENSCORRECTION2 = 17; // [-500, 500]
public static final int CLEYE_LENSCORRECTION3 = 18; // [-500, 500]
public static final int CLEYE_LENSBRIGHTNESS = 19; // [-500, 500]
public static final int[] CLEYE_FRAME_RATES = {15, 30, 60, 75, 100, 125}; // TODO only QVGA now
static{Arrays.sort(CLEYE_FRAME_RATES);}
native static int CLEyeGetCameraCount();
native static String CLEyeGetCameraUUID(int index);
native static int CLEyeCreateCamera(int cameraIndex, int mode, int resolution, int framerate);
native static boolean CLEyeDestroyCamera(int cameraIndex);
native static boolean CLEyeCameraStart(int cameraInstance);
native static boolean CLEyeCameraStop(int cameraInstance);
native static boolean CLEyeSetCameraParameter(int cameraInstance, int param, int val);
native static int CLEyeGetCameraParameter(int cameraInstance, int param);
native static boolean CLEyeCameraGetFrame(int cameraInstance, int[] imgData, int waitTimeout);
/**
* @return the libraryLoaded
*/
synchronized public static boolean isLibraryLoaded() {
return libraryLoaded;
}
/**
* @param aLibraryLoaded the libraryLoaded to set
*/
synchronized public static void setLibraryLoaded(boolean aLibraryLoaded) {
libraryLoaded = aLibraryLoaded;
}
public static int cameraCount() {
return CLEyeGetCameraCount();
}
public static String cameraUUID(int index) {
return CLEyeGetCameraUUID(index);
}
/** Constructs instance for first camera
*
*/
public CLCamera() {
}
/** Constructs instance to open the cameraIndex camera
*
* @param cameraIndex 0 based index of cameras.
*/
CLCamera(int cameraIndex) {
this.cameraIndex = cameraIndex;
}
private boolean createCamera(int cameraIndex, int mode, int resolution, int framerate) {
cameraInstance = CLEyeCreateCamera(cameraIndex, mode, resolution, framerate);
return cameraInstance != 0;
}
private boolean destroyCamera() {
if (cameraInstance == 0) {
return true;
}
return CLEyeDestroyCamera(cameraInstance);
}
protected boolean cameraStarted = false;
/** Starts the camera
*
* @return true if successful or if already started
*/
synchronized public boolean startCamera() {
if (cameraStarted) {
return true;
}
cameraStarted = CLEyeCameraStart(cameraInstance);
return cameraStarted;
}
/** Stops the camera
*
* @return true if successful or if not started
*/
synchronized public boolean stopCamera() {
if (!cameraStarted) {
return true;
}
boolean stopped = CLEyeCameraStop(cameraInstance);
cameraStarted = false;
return stopped;
}
/** Gets frame data
*
* @param imgData
* @param waitTimeout in ms
* @return true if successful
* @throws HardwareInterfaceException if there is an error
*/
synchronized public void getCameraFrame(int[] imgData, int waitTimeout) throws HardwareInterfaceException {
if (!CLEyeCameraGetFrame(cameraInstance, imgData, waitTimeout)) {
throw new HardwareInterfaceException("capturing frame");
}
}
synchronized public boolean setCameraParam(int param, int val) {
if (cameraInstance == 0) {
return false;
}
return CLEyeSetCameraParameter(cameraInstance, param, val);
}
public int getCameraParam(int param) {
return CLEyeGetCameraParameter(cameraInstance, param);
}
@Override
public String getTypeName() {
return "CLEye PS Eye camera";
}
private void dispose() {
stopCamera();
destroyCamera();
}
/** Stops the camera.
*
*/
@Override
public void close() {
if(!isOpened) return;
isOpened = false;
boolean stopped=stopCamera();
if(!stopped){
log.warning("stopCamera returned an error");
}
boolean destroyed=destroyCamera();
if(!destroyed){
log.warning("destroyCamera returned an error");
}
cameraInstance=0;
}
/** Opens the cameraIndex camera with some default settings and starts the camera. Set the frameRateHz before calling open().
*
* @throws HardwareInterfaceException
*/
@Override
public void open() throws HardwareInterfaceException {
if (isOpened) {
return;
}
// if (cameraInstance == 0) { // only make one instance, don't destroy it on close
boolean gotCam = createCamera(cameraIndex, colorMode.code, CLEYE_QVGA, getFrameRateHz()); // TODO fixed settings now
if (!gotCam) {
throw new HardwareInterfaceException("couldn't get camera");
}
if (!startCamera()) {
throw new HardwareInterfaceException("couldn't start camera");
}
isOpened = true;
}
@Override
public boolean isOpen() {
return isOpened;
}
/**
* @return the frameRateHz
*/
public int getFrameRateHz() {
return frameRateHz;
}
/**
* @param frameRateHz the frameRateHz to set
*/
synchronized public void setFrameRateHz(int frameRateHz) throws HardwareInterfaceException {
int old = this.frameRateHz;
int closest = closestRateTo(frameRateHz);
if (closest != frameRateHz) {
log.warning("returning closest allowed frame rate of " + closest + " from desired rate " + frameRateHz);
frameRateHz = closest;
}
if (old != frameRateHz && isOpen()) {
log.warning("new frame rate of " + frameRateHz + " will only take effect when camera is next opened");
}
this.frameRateHz = frameRateHz;
prefs.putInt("CLCamera.frameRateHz", this.frameRateHz);
}
private int closestRateTo(int rate) {
int ind = Arrays.binarySearch(CLEYE_FRAME_RATES, rate);
if(-ind>=CLEYE_FRAME_RATES.length){
return CLEYE_FRAME_RATES[CLEYE_FRAME_RATES.length];
}
if (ind <0) {
return CLEYE_FRAME_RATES[-ind-1];
}
return CLEYE_FRAME_RATES[ind];
}
/** Thrown for invalid parameters */
public class InvalidParameterException extends Exception {
public InvalidParameterException(String message) {
super(message);
}
}
/** Sets the gain value.
*
* @param gain gain value, range 0-79
* @throws HardwareInterfaceException if there is a hardware exception signaled by false return from driver
* @throws cl.eye.CLCamera.InvalidParameterException if parameter is invalid (outside range)
*/
synchronized public void setGain(int gain) throws HardwareInterfaceException, InvalidParameterException {
if (gain < 0) {
throw new InvalidParameterException("tried to set gain<0 (" + gain + ")");
}
if (gain > 79) {
throw new InvalidParameterException("tried to set gain>79 (" + gain + ")");
}
if (!setCameraParam(CLEYE_GAIN, gain)) {
throw new HardwareInterfaceException("setting gain to " + gain);
}
}
/** Asks the driver for the gain value.
*
* @return gain value
*/
public int getGain() {
int gain = getCameraParam(CLEYE_GAIN);
return gain;
}
/** Sets the exposure value.
*
* @param exp exposure value, range 0-511
* @throws HardwareInterfaceException if there is a hardware exception signaled by false return from driver
* @throws cl.eye.CLCamera.InvalidParameterException if parameter is invalid (outside range)
*/
synchronized public void setExposure(int exp) throws HardwareInterfaceException, InvalidParameterException {
if (exp < 0) {
throw new InvalidParameterException("tried to set exposure<0 (" + exp + ")");
}
if (exp > 511) {
throw new InvalidParameterException("tried to set exposure>511 (" + exp + ")");
}
if (!setCameraParam(CLEYE_EXPOSURE, exp)) {
throw new HardwareInterfaceException("setting exposure to " + exp);
}
}
/** Asks the driver for the exposure value.
*
* @return exposure value
*/
public int getExposure() {
int gain = getCameraParam(CLEYE_EXPOSURE);
return gain;
}
/** Enables auto gain
*
* @param yes
* @throws HardwareInterfaceException
*/
synchronized public void setAutoGain(boolean yes) throws HardwareInterfaceException {
if (!setCameraParam(CLEYE_AUTO_GAIN, yes ? 1 : 0)) {
throw new HardwareInterfaceException("setting auto gain=" + yes);
}
}
public boolean isAutoGain() {
return getCameraParam(CLEYE_AUTO_GAIN) != 0;
}
/** Enables auto exposure
*
* @param yes
* @throws HardwareInterfaceException
*/
synchronized public void setAutoExposure(boolean yes) throws HardwareInterfaceException {
if (!setCameraParam(CLEYE_AUTO_EXPOSURE, yes ? 1 : 0)) {
throw new HardwareInterfaceException("setting auto exposure=" + yes);
}
}
public boolean isAutoExposure() {
return getCameraParam(CLEYE_AUTO_EXPOSURE) != 0;
}
}
|
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// 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:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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:")) {
createTModel(line);
// 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:")) {
createPModel(line);
// 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();
/*
* 7/Apr/2010: MRH
* Neither of these variables are utilized
*/
// LinkedHashMap speciesStatus = new LinkedHashMap();
// int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
speciesSet = populateInitialStatusListWithReactiveSpecies(reader);
// 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:")) {
populateInitialStatusListWithInertSpecies(reader);
// 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);
}
}
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();
// 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;
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;
//11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT
// 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;
}
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);
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());
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);
//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) {
/*
* Rename current restart files:
* In the event RMG fails while writing the restart files,
* user won't lose any information
*/
String[] restartFiles = {"Restart/coreReactions.txt", "Restart/coreSpecies.txt",
"Restart/edgeReactions.txt", "Restart/edgeSpecies.txt", "Restart/lindemannReactions.txt",
"Restart/pdepnetworks.txt", "Restart/thirdBodyReactions.txt", "Restart/troeReactions.txt"};
writeBackupRestartFiles(restartFiles);
writeCoreSpecies();
writeCoreReactions();
writeEdgeSpecies();
writeEdgeReactions();
if (PDepNetwork.generateNetworks == true) writePDepNetworks();
/*
* Remove backup restart files from Restart folder
*/
removeBackupRestartFiles(restartFiles);
}
//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)));
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))));
//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);
}
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus());
}
//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);
}
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseRestartFiles method
*/
// private void parseRestartFiles() {
// parseAllSpecies();
// parseCoreSpecies();
// parseEdgeSpecies();
// parseAllReactions();
// parseCoreReactions();
/*
* MRH 23MAR2010:
* Commenting out deprecated parseEdgeReactions method
*/
// 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);
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// 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);
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// 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;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public LinkedHashSet parseAllSpecies() {
// // String restartFileContent ="";
// int speciesCount = 0;
// LinkedHashSet speciesSet = new LinkedHashSet();
// boolean added;
// try{
// long initialTime = System.currentTimeMillis();
// File coreSpecies = new File ("allSpecies.txt");
// BufferedReader reader = new BufferedReader(new FileReader(coreSpecies));
// String line = ChemParser.readMeaningfulLine(reader);
// int i=0;
// 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();
// 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.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;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// 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="";
}
/*
* MRH 25MAR2010
* This method is no longer used
*/
/*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);
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//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();
}
}
}
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//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"),false));
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"),false));
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"),false));
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()[0],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()[0],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[1];
k[0] = 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,true);
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 void createTModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = 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();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
public void createPModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = 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();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
public LinkedHashMap populateInitialStatusListWithReactiveSpecies(BufferedReader reader) throws IOException {
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
String 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
}
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)));
}
}
return speciesSet;
}
public void populateInitialStatusListWithInertSpecies(BufferedReader reader) {
String 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);
}
}
public ReactionModelEnlarger getReactionModelEnlarger() {
return reactionModelEnlarger;
}
public LinkedList getTempList() {
return tempList;
}
public LinkedList getPressList() {
return presList;
}
public LinkedList getInitialStatusList() {
return initialStatusList;
}
public void writeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]);
if (temporaryRestartFile.exists()) temporaryRestartFile.renameTo(new File(listOfFiles[i]+"~"));
}
}
public void removeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]+"~");
temporaryRestartFile.delete();
}
}
}
|
package net.fortuna.ical4j.model;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
import edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArrayList;
/**
* $Id$ [Apr 5, 2004]
*
* Defines a list of iCalendar parameters. A parameter list may be specified as unmodifiable at instantiation - useful
* for constant properties that you don't want modified.
* @author Ben Fortuna
*/
public class ParameterList implements Serializable {
private static final long serialVersionUID = -1913059830016450169L;
private List parameters;
/**
* Default constructor. Creates a modifiable parameter list.
*/
public ParameterList() {
this(false);
}
/**
* Constructor.
* @param unmodifiable indicates whether the list should be mutable
*/
public ParameterList(final boolean unmodifiable) {
if (unmodifiable) {
parameters = Collections.unmodifiableList(new ArrayList());
}
else {
parameters = new CopyOnWriteArrayList();
}
}
/**
* Creates a deep copy of the specified parameter list. That is, copies of all parameters in the specified list are
* added to this list.
* @param list a parameter list to copy parameters from
* @param unmodifiable indicates whether the list should be mutable
* @throws URISyntaxException where a parameter in the list specifies an invalid URI value
*/
public ParameterList(final ParameterList list, final boolean unmodifiable)
throws URISyntaxException {
parameters = new CopyOnWriteArrayList();
for (final Iterator i = list.iterator(); i.hasNext();) {
final Parameter parameter = (Parameter) i.next();
parameters.add(parameter.copy());
}
if (unmodifiable) {
parameters = Collections.unmodifiableList(parameters);
}
}
/**
* {@inheritDoc}
*/
public final String toString() {
final StringBuffer buffer = new StringBuffer();
for (final Iterator i = parameters.iterator(); i.hasNext();) {
buffer.append(';');
buffer.append(i.next().toString());
}
return buffer.toString();
}
/**
* Returns the first parameter with the specified name.
* @param aName name of the parameter
* @return the first matching parameter or null if no matching parameters
*/
public final Parameter getParameter(final String aName) {
for (final Iterator i = parameters.iterator(); i.hasNext();) {
final Parameter p = (Parameter) i.next();
if (aName.equalsIgnoreCase(p.getName())) {
return p;
}
}
return null;
}
/**
* Returns a list of parameters with the specified name.
* @param name name of parameters to return
* @return a parameter list
*/
public final ParameterList getParameters(final String name) {
final ParameterList list = new ParameterList();
for (final Iterator i = parameters.iterator(); i.hasNext();) {
final Parameter p = (Parameter) i.next();
if (p.getName().equalsIgnoreCase(name)) {
list.add(p);
}
}
return list;
}
/**
* Add a parameter to the list. Note that this method will not remove existing parameters of the same type. To
* achieve this use {
* @link ParameterList#replace(Parameter) }
* @param parameter the parameter to add
* @return true
* @see List#add(java.lang.Object)
*/
public final boolean add(final Parameter parameter) {
if (parameter == null) {
throw new IllegalArgumentException("Trying to add null Parameter");
}
return parameters.add(parameter);
}
/**
* Replace any parameters of the same type with the one specified.
* @param parameter parameter to add to this list in place of all others with the same name
* @return true if successfully added to this list
*/
public final boolean replace(final Parameter parameter) {
for (final Iterator i = getParameters(parameter.getName()).iterator(); i.hasNext();) {
remove((Parameter) i.next());
}
return add(parameter);
}
/**
* @return boolean indicates if the list is empty
* @see List#isEmpty()
*/
public final boolean isEmpty() {
return parameters.isEmpty();
}
/**
* @return an iterator
* @see List#iterator()
*/
public final Iterator iterator() {
return parameters.iterator();
}
/**
* Remove a parameter from the list.
* @param parameter the parameter to remove
* @return true if the list contained the specified parameter
* @see List#remove(java.lang.Object)
*/
public final boolean remove(final Parameter parameter) {
return parameters.remove(parameter);
}
/**
* Remove all parameters with the specified name.
* @param paramName the name of parameters to remove
*/
public final void removeAll(final String paramName) {
final ParameterList params = getParameters(paramName);
parameters.removeAll(params.parameters);
}
/**
* @return the number of parameters in the list
* @see List#size()
*/
public final int size() {
return parameters.size();
}
/**
* {@inheritDoc}
*/
public final boolean equals(final Object arg0) {
if (arg0 instanceof ParameterList) {
final ParameterList p = (ParameterList) arg0;
return ObjectUtils.equals(parameters, p.parameters);
}
return super.equals(arg0);
}
/**
* {@inheritDoc}
*/
public final int hashCode() {
return new HashCodeBuilder().append(parameters).toHashCode();
}
}
|
package org.jasig.portal.channels;
import org.jasig.portal.*;
import org.jasig.portal.utils.XSLT;
import org.jasig.portal.helpers.SAXHelper;
import org.xml.sax.DocumentHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.MalformedURLException;
/**
* <p>A channel which transforms XML for rendering in the portal.</p>
*
* <p>Static channel parameters to be supplied:
*
* 1) "xmlUri" - a URI representing the source XML document
* 2) "sslUri" - a URI representing the corresponding .ssl (stylesheet list) file
* 3) "xslTitle" - a title representing the stylesheet (optional)
* <i>If no title parameter is specified, a default
* stylesheet will be chosen according to the media</i>
* 4) "xslUri" - a URI representing the stylesheet to use
* <i>If <code>xslUri</code> is supplied, <code>sslUri</code>
* and <code>xslTitle</code> will be ignored.
* </p>
* <p>The static parameters above can be overridden by including
* parameters of the same name (<code>xmlUri</code>, <code>sslUri</code>,
* <code>xslTitle</code> and/or <code>xslUri</code> in the HttpRequest string.</p>
* <p>This channel can be used for all XML formats including RSS.
* Any other parameters passed to this channel via HttpRequest will get
* passed in turn to the XSLT stylesheet as stylesheet parameters. They can be
* read in the stylesheet as follows:
* <code><xsl:param name="yourParamName">aDefaultValue</xsl:param></code></p>
* @author Steve Toth, stoth@interactivebusiness.com
* @author Ken Weiner, kweiner@interactivebusiness.com
* @version $Revision$
*/
public class CGenericXSLT implements org.jasig.portal.IChannel
{
protected String xmlUri;
protected String sslUri;
protected String xslTitle;
protected String xslUri;
protected ChannelRuntimeData runtimeData;
protected String media;
protected MediaManager mm;
protected static String fs = File.separator;
protected static String stylesheetDir = GenericPortalBean.getPortalBaseDir () + "webpages" + "stylesheets" + fs + "org" + fs + "jasig" + fs + "portal" + fs + "CGenericXSLT" + fs;
protected static String sMediaProps = GenericPortalBean.getPortalBaseDir () + "properties" + fs + "media.properties";
// Cache transformed content in this smartcache - should be moved out of the channel
protected static SmartCache bufferCache = new SmartCache(15 * 60); // 15 mins
public CGenericXSLT ()
{
}
// Get channel parameters.
public void setStaticData (ChannelStaticData sd)
{
this.xmlUri = sd.getParameter("xml");
this.sslUri = sd.getParameter("ssl");
}
public void setRuntimeData (ChannelRuntimeData rd)
{
runtimeData = rd;
String xmlUri = runtimeData.getParameter("xmlUri");
if (xmlUri != null)
this.xmlUri = xmlUri;
String sslUri = runtimeData.getParameter("sslUri");
if (sslUri != null)
this.sslUri = sslUri;
String xslTitle = runtimeData.getParameter("xslTitle");
if (xslTitle != null)
this.xslTitle = xslTitle;
String xslUri = runtimeData.getParameter("xslUri");
if (xslUri != null)
this.xslUri = xslUri;
media = runtimeData.getMedia();
}
public void receiveEvent (LayoutEvent ev)
{
// No events to process here
}
// Access channel runtime properties.
public ChannelRuntimeProperties getRuntimeProperties ()
{
return new ChannelRuntimeProperties ();
}
// Set some channel properties -- going away
public ChannelSubscriptionProperties getSubscriptionProperties ()
{
return new ChannelSubscriptionProperties ();
}
public void renderXML(DocumentHandler out) throws PortalException
{
String xml;
Document xmlDoc;
sslUri = UtilitiesBean.fixURI(sslUri);
String key = getKey(); // Generate a key to lookup cache
SAXBufferImpl cache = (SAXBufferImpl)bufferCache.get(key);
// If there is cached content then write it out
if (cache == null)
{
cache = new SAXBufferImpl();
try
{
org.apache.xerces.parsers.DOMParser domParser = new org.apache.xerces.parsers.DOMParser();
org.jasig.portal.utils.DTDResolver dtdResolver = new org.jasig.portal.utils.DTDResolver();
domParser.setEntityResolver(dtdResolver);
domParser.parse(UtilitiesBean.fixURI(xmlUri));
xmlDoc = domParser.getDocument();
}
catch (IOException e)
{
throw new ResourceMissingException (xmlUri, "", e.getMessage());
}
catch (SAXException se)
{
throw new GeneralRenderingException("Problem parsing " + xmlUri + ": " + se);
}
runtimeData.put("baseActionURL", runtimeData.getBaseActionURL());
cache.startBuffering();
try
{
if (xslUri != null)
XSLT.transform(xmlDoc, new URL(xslUri), cache, runtimeData);
else
{
if (xslTitle != null)
XSLT.transform(xmlDoc, new URL(sslUri), cache, runtimeData, xslTitle, media);
else
XSLT.transform(xmlDoc, new URL(sslUri), cache, runtimeData, media);
}
Logger.log(Logger.INFO, "Caching output of CGenericXSLT for: " + key);
bufferCache.put(key, cache);
}
catch (SAXException se)
{
throw new GeneralRenderingException("Problem performing the transformation:" + se.toString());
}
catch (IOException ioe)
{
StringWriter sw = new StringWriter();
ioe.printStackTrace(new PrintWriter(sw));
sw.flush();
throw new GeneralRenderingException(sw.toString());
}
}
try
{
cache.outputBuffer(out);
}
catch (SAXException se)
{
throw new GeneralRenderingException("Problem retreiving output from cache:" + se.toString());
}
}
private String getKey()
{
StringBuffer sbKey = new StringBuffer(1024);
sbKey.append("xmluri:").append(xmlUri).append(", ");
sbKey.append("sslUri:").append(sslUri).append(", ");
sbKey.append("xslUri:").append(xslUri).append(", ");
sbKey.append("params:").append(runtimeData.toString()).append(", ");
sbKey.append("media:").append(media);
return sbKey.toString();
}
}
|
package org.pentaho.di.ui.spoon.trans;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransExecutionConfiguration;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.debug.BreakPointListener;
import org.pentaho.di.trans.debug.StepDebugMeta;
import org.pentaho.di.trans.debug.TransDebugMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepStatus;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.spoon.Messages;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.TabItemInterface;
import org.pentaho.di.ui.spoon.dialog.EnterPreviewRowsDialog;
import org.pentaho.di.ui.spoon.dialog.LogSettingsDialog;
/**
* SpoonLog handles the display of the logging information in the Spoon logging window.
*
* @see org.pentaho.di.ui.spoon.Spoon
* @author Matt
* @since 17 may 2003
*/
public class TransLog extends Composite implements TabItemInterface
{
private static final LogWriter log = LogWriter.getInstance();
public static final long UPDATE_TIME_VIEW = 1000L;
public static final long UPDATE_TIME_LOG = 2000L;
public static final long REFRESH_TIME = 100L;
public final static String START_TEXT = Messages.getString("SpoonLog.Button.StartTransformation"); //$NON-NLS-1$
public final static String PAUSE_TEXT = Messages.getString("SpoonLog.Button.PauseTransformation"); //$NON-NLS-1$
public final static String RESUME_TEXT = Messages.getString("SpoonLog.Button.ResumeTransformation"); //$NON-NLS-1$
public final static String STOP_TEXT = Messages.getString("SpoonLog.Button.StopTransformation"); //$NON-NLS-1$
private Display display;
private Shell shell;
private TransMeta transMeta;
private ColumnInfo[] colinf;
private TableView wFields;
private Button wOnlyActive;
private Button wSafeMode;
private Text wText;
private Button wStart;
private Button wPause;
private Button wStop;
private Button wPreview;
private Button wError;
private Button wClear;
private Button wLog;
private long lastUpdateView;
private long lastUpdateLog;
private FormData fdText, fdSash, fdStart, fdPause, fdPreview, fdError, fdClear, fdLog, fdOnlyActive, fdSafeMode;
private boolean running;
private boolean initialized;
private SelectionListener lsStart, lsPause, lsStop, lsPreview, lsError, lsClear, lsLog;
private StringBuffer message;
private FileInputStream in;
private Trans trans;
private Spoon spoon;
private boolean halted;
private boolean halting;
private boolean debug;
private FormData fdStop;
private boolean pausing;
public TransLog(Composite parent, final Spoon spoon, final TransMeta transMeta)
{
super(parent, SWT.NONE);
shell = parent.getShell();
this.spoon = spoon;
this.transMeta = transMeta;
trans = null;
display = shell.getDisplay();
running = false;
debug = false;
lastUpdateView = 0L;
lastUpdateLog = 0L;
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
setLayout(formLayout);
setVisible(true);
spoon.props.setLook(this);
SashForm sash = new SashForm(this, SWT.VERTICAL);
spoon.props.setLook(sash);
sash.setLayout(new FillLayout());
colinf = new ColumnInfo[] {
new ColumnInfo(Messages.getString("SpoonLog.Column.Stepname"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Copynr"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Read"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Written"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Input"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Output"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Updated"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Rejected"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Errors"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Active"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Time"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.Speed"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("SpoonLog.Column.PriorityBufferSizes"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
};
colinf[1].setAllignement(SWT.RIGHT);
colinf[2].setAllignement(SWT.RIGHT);
colinf[3].setAllignement(SWT.RIGHT);
colinf[4].setAllignement(SWT.RIGHT);
colinf[5].setAllignement(SWT.RIGHT);
colinf[6].setAllignement(SWT.RIGHT);
colinf[7].setAllignement(SWT.RIGHT);
colinf[8].setAllignement(SWT.RIGHT);
colinf[9].setAllignement(SWT.RIGHT);
colinf[10].setAllignement(SWT.RIGHT);
colinf[11].setAllignement(SWT.RIGHT);
colinf[12].setAllignement(SWT.RIGHT);
wFields = new TableView(transMeta, sash, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, 1, true, // readonly!
null, // Listener
spoon.props);
wText = new Text(sash, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY);
spoon.props.setLook(wText);
wText.setVisible(true);
wStart = new Button(this, SWT.PUSH);
wStart.setText(START_TEXT);
wStart.setEnabled(true);
wPause= new Button(this, SWT.PUSH);
wPause.setText(PAUSE_TEXT);
wPause.setEnabled(false);
wStop= new Button(this, SWT.PUSH);
wStop.setText(STOP_TEXT);
wStop.setEnabled(false);
wPreview = new Button(this, SWT.PUSH);
wPreview.setText(Messages.getString("SpoonLog.Button.Preview")); //$NON-NLS-1$
wError = new Button(this, SWT.PUSH);
wError.setText(Messages.getString("SpoonLog.Button.ShowErrorLines")); //$NON-NLS-1$
wClear = new Button(this, SWT.PUSH);
wClear.setText(Messages.getString("SpoonLog.Button.ClearLog")); //$NON-NLS-1$
wLog = new Button(this, SWT.PUSH);
wLog.setText(Messages.getString("SpoonLog.Button.LogSettings")); //$NON-NLS-1$
wOnlyActive = new Button(this, SWT.CHECK);
wOnlyActive.setText(Messages.getString("SpoonLog.Button.ShowOnlyActiveSteps")); //$NON-NLS-1$
spoon.props.setLook(wOnlyActive);
wSafeMode = new Button(this, SWT.CHECK);
wSafeMode.setText(Messages.getString("SpoonLog.Button.SafeMode")); //$NON-NLS-1$
spoon.props.setLook(wSafeMode);
fdStart = new FormData();
fdStart.left = new FormAttachment(0, 10);
fdStart.bottom = new FormAttachment(100, 0);
wStart.setLayoutData(fdStart);
fdPause= new FormData();
fdPause.left = new FormAttachment(wStart, 10);
fdPause.bottom = new FormAttachment(100, 0);
wPause.setLayoutData(fdPause);
fdStop = new FormData();
fdStop.left = new FormAttachment(wPause, 10);
fdStop.bottom = new FormAttachment(100, 0);
wStop.setLayoutData(fdStop);
fdPreview = new FormData();
fdPreview.left = new FormAttachment(wStop, 10);
fdPreview.bottom = new FormAttachment(100, 0);
wPreview.setLayoutData(fdPreview);
fdError = new FormData();
fdError.left = new FormAttachment(wPreview, 10);
fdError.bottom = new FormAttachment(100, 0);
wError.setLayoutData(fdError);
fdClear = new FormData();
fdClear.left = new FormAttachment(wError, 10);
fdClear.bottom = new FormAttachment(100, 0);
wClear.setLayoutData(fdClear);
fdLog = new FormData();
fdLog.left = new FormAttachment(wClear, 10);
fdLog.bottom = new FormAttachment(100, 0);
wLog.setLayoutData(fdLog);
fdOnlyActive = new FormData();
fdOnlyActive.left = new FormAttachment(wLog, Const.MARGIN);
fdOnlyActive.bottom = new FormAttachment(100, 0);
wOnlyActive.setLayoutData(fdOnlyActive);
wOnlyActive.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
spoon.props.setOnlyActiveSteps(wOnlyActive.getSelection());
}
});
wOnlyActive.setSelection(spoon.props.getOnlyActiveSteps());
fdSafeMode = new FormData();
fdSafeMode.left = new FormAttachment(wOnlyActive, Const.MARGIN);
fdSafeMode.bottom = new FormAttachment(100, 0);
wSafeMode.setLayoutData(fdSafeMode);
// Put text in the middle
fdText = new FormData();
fdText.left = new FormAttachment(0, 0);
fdText.top = new FormAttachment(0, 0);
fdText.right = new FormAttachment(100, 0);
fdText.bottom = new FormAttachment(100, 0);
wText.setLayoutData(fdText);
fdSash = new FormData();
fdSash.left = new FormAttachment(0, 0); // First one in the left top corner
fdSash.top = new FormAttachment(0, 0);
fdSash.right = new FormAttachment(100, 0);
fdSash.bottom = new FormAttachment(wStart, -5);
sash.setLayoutData(fdSash);
pack();
try
{
in = log.getFileInputStream();
}
catch (Exception e)
{
log.logError(Spoon.APP_NAME, Messages.getString("SpoonLog.Log.CouldNotLinkInputToOutputPipe")); //$NON-NLS-1$
}
lsError = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
showErrors();
}
};
final Timer tim = new Timer("TransLog: " + getMeta().getName());
final StringBuffer busy = new StringBuffer("N");
TimerTask timtask = new TimerTask()
{
public void run()
{
if (display != null && !display.isDisposed())
{
display.asyncExec(
new Runnable()
{
public void run()
{
if (busy.toString().equals("N"))
{
busy.setCharAt(0, 'Y');
checkStartThreads();
checkTransEnded();
checkErrors();
readLog();
refreshView();
busy.setCharAt(0, 'N');
}
}
}
);
}
}
};
tim.schedule(timtask, 0L, REFRESH_TIME); // schedule to repeat a couple of times per second to get fast feedback
lsStart = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
spoon.executeTransformation(transMeta, true, false, false, false, false, null);
}
};
lsPause = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
pauseResume();
}
};
lsStop = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
stop();
}
};
lsPreview = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
spoon.executeTransformation(transMeta, true, false, false, true, false, null);
}
};
lsClear = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
clearLog();
}
};
lsLog = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
setLog();
}
};
wError.addSelectionListener(lsError);
wStart.addSelectionListener(lsStart);
wPause.addSelectionListener(lsPause);
wStop.addSelectionListener(lsStop);
wPreview.addSelectionListener(lsPreview);
wClear.addSelectionListener(lsClear);
wLog.addSelectionListener(lsLog);
addDisposeListener(new DisposeListener()
{
public void widgetDisposed(DisposeEvent e)
{
tim.cancel();
}
});
}
private void checkStartThreads()
{
if (initialized && !running && trans!=null)
{
startThreads();
}
}
private void checkTransEnded()
{
if (trans != null)
{
if (trans.isFinished() && ( running || halted ))
{
log.logMinimal(Spoon.APP_NAME, Messages.getString("SpoonLog.Log.TransformationHasFinished")); //$NON-NLS-1$
running = false;
initialized=false;
halted = false;
halting = false;
try
{
trans.endProcessing("end"); //$NON-NLS-1$
if (spoonHistoryRefresher!=null) spoonHistoryRefresher.markRefreshNeeded();
}
catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("SpoonLog.Dialog.ErrorWritingLogRecord.Title"), Messages.getString("SpoonLog.Dialog.ErrorWritingLogRecord.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
wStart.setEnabled(true);
wPause.setEnabled(false);
wStop.setEnabled(false);
// OK, also see if we had a debugging session going on.
// If so and we didn't hit a breakpoint yet, display the show preview dialog...
if (debug && lastTransDebugMeta!=null && lastTransDebugMeta.getTotalNumberOfHits()==0) {
showLastPreviewResults();
}
debug=false;
}
}
}
public synchronized void start(TransExecutionConfiguration executionConfiguration)
{
if (!running) // Not running, start the transformation...
{
// Auto save feature...
if (transMeta.hasChanged())
{
if (spoon.props.getAutoSave())
{
spoon.saveToFile(transMeta);
}
else
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("SpoonLog.Dialog.FileHasChanged.Title"), //$NON-NLS-1$
null, Messages.getString("SpoonLog.Dialog.FileHasChanged1.Message") + Const.CR + Messages.getString("SpoonLog.Dialog.FileHasChanged2.Message") + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.QUESTION, new String[] { Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") }, //$NON-NLS-1$ //$NON-NLS-2$
0, Messages.getString("SpoonLog.Dialog.Option.AutoSaveTransformation"), //$NON-NLS-1$
spoon.props.getAutoSave());
int answer = md.open();
if ( (answer & 0xFF) == 0)
{
spoon.saveToFile(transMeta);
}
spoon.props.setAutoSave(md.getToggleState());
}
}
if (((transMeta.getName() != null && spoon.rep != null) || // Repository available & name set
(transMeta.getFilename() != null && spoon.rep == null) // No repository & filename set
) && !transMeta.hasChanged() // Didn't change
)
{
if (trans == null || (trans != null && trans.isFinished()))
{
try
{
// Set the requested logging level.
log.setLogLevel(executionConfiguration.getLogLevel());
trans = new Trans((VariableSpace)transMeta, spoon.rep, transMeta.getName(), transMeta.getDirectory().getPath(), transMeta.getFilename());
trans.setReplayDate(executionConfiguration.getReplayDate());
trans.injectVariables(executionConfiguration.getVariables());
trans.setMonitored(true);
log.logBasic(toString(), Messages.getString("SpoonLog.Log.TransformationOpened")); //$NON-NLS-1$
}
catch (KettleException e)
{
trans = null;
new ErrorDialog(shell,
Messages.getString("SpoonLog.Dialog.ErrorOpeningTransformation.Title"), Messages.getString("SpoonLog.Dialog.ErrorOpeningTransformation.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
readLog();
if (trans != null)
{
Map<String,String> arguments = executionConfiguration.getArguments();
final String args[];
if (arguments != null) args = convertArguments(arguments); else args = null;
setVariables(executionConfiguration);
log.logMinimal(Spoon.APP_NAME, Messages.getString("SpoonLog.Log.LaunchingTransformation") + trans.getTransMeta().getName() + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled());
// Launch the step preparation in a different thread.
// That way Spoon doesn't block anymore and that way we can follow the progress of the initialisation
final Thread parentThread = Thread.currentThread();
display.asyncExec(
new Runnable()
{
public void run()
{
prepareTrans(parentThread, args);
}
}
);
log.logMinimal(Spoon.APP_NAME, Messages.getString("SpoonLog.Log.StartedExecutionOfTransformation")); //$NON-NLS-1$
wStart.setEnabled(false);
wPause.setEnabled(true);
wStop.setEnabled(true);
readLog();
}
}
else
{
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("SpoonLog.Dialog.DoNoStartTransformationTwice.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("SpoonLog.Dialog.DoNoStartTransformationTwice.Message")); //$NON-NLS-1$
m.open();
}
}
else
{
if (transMeta.hasChanged())
{
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("SpoonLog.Dialog.SaveTransformationBeforeRunning.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("SpoonLog.Dialog.SaveTransformationBeforeRunning.Message")); //$NON-NLS-1$
m.open();
}
else if (spoon.rep != null && transMeta.getName() == null)
{
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("SpoonLog.Dialog.GiveTransformationANameBeforeRunning.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("SpoonLog.Dialog.GiveTransformationANameBeforeRunning.Message")); //$NON-NLS-1$
m.open();
}
else
{
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("SpoonLog.Dialog.SaveTransformationBeforeRunning2.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("SpoonLog.Dialog.SaveTransformationBeforeRunning2.Message")); //$NON-NLS-1$
m.open();
}
}
}
}
public synchronized void stop()
{
if (running && !halting)
{
halting = true;
trans.stopAll();
try
{
trans.endProcessing("stop"); //$NON-NLS-1$
log.logMinimal(Spoon.APP_NAME, Messages.getString("SpoonLog.Log.ProcessingOfTransformationStopped")); //$NON-NLS-1$
}
catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("SpoonLog.Dialog.ErrorWritingLogRecord.Title"), Messages.getString("SpoonLog.Dialog.ErrorWritingLogRecord.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
wStart.setEnabled(true);
wPause.setEnabled(false);
wStop.setEnabled(false);
running = false;
initialized = false;
halted = false;
halting = false;
transMeta.setInternalKettleVariables(); // set the original vars back as they may be changed by a mapping
}
}
public synchronized void pauseResume()
{
if (running)
{
if (!pausing)
{
pausing = true;
trans.pauseRunning();
wPause.setText(RESUME_TEXT);
wStart.setEnabled(false);
wPause.setEnabled(true);
wStop.setEnabled(true);
}
else
{
pausing = false;
trans.resumeRunning();
wPause.setText(PAUSE_TEXT);
wStart.setEnabled(false);
wPause.setEnabled(true);
wStop.setEnabled(true);
}
}
}
private synchronized void prepareTrans(final Thread parentThread, final String[] args)
{
Runnable runnable = new Runnable()
{
public void run()
{
try {
trans.prepareExecution(args);
initialized = true;
} catch (KettleException e) {
initialized = false;
}
halted = trans.hasHaltedSteps();
}
};
Thread thread = new Thread(runnable);
thread.start();
refreshView();
}
private synchronized void startThreads()
{
running=true;
trans.startThreads();
}
private void setVariables(TransExecutionConfiguration executionConfiguration)
{
Map<String, String> variables = executionConfiguration.getVariables();
transMeta.injectVariables(variables);
}
public void checkErrors()
{
if (trans != null)
{
if (!trans.isFinished())
{
if (trans.getErrors() != 0)
{
trans.killAll();
}
}
}
}
public void readLog()
{
long time = new Date().getTime();
long msSinceLastUpdate = time - lastUpdateLog;
if (msSinceLastUpdate < UPDATE_TIME_LOG)
{
return;
}
lastUpdateLog = time;
if (message == null)
message = new StringBuffer();
else
message.setLength(0);
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Const.XML_ENCODING));
String line;
while ((line = reader.readLine()) != null)
{
message.append(line);
message.append(Const.CR);
}
}
catch (Exception ex)
{
message.append("Unexpected error reading the log: " + ex.toString());
}
if (!wText.isDisposed() && message.length() > 0)
{
String mess = wText.getText();
wText.setSelection(mess.length());
wText.clearSelection();
wText.insert(message.toString());
int maxLines = Props.getInstance().getMaxNrLinesInLog();
if (maxLines>0 && wText.getLineCount()>maxLines)
{
// OK, remove the extra amount of character + 20 from
// Remove the oldest ones.
StringBuffer buffer = new StringBuffer(mess);
buffer.delete(0, message.length()+20);
wText.setText(buffer.toString());
}
}
}
private boolean refresh_busy;
private TransHistoryRefresher spoonHistoryRefresher;
private TransDebugMeta lastTransDebugMeta;
private void refreshView()
{
boolean insert = true;
if (wFields.isDisposed()) return;
if (refresh_busy) return;
refresh_busy = true;
Table table = wFields.table;
long time = new Date().getTime();
long msSinceLastUpdate = time - lastUpdateView;
if ( trans != null && msSinceLastUpdate > UPDATE_TIME_VIEW )
{
lastUpdateView = time;
int nrSteps = trans.nrSteps();
if (wOnlyActive.getSelection()) nrSteps = trans.nrActiveSteps();
if (table.getItemCount() != nrSteps)
{
table.removeAll();
}
else
{
insert = false;
}
if (nrSteps == 0)
{
if (table.getItemCount() == 0) new TableItem(table, SWT.NONE);
}
int nr = 0;
for (int i = 0; i < trans.nrSteps(); i++)
{
BaseStep baseStep = trans.getRunThread(i);
if ( (baseStep.isAlive() && wOnlyActive.getSelection()) || baseStep.getStatus()!=StepDataInterface.STATUS_EMPTY)
{
StepStatus stepStatus = new StepStatus(baseStep);
TableItem ti;
if (insert)
{
ti = new TableItem(table, SWT.NONE);
}
else
{
ti = table.getItem(nr);
}
String fields[] = stepStatus.getSpoonLogFields();
// Anti-flicker: if nothing has changed, don't change it on the screen!
for (int f = 1; f < fields.length; f++)
{
if (!fields[f].equalsIgnoreCase(ti.getText(f)))
{
ti.setText(f, fields[f]);
}
}
// Error lines should appear in red:
if (baseStep.getErrors() > 0)
{
ti.setBackground(GUIResource.getInstance().getColorRed());
}
else
{
ti.setBackground(GUIResource.getInstance().getColorWhite());
}
nr++;
}
}
wFields.setRowNums();
wFields.optWidth(true);
}
else
{
// We need at least one table-item in a table!
if (table.getItemCount() == 0) new TableItem(table, SWT.NONE);
}
refresh_busy = false;
}
public synchronized void debug(TransExecutionConfiguration executionConfiguration, TransDebugMeta transDebugMeta)
{
if (!running)
{
try
{
this.lastTransDebugMeta = transDebugMeta;
log.setLogLevel(executionConfiguration.getLogLevel());
log.logDetailed(toString(), Messages.getString("SpoonLog.Log.DoPreview")); //$NON-NLS-1$
String[] args=null;
Map<String,String> arguments = executionConfiguration.getArguments();
if (arguments != null)
{
args = convertArguments(arguments);
}
setVariables(executionConfiguration);
// Create a new transformation to execution
trans = new Trans(transMeta);
trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled());
trans.prepareExecution(args);
// Add the row listeners to the allocated threads
transDebugMeta.addRowListenersToTransformation(trans);
// What method should we call back when a break-point is hit?
transDebugMeta.addBreakPointListers(new BreakPointListener() {
public void breakPointHit(TransDebugMeta transDebugMeta, StepDebugMeta stepDebugMeta, RowMetaInterface rowBufferMeta, List<Object[]> rowBuffer) {
showPreview(transDebugMeta, stepDebugMeta, rowBufferMeta, rowBuffer);
}
}
);
// Start the threads for the steps...
trans.startThreads();
readLog();
running = !running;
debug=true;
wStart.setEnabled(false);
wPause.setEnabled(true);
wStop.setEnabled(true);
}
catch (Exception e)
{
new ErrorDialog(shell, Messages.getString("SpoonLog.Dialog.UnexpectedErrorDuringPreview.Title"), Messages.getString("SpoonLog.Dialog.UnexpectedErrorDuringPreview.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
{
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(Messages.getString("SpoonLog.Dialog.DoNoPreviewWhileRunning.Title")); //$NON-NLS-1$
m.setMessage(Messages.getString("SpoonLog.Dialog.DoNoPreviewWhileRunning.Message")); //$NON-NLS-1$
m.open();
}
}
private String[] convertArguments(Map<String, String> arguments)
{
String[] argumentNames = arguments.keySet().toArray(new String[arguments.size()]);
Arrays.sort(argumentNames);
String args[] = new String[argumentNames.length];
for (int i = 0; i < args.length; i++)
{
String argumentName = argumentNames[i];
args[i] = arguments.get(argumentName);
}
return args;
}
public void showPreview(final TransDebugMeta transDebugMeta, final StepDebugMeta stepDebugMeta, final RowMetaInterface rowBufferMeta, final List<Object[]> rowBuffer)
{
display.asyncExec(new Runnable() {
public void run() {
// The transformation is now paused, indicate this in the log dialog...
pausing=true;
wPause.setText(RESUME_TEXT);
PreviewRowsDialog previewRowsDialog = new PreviewRowsDialog(shell, transMeta, SWT.APPLICATION_MODAL, stepDebugMeta.getStepMeta().getName(), rowBufferMeta, rowBuffer);
previewRowsDialog.open();
// clear the row buffer.
// That way if you click resume, you get the next N rows for the step :-)
rowBuffer.clear();
}
});
}
private void clearLog()
{
wFields.table.removeAll();
new TableItem(wFields.table, SWT.NONE);
wText.setText(""); //$NON-NLS-1$
}
private void setLog()
{
LogSettingsDialog lsd = new LogSettingsDialog(shell, SWT.NONE, log, spoon.props);
lsd.open();
}
public void showErrors()
{
String all = wText.getText();
ArrayList<String> err = new ArrayList<String>();
int i = 0;
int startpos = 0;
int crlen = Const.CR.length();
while (i < all.length() - crlen)
{
if (all.substring(i, i + crlen).equalsIgnoreCase(Const.CR))
{
String line = all.substring(startpos, i);
String uLine = line.toUpperCase();
if (uLine.indexOf(Messages.getString("SpoonLog.System.ERROR")) >= 0 || //$NON-NLS-1$
uLine.indexOf(Messages.getString("SpoonLog.System.EXCEPTION")) >= 0 || //$NON-NLS-1$
uLine.indexOf("ERROR") >= 0 || // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
uLine.indexOf("EXCEPTION") >= 0 // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
)
{
err.add(line);
}
// New start of line
startpos = i + crlen;
}
i++;
}
String line = all.substring(startpos);
String uLine = line.toUpperCase();
if (uLine.indexOf(Messages.getString("SpoonLog.System.ERROR2")) >= 0 || //$NON-NLS-1$
uLine.indexOf(Messages.getString("SpoonLog.System.EXCEPTION2")) >= 0 || //$NON-NLS-1$
uLine.indexOf("ERROR") >= 0 || // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
uLine.indexOf("EXCEPTION") >= 0 // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
)
{
err.add(line);
}
if (err.size() > 0)
{
String err_lines[] = new String[err.size()];
for (i = 0; i < err_lines.length; i++)
err_lines[i] = err.get(i);
EnterSelectionDialog esd = new EnterSelectionDialog(shell, err_lines, Messages.getString("SpoonLog.Dialog.ErrorLines.Title"), Messages.getString("SpoonLog.Dialog.ErrorLines.Message")); //$NON-NLS-1$ //$NON-NLS-2$
line = esd.open();
if (line != null)
{
for (i = 0; i < transMeta.nrSteps(); i++)
{
StepMeta stepMeta = transMeta.getStep(i);
if (line.indexOf(stepMeta.getName()) >= 0)
{
spoon.editStep(transMeta, stepMeta);
}
}
// System.out.println("Error line selected: "+line);
}
}
}
public String toString()
{
return Spoon.APP_NAME;
}
/**
* @return Returns the running.
*/
public boolean isRunning()
{
return running;
}
public void setTransHistoryRefresher(TransHistoryRefresher spoonHistoryRefresher)
{
this.spoonHistoryRefresher = spoonHistoryRefresher;
}
public boolean isSafeModeChecked()
{
return wSafeMode.getSelection();
}
public EngineMetaInterface getMeta() {
return transMeta;
}
/**
* @param transMeta the transMeta to set
*/
public void setTransMeta(TransMeta transMeta)
{
this.transMeta = transMeta;
}
public boolean canBeClosed()
{
return !running;
}
public Object getManagedObject()
{
return transMeta;
}
public boolean hasContentChanged()
{
return false;
}
public int showChangedWarning()
{
// show running error.
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(Messages.getString("Spoon.Message.Warning.PromptExitWhenRunTransformation"));// There is a running transformation. Do you want to stop it and quit Spoon?
mb.setText(Messages.getString("System.Warning")); //Warning
int answer = mb.open();
if (answer==SWT.NO) return SWT.CANCEL;
return answer;
}
public boolean applyChanges()
{
return true;
}
/**
* @return the lastTransDebugMeta
*/
public TransDebugMeta getLastTransDebugMeta() {
return lastTransDebugMeta;
}
public void showLastPreviewResults() {
if (lastTransDebugMeta==null || lastTransDebugMeta.getStepDebugMetaMap().isEmpty()) return;
List<String> stepnames = new ArrayList<String>();
List<RowMetaInterface> rowMetas = new ArrayList<RowMetaInterface>();
List<List<Object[]>> rowBuffers = new ArrayList<List<Object[]>>();
// Assemble the buffers etc in the old style...
for (StepMeta stepMeta : lastTransDebugMeta.getStepDebugMetaMap().keySet() ) {
StepDebugMeta stepDebugMeta = lastTransDebugMeta.getStepDebugMetaMap().get(stepMeta);
stepnames.add(stepMeta.getName());
rowMetas.add(stepDebugMeta.getRowBufferMeta());
rowBuffers.add(stepDebugMeta.getRowBuffer());
}
EnterPreviewRowsDialog dialog = new EnterPreviewRowsDialog(shell, SWT.NONE, stepnames, rowMetas, rowBuffers);
dialog.open();
}
}
|
package Algorithms.Implementation;
import java.util.Scanner;
public class DayOfProgrammer {
static String solve(int year){
int feb=28, day;
String s="";
if (year==1918) {
s= "26.09."+year;
} else if (year<1918) {
if (year%4==0) {
feb=29;
}
day=256-(215+feb);
s= day+".09."+year;
} else if (year>=1919) {
if (year%400==0 || (year%4==0 && year%100!=0)) {
feb=29;
}
day=256-(215+feb);
s= day+".09."+year;
}
return s;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int year = in.nextInt();
in.close();
String result = solve(year);
System.out.println(result);
}
}
|
package com.team4153;
import com.team4153.commands.DriveWithJoystick;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
private static Joystick joystick;
private static Button triggerButton;
public OI() {
joystick = new Joystick(RobotMap.JOYSTICK_PORT);
triggerButton = new JoystickButton(joystick, RobotMap.JSBUTTON_TRIGGER);
// triggerButton.whenPressed(new DriveWithJoystick());
}
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// Another type of button you can create is a DigitalIOButton, which is
// a button or switch hooked up to the cypress module. These are useful if
// you want to build a customized operator interface.
// Button button = new DigitalIOButton(1);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
public static Joystick getJoystick() {
return joystick;
}
public static Button getTriggerButton() {
return triggerButton;
}
}
|
package org.voltdb.iv2;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltcore.zk.BabySitter;
import org.voltcore.zk.LeaderElector;
import org.voltcore.zk.ZKUtil;
import org.voltdb.*;
import org.voltdb.TheHashinator.HashinatorType;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.sysprocs.saverestore.SnapshotUtil.SnapshotResponseHandler;
import com.google.common.collect.ImmutableMap;
/**
* LeaderAppointer handles centralized appointment of partition leaders across
* the partition. This is primarily so that the leaders can be evenly
* distributed throughout the cluster, reducing bottlenecks (at least at
* startup). As a side-effect, this service also controls the initial startup
* of the cluster, blocking operation until each partition has a k-safe set of
* replicas, each partition has a leader, and the MPI has started.
*/
public class LeaderAppointer implements Promotable
{
private static final VoltLogger tmLog = new VoltLogger("TM");
private enum AppointerState {
INIT, // Initial start state, used to inhibit ZK callback actions
CLUSTER_START, // indicates that we're doing the initial cluster startup
DONE // indicates normal running conditions, including repair
}
private final HostMessenger m_hostMessenger;
private final ZooKeeper m_zk;
// This should only be accessed through getInitialPartitionCount() on cluster startup.
private final int m_initialPartitionCount;
private final Map<Integer, BabySitter> m_partitionWatchers;
private final LeaderCache m_iv2appointees;
private final LeaderCache m_iv2masters;
private final Map<Integer, PartitionCallback> m_callbacks;
private final int m_kfactor;
private final JSONObject m_topo;
private final MpInitiator m_MPI;
private final AtomicReference<AppointerState> m_state =
new AtomicReference<AppointerState>(AppointerState.INIT);
private CountDownLatch m_startupLatch = null;
private final boolean m_partitionDetectionEnabled;
private boolean m_partitionDetected = false;
private boolean m_usingCommandLog = false;
private final AtomicBoolean m_replayComplete = new AtomicBoolean(false);
// Provide a single single-threaded executor service to all the BabySitters for each partition.
// This will guarantee that the ordering of events generated by ZooKeeper is preserved in the
// handling of callbacks in LeaderAppointer.
private final ExecutorService m_es =
CoreUtils.getCachedSingleThreadExecutor("LeaderAppointer-Babysitters", 15000);
private final SnapshotSchedule m_partSnapshotSchedule;
private final SnapshotResponseHandler m_snapshotHandler =
new SnapshotResponseHandler() {
@Override
public void handleResponse(ClientResponse resp)
{
if (resp == null) {
VoltDB.crashLocalVoltDB("Received a null response to a snapshot initiation request. " +
"This should be impossible.", true, null);
}
else if (resp.getStatus() != ClientResponse.SUCCESS) {
tmLog.info("Failed to complete partition detection snapshot, status: " + resp.getStatus() +
", reason: " + resp.getStatusString());
tmLog.info("Retrying partition detection snapshot...");
SnapshotUtil.requestSnapshot(0L,
m_partSnapshotSchedule.getPath(),
m_partSnapshotSchedule.getPrefix() + System.currentTimeMillis(),
true, SnapshotFormat.NATIVE, null, m_snapshotHandler,
true);
}
else if (!SnapshotUtil.didSnapshotRequestSucceed(resp.getResults())) {
VoltDB.crashGlobalVoltDB("Unable to complete partition detection snapshot: " +
resp.getResults()[0], false, null);
}
else {
VoltDB.crashGlobalVoltDB("Partition detection snapshot completed. Shutting down.",
false, null);
}
}
};
private class PartitionCallback extends BabySitter.Callback
{
final int m_partitionId;
final Set<Long> m_replicas;
long m_currentLeader;
/** Constructor used when we know (or think we know) who the leader for this partition is */
PartitionCallback(int partitionId, long currentLeader)
{
this(partitionId);
// Try to be clever for repair. Create ourselves with the current leader set to
// whatever is in the LeaderCache, and claim that replica exists, then let the
// first run() call fix the world.
m_currentLeader = currentLeader;
m_replicas.add(currentLeader);
}
/** Constructor used at startup when there is no leader */
PartitionCallback(int partitionId)
{
m_partitionId = partitionId;
// A bit of a hack, but we should never end up with an HSID as Long.MAX_VALUE
m_currentLeader = Long.MAX_VALUE;
m_replicas = new HashSet<Long>();
}
@Override
public void run(List<String> children)
{
List<Long> updatedHSIds = VoltZK.childrenToReplicaHSIds(children);
// compute previously unseen HSId set in the callback list
Set<Long> newHSIds = new HashSet<Long>(updatedHSIds);
newHSIds.removeAll(m_replicas);
tmLog.debug("Newly seen replicas: " + CoreUtils.hsIdCollectionToString(newHSIds));
// compute previously seen but now vanished from the callback list HSId set
Set<Long> missingHSIds = new HashSet<Long>(m_replicas);
missingHSIds.removeAll(updatedHSIds);
tmLog.debug("Newly dead replicas: " + CoreUtils.hsIdCollectionToString(missingHSIds));
tmLog.debug("Handling babysitter callback for partition " + m_partitionId + ": children: " +
CoreUtils.hsIdCollectionToString(updatedHSIds));
if (m_state.get() == AppointerState.CLUSTER_START) {
// We can't yet tolerate a host failure during startup. Crash it all
if (missingHSIds.size() > 0) {
VoltDB.crashGlobalVoltDB("Node failure detected during startup.", false, null);
}
// ENG-3166: Eventually we would like to get rid of the extra replicas beyond k_factor,
// but for now we just look to see how many replicas of this partition we actually expect
// and gate leader assignment on that many copies showing up.
int replicaCount = m_kfactor + 1;
JSONArray parts;
try {
parts = m_topo.getJSONArray("partitions");
for (int p = 0; p < parts.length(); p++) {
JSONObject aPartition = parts.getJSONObject(p);
int pid = aPartition.getInt("partition_id");
if (pid == m_partitionId) {
replicaCount = aPartition.getJSONArray("replicas").length();
}
}
} catch (JSONException e) {
// Ignore and just assume the normal number of replicas
}
if (children.size() == replicaCount) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
else {
tmLog.info("Waiting on " + ((m_kfactor + 1) - children.size()) + " more nodes " +
"for k-safety before startup");
}
}
else {
Set<Integer> hostsOnRing = new HashSet<Integer>();
// Check for k-safety
if (!isClusterKSafe(hostsOnRing)) {
VoltDB.crashGlobalVoltDB("Some partitions have no replicas. Cluster has become unviable.",
false, null);
}
// Check if replay has completed
if (m_replayComplete.get() == false) {
VoltDB.crashGlobalVoltDB("Detected node failure during command log replay. Cluster will shut down.",
false, null);
}
// Check to see if there's been a possible network partition and we're not already handling it
if (m_partitionDetectionEnabled && !m_partitionDetected) {
doPartitionDetectionActivities(hostsOnRing);
}
// If we survived the above gauntlet of fail, appoint a new leader for this partition.
if (missingHSIds.contains(m_currentLeader)) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
// If this partition doesn't have a leader yet, and we have new replicas added,
// elect a leader.
if (m_currentLeader == Long.MAX_VALUE && !updatedHSIds.isEmpty()) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
}
m_replicas.clear();
m_replicas.addAll(updatedHSIds);
}
}
/* We'll use this callback purely for startup so we can discover when all
* the leaders we have appointed have completed their promotions and
* published themselves to Zookeeper */
LeaderCache.Callback m_masterCallback = new LeaderCache.Callback()
{
@Override
public void run(ImmutableMap<Integer, Long> cache) {
Set<Long> currentLeaders = new HashSet<Long>(cache.values());
tmLog.debug("Updated leaders: " + currentLeaders);
if (m_state.get() == AppointerState.CLUSTER_START) {
try {
if (currentLeaders.size() == getInitialPartitionCount()) {
tmLog.debug("Leader appointment complete, promoting MPI and unblocking.");
m_state.set(AppointerState.DONE);
m_MPI.acceptPromotion();
m_startupLatch.countDown();
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count", true, e);
}
}
}
};
Watcher m_partitionCallback = new Watcher() {
@Override
public void process(WatchedEvent event)
{
m_es.submit(new Runnable() {
@Override
public void run()
{
try {
List<String> children = m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
tmLog.info("Noticed partition change " + children + ", " +
"currenctly watching " + m_partitionWatchers.keySet());
for (String child : children) {
int pid = LeaderElector.getPartitionFromElectionDir(child);
if (!m_partitionWatchers.containsKey(pid) && pid != MpInitiator.MP_INIT_PID) {
watchPartition(pid, m_es, false);
}
}
tmLog.info("Done " + m_partitionWatchers.keySet());
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Cannot read leader initiator directory", false, e);
}
}
});
}
};
public LeaderAppointer(HostMessenger hm, int numberOfPartitions,
int kfactor, boolean partitionDetectionEnabled,
SnapshotSchedule partitionSnapshotSchedule,
boolean usingCommandLog,
JSONObject topology, MpInitiator mpi)
{
m_hostMessenger = hm;
m_zk = hm.getZK();
m_kfactor = kfactor;
m_topo = topology;
m_MPI = mpi;
m_initialPartitionCount = numberOfPartitions;
m_callbacks = new HashMap<Integer, PartitionCallback>();
m_partitionWatchers = new HashMap<Integer, BabySitter>();
m_iv2appointees = new LeaderCache(m_zk, VoltZK.iv2appointees);
m_iv2masters = new LeaderCache(m_zk, VoltZK.iv2masters, m_masterCallback);
m_partitionDetectionEnabled = partitionDetectionEnabled;
m_partSnapshotSchedule = partitionSnapshotSchedule;
m_usingCommandLog = usingCommandLog;
}
@Override
public void acceptPromotion() throws InterruptedException, ExecutionException, KeeperException
{
// Crank up the leader caches. Use blocking startup so that we'll have valid point-in-time caches later.
m_iv2appointees.start(true);
m_iv2masters.start(true);
ImmutableMap<Integer, Long> appointees = m_iv2appointees.pointInTimeCache();
// Figure out what conditions we assumed leadership under.
if (appointees.size() == 0)
{
tmLog.debug("LeaderAppointer in startup");
m_state.set(AppointerState.CLUSTER_START);
}
else if (m_state.get() == AppointerState.INIT) {
ImmutableMap<Integer, Long> masters = m_iv2masters.pointInTimeCache();
try {
if ((appointees.size() < getInitialPartitionCount()) ||
(masters.size() < getInitialPartitionCount()) ||
(appointees.size() != masters.size())) {
// If we are promoted and the appointees or masters set is partial, the previous appointer failed
// during startup (at least for now, until we add remove a partition on the fly).
VoltDB.crashGlobalVoltDB("Detected failure during startup, unable to start", false, null);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count", true, e);
}
}
else {
tmLog.debug("LeaderAppointer in repair");
m_state.set(AppointerState.DONE);
}
if (m_state.get() == AppointerState.CLUSTER_START) {
// Need to block the return of acceptPromotion until after the MPI is promoted. Wait for this latch
// to countdown after appointing all the partition leaders. The
// LeaderCache callback will count it down once it has seen all the
// appointed leaders publish themselves as the actual leaders.
m_startupLatch = new CountDownLatch(1);
writeKnownLiveNodes(new HashSet<Integer>(m_hostMessenger.getLiveHostIds()));
// Theoretically, the whole try/catch block below can be removed because the leader
// appointer now watches the parent dir for any new partitions. It doesn't have to
// create the partition dirs all at once, it can pick them up one by one as they are
// created. But I'm too afraid to remove this block just before the release,
// so leaving it here till later. - ning
try {
final int initialPartitionCount = getInitialPartitionCount();
for (int i = 0; i < initialPartitionCount; i++) {
LeaderElector.createRootIfNotExist(m_zk,
LeaderElector.electionDirForPartition(i));
watchPartition(i, m_es, true);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count on startup", true, e);
}
m_startupLatch.await();
m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
}
else {
// If we're taking over for a failed LeaderAppointer, we know when
// we get here that every partition had a leader at some point in
// time. We'll seed each of the PartitionCallbacks for each
// partition with the HSID of the last published leader. The
// blocking startup of the BabySitter watching that partition will
// call our callback, get the current full set of replicas, and
// appoint a new leader if the seeded one has actually failed
Map<Integer, Long> masters = m_iv2masters.pointInTimeCache();
tmLog.info("LeaderAppointer repairing with master set: " + CoreUtils.hsIdValueMapToString(masters));
for (Entry<Integer, Long> master : masters.entrySet()) {
int partId = master.getKey();
String dir = LeaderElector.electionDirForPartition(partId);
m_callbacks.put(partId, new PartitionCallback(partId, master.getValue()));
Pair<BabySitter, List<String>> sitterstuff =
BabySitter.blockingFactory(m_zk, dir, m_callbacks.get(partId), m_es);
m_partitionWatchers.put(partId, sitterstuff.getFirst());
}
// just go ahead and promote our MPI
m_MPI.acceptPromotion();
}
}
/**
* Watch the partition ZK dir in the leader appointer.
*
* This should be called on the elected leader appointer only. m_callbacks and
* m_partitionWatchers are only accessed on initialization, promotion,
* or elastic add node.
*
* @param pid The partition ID
* @param es The executor service to use to construct the baby sitter
* @param shouldBlock Whether or not to wait for the initial read of children
* @throws KeeperException
* @throws InterruptedException
* @throws ExecutionException
*/
void watchPartition(int pid, ExecutorService es, boolean shouldBlock)
throws InterruptedException, ExecutionException
{
String dir = LeaderElector.electionDirForPartition(pid);
m_callbacks.put(pid, new PartitionCallback(pid));
BabySitter babySitter;
if (shouldBlock) {
babySitter = BabySitter.blockingFactory(m_zk, dir, m_callbacks.get(pid), es).getFirst();
} else {
babySitter = BabySitter.nonblockingFactory(m_zk, dir, m_callbacks.get(pid), es);
}
m_partitionWatchers.put(pid, babySitter);
}
private long assignLeader(int partitionId, List<Long> children)
{
// We used masterHostId = -1 as a way to force the leader choice to be
// the first replica in the list, if we don't have some other mechanism
// which has successfully overridden it.
int masterHostId = -1;
if (m_state.get() == AppointerState.CLUSTER_START) {
try {
// find master in topo
JSONArray parts = m_topo.getJSONArray("partitions");
for (int p = 0; p < parts.length(); p++) {
JSONObject aPartition = parts.getJSONObject(p);
int pid = aPartition.getInt("partition_id");
if (pid == partitionId) {
masterHostId = aPartition.getInt("master");
}
}
}
catch (JSONException jse) {
tmLog.error("Failed to find master for partition " + partitionId + ", defaulting to 0");
jse.printStackTrace();
masterHostId = -1; // stupid default
}
}
else {
// For now, if we're appointing a new leader as a result of a
// failure, just pick the first replica in the children list.
// Could eventually do something more complex here to try to keep a
// semi-balance, but it's unclear that this has much utility until
// we add rebalancing on rejoin as well.
masterHostId = -1;
}
long masterHSId = children.get(0);
for (Long child : children) {
if (CoreUtils.getHostIdFromHSId(child) == masterHostId) {
masterHSId = child;
break;
}
}
tmLog.info("Appointing HSId " + CoreUtils.hsIdToString(masterHSId) + " as leader for partition " +
partitionId);
try {
m_iv2appointees.put(partitionId, masterHSId);
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to appoint new master for partition " + partitionId, true, e);
}
return masterHSId;
}
private void writeKnownLiveNodes(Set<Integer> liveNodes)
{
try {
if (m_zk.exists(VoltZK.lastKnownLiveNodes, null) == null)
{
// VoltZK.createPersistentZKNodes should have done this
m_zk.create(VoltZK.lastKnownLiveNodes, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("liveNodes").array();
for (Integer node : liveNodes) {
stringer.value(node);
}
stringer.endArray();
stringer.endObject();
JSONObject obj = new JSONObject(stringer.toString());
tmLog.debug("Writing live nodes to ZK: " + obj.toString(4));
m_zk.setData(VoltZK.lastKnownLiveNodes, obj.toString(4).getBytes("UTF-8"), -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to update known live nodes at ZK path: " +
VoltZK.lastKnownLiveNodes, true, e);
}
}
private Set<Integer> readPriorKnownLiveNodes()
{
Set<Integer> nodes = new HashSet<Integer>();
try {
byte[] data = m_zk.getData(VoltZK.lastKnownLiveNodes, false, null);
String jsonString = new String(data, "UTF-8");
tmLog.debug("Read prior known live nodes: " + jsonString);
JSONObject jsObj = new JSONObject(jsonString);
JSONArray jsonNodes = jsObj.getJSONArray("liveNodes");
for (int ii = 0; ii < jsonNodes.length(); ii++) {
nodes.add(jsonNodes.getInt(ii));
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read prior known live nodes at ZK path: " +
VoltZK.lastKnownLiveNodes, true, e);
}
return nodes;
}
/**
* Given a set of the known host IDs before a fault, and the known host IDs in the
* post-fault cluster, determine whether or not we think a network partition may have happened.
* NOTE: this assumes that we have already done the k-safety validation for every partition and already failed
* if we weren't a viable cluster.
* ALSO NOTE: not private so it may be unit-tested.
*/
static boolean makePPDDecision(Set<Integer> previousHosts, Set<Integer> currentHosts)
{
// Real partition detection stuff would go here
// find the lowest hostId between the still-alive hosts and the
// failed hosts. Which set contains the lowest hostId?
int blessedHostId = Integer.MAX_VALUE;
boolean blessedHostIdInFailedSet = true;
// This should be all the pre-partition hosts IDs. Any new host IDs
// (say, if this was triggered by rejoin), will be greater than any surviving
// host ID, so don't worry about including it in this search.
for (Integer hostId : previousHosts) {
if (hostId < blessedHostId) {
blessedHostId = hostId;
}
}
for (Integer hostId : currentHosts) {
if (hostId.equals(blessedHostId)) {
blessedHostId = hostId;
blessedHostIdInFailedSet = false;
}
}
// Evaluate PPD triggers.
boolean partitionDetectionTriggered = false;
// Exact 50-50 splits. The set with the lowest survivor host doesn't trigger PPD
// If the blessed host is in the failure set, this set is not blessed.
if (currentHosts.size() * 2 == previousHosts.size()) {
if (blessedHostIdInFailedSet) {
tmLog.info("Partition detection triggered for 50/50 cluster failure. " +
"This survivor set is shutting down.");
partitionDetectionTriggered = true;
}
else {
tmLog.info("Partition detected for 50/50 failure. " +
"This survivor set is continuing execution.");
}
}
// A strict, viable minority is always a partition.
if (currentHosts.size() * 2 < previousHosts.size()) {
tmLog.info("Partition detection triggered. " +
"This minority survivor set is shutting down.");
partitionDetectionTriggered = true;
}
return partitionDetectionTriggered;
}
private void doPartitionDetectionActivities(Set<Integer> currentNodes)
{
// We should never re-enter here once we've decided we're partitioned and doomed
assert(!m_partitionDetected);
Set<Integer> currentHosts = new HashSet<Integer>(currentNodes);
Set<Integer> previousHosts = readPriorKnownLiveNodes();
boolean partitionDetectionTriggered = makePPDDecision(previousHosts, currentHosts);
if (partitionDetectionTriggered) {
m_partitionDetected = true;
if (m_usingCommandLog) {
// Just shut down immediately
VoltDB.crashGlobalVoltDB("Use of command logging detected, no additional database snapshot will " +
"be generated. Please use the 'recover' action to restore the database if necessary.",
false, null);
}
else {
SnapshotUtil.requestSnapshot(0L,
m_partSnapshotSchedule.getPath(),
m_partSnapshotSchedule.getPrefix() + System.currentTimeMillis(),
true, SnapshotFormat.NATIVE, null, m_snapshotHandler,
true);
}
}
// If the cluster host set has changed, then write the new set to ZK
// NOTE: we don't want to update the known live nodes if we've decided that our subcluster is
// dying, otherwise a poorly timed subsequent failure might reverse this decision. Any future promoted
// LeaderAppointer should make their partition detection decision based on the pre-partition cluster state.
else if (!currentHosts.equals(previousHosts)) {
writeKnownLiveNodes(currentNodes);
}
}
private boolean isClusterKSafe(Set<Integer> hostsOnRing)
{
boolean retval = true;
List<String> partitionDirs = null;
try {
partitionDirs = m_zk.getChildren(VoltZK.leaders_initiators, null);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read partitions from ZK", true, e);
}
//Don't fetch the values serially do it asynchronously
Queue<ZKUtil.ByteArrayCallback> dataCallbacks = new ArrayDeque<ZKUtil.ByteArrayCallback>();
Queue<ZKUtil.ChildrenCallback> childrenCallbacks = new ArrayDeque<ZKUtil.ChildrenCallback>();
for (String partitionDir : partitionDirs) {
String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
try {
ZKUtil.ByteArrayCallback callback = new ZKUtil.ByteArrayCallback();
m_zk.getData(dir, false, callback, null);
dataCallbacks.offer(callback);
ZKUtil.ChildrenCallback childrenCallback = new ZKUtil.ChildrenCallback();
m_zk.getChildren(dir, false, childrenCallback, null);
childrenCallbacks.offer(childrenCallback);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
}
}
for (String partitionDir : partitionDirs) {
int pid = LeaderElector.getPartitionFromElectionDir(partitionDir);
if (pid == MpInitiator.MP_INIT_PID) continue;
String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
try {
// The data of the partition dir indicates whether the partition has finished
// initializing or not. If not, the replicas may still be in the process of
// adding themselves to the dir. So don't check for k-safety if that's the case.
byte[] partitionState = dataCallbacks.poll().getData();
boolean isInitializing = false;
if (partitionState != null && partitionState.length == 1) {
isInitializing = partitionState[0] == LeaderElector.INITIALIZING;
}
List<String> replicas = childrenCallbacks.poll().getChildren();
final boolean partitionNotOnHashRing = partitionNotOnHashRing(pid);
if (!isInitializing && replicas.isEmpty()) {
//These partitions can fail, just cleanup and remove the partition from the system
if (partitionNotOnHashRing) {
removeAndCleanupPartition(pid);
continue;
}
tmLog.fatal("K-Safety violation: No replicas found for partition: " + pid);
retval = false;
} else if (!partitionNotOnHashRing) {
//Record host ids for all partitions that are on the ring
//so they are considered for partition detection
for (String replica : replicas) {
final String split[] = replica.split("/");
final long hsId = Long.valueOf(split[split.length - 1].split("_")[0]);
final int hostId = CoreUtils.getHostIdFromHSId(hsId);
hostsOnRing.add(hostId);
}
}
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
}
}
return retval;
}
private void removeAndCleanupPartition(int pid) {
tmLog.info("Removing and cleanup up partition info for partition " + pid);
BabySitter sitter = m_partitionWatchers.remove(pid);
if (sitter != null) {
sitter.shutdown();
}
m_callbacks.remove(pid);
try {
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.iv2masters, String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.iv2appointees, String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.leaders_initiators, "partition_" + String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
} catch (Exception e) {
tmLog.error("Error removing partition info", e);
}
}
private boolean partitionNotOnHashRing(int pid) {
if (TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY) return false;
return TheHashinator.getRanges(pid).isEmpty();
}
/**
* Gets the initial cluster partition count on startup. This can only be called during
* initialization. Calling this after initialization throws, because the partition count may
* not reflect the actual partition count in the cluster.
*
* @return
*/
private int getInitialPartitionCount() throws IllegalAccessException
{
AppointerState currentState = m_state.get();
if (currentState != AppointerState.INIT && currentState != AppointerState.CLUSTER_START) {
throw new IllegalAccessException("Getting cached partition count after cluster " +
"startup");
}
return m_initialPartitionCount;
}
public void onReplayCompletion()
{
m_replayComplete.set(true);
}
public void shutdown()
{
try {
m_iv2appointees.shutdown();
m_iv2masters.shutdown();
for (BabySitter watcher : m_partitionWatchers.values()) {
watcher.shutdown();
}
}
catch (Exception e) {
// don't care, we're going down
}
}
}
|
package StevenDimDoors.mod_pocketDim;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import StevenDimDoors.mod_pocketDim.helpers.dimHelper;
import StevenDimDoors.mod_pocketDim.items.ItemRiftBlade;
import StevenDimDoors.mod_pocketDim.world.pocketProvider;
import cpw.mods.fml.common.IWorldGenerator;
public class RiftGenerator implements IWorldGenerator
{
public static final int MAX_GATEWAY_GENERATION_CHANCE = 10000;
public static final int MAX_CLUSTER_GENERATION_CHANCE = 10000;
private static final int CLUSTER_GROWTH_CHANCE = 80;
private static final int MAX_CLUSTER_GROWTH_CHANCE = 100;
private static final int MIN_RIFT_Y = 21;
private static final int MAX_RIFT_Y = 250;
private static final int CHUNK_LENGTH = 16;
private static final int GATEWAY_RADIUS = 4;
private static DDProperties properties = null;
public RiftGenerator()
{
if (properties == null)
properties = DDProperties.instance();
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
//Don't generate rifts or gateways if the rift generation flag is disabled,
//the current world is a pocket dimension, or the world is remote.
if (!properties.WorldRiftGenerationEnabled || world.provider instanceof pocketProvider || world.isRemote)
{
return;
}
int x, y, z;
int blockID;
LinkData link;
//Randomly decide whether to place a cluster of rifts here
if (random.nextInt(MAX_CLUSTER_GENERATION_CHANCE) < properties.ClusterGenerationChance)
{
link = null;
do
{
//Pick a random point on the surface of the chunk
x = chunkX * CHUNK_LENGTH - random.nextInt(CHUNK_LENGTH);
z = chunkZ * CHUNK_LENGTH - random.nextInt(CHUNK_LENGTH);
y = world.getHeightValue(x, z);
//If the point is within the acceptable altitude range and the block above is empty, then place a rift
if (y >= MIN_RIFT_Y && y <= MAX_RIFT_Y && world.isAirBlock(x, y + 1, z))
{
//Create a link. If this is the first time, create a dungeon pocket and create a two-way link.
//Otherwise, create a one-way link and connect to the destination of the first link.
if (link == null)
{
link = new LinkData(world.provider.dimensionId, 0, x, y + 1, z, x, y + 1, z, true, random.nextInt(4));
link = dimHelper.instance.createPocket(link, true, true);
}
else
{
link = dimHelper.instance.createLink(link.locDimID, link.destDimID, x, y + 1, z, link.destXCoord, link.destYCoord, link.destZCoord);
}
}
}
//Randomly decide whether to repeat the process and add another rift to the cluster
while (random.nextInt(MAX_CLUSTER_GROWTH_CHANCE) < CLUSTER_GROWTH_CHANCE);
}
//Randomly decide whether to place a Rift Gateway here.
//This only happens if a rift cluster was NOT generated.
else if (random.nextInt(MAX_GATEWAY_GENERATION_CHANCE) < properties.GatewayGenerationChance)
{
//Pick a random point on the surface of the chunk
x = chunkX * CHUNK_LENGTH - random.nextInt(CHUNK_LENGTH);
z = chunkZ * CHUNK_LENGTH - random.nextInt(CHUNK_LENGTH);
y = world.getHeightValue(x, z);
//Check if the point is within the acceptable altitude range, the block above that point is empty,
//and at least one of the two blocks under that point are opaque
if (y >= MIN_RIFT_Y && y <= MAX_RIFT_Y && world.isAirBlock(x, y + 1, z) &&
world.isBlockOpaqueCube(x, y - 2, z) || world.isBlockOpaqueCube(x, y - 1, z))
{
//Create a two-way link between the upper block of the gateway and a pocket dimension
//That pocket dimension is where we'll start a dungeon!
link = new LinkData(world.provider.dimensionId, 0, x, y + 1, z, x, y + 1, z, true, random.nextInt(4));
link = dimHelper.instance.createPocket(link, true, true);
//If the current dimension isn't Limbo, build a Rift Gateway out of Stone Bricks
if (world.provider.dimensionId != properties.LimboDimensionID)
{
blockID = Block.stoneBrick.blockID;
//Replace some of the ground around the gateway with bricks
for (int xc = -GATEWAY_RADIUS; xc <= GATEWAY_RADIUS; xc++)
{
for (int zc= -GATEWAY_RADIUS; zc <= GATEWAY_RADIUS; zc++)
{
//Check that the block is supported by an opaque block.
//This prevents us from building over a cliff, on the peak of a mountain,
//or the surface of the ocean or a frozen lake.
if (world.isBlockOpaqueCube(x + xc, y - 2, z + zc))
{
//Randomly choose whether to place bricks or not. The math is designed so that the
//chances of placing a block decrease as we get farther from the gateway's center.
if (Math.abs(xc) + Math.abs(zc) < random.nextInt(2) + 3)
{
//Place Stone Bricks
world.setBlock(x + xc, y - 1, z + zc, blockID,0,2);
}
else if (Math.abs(xc) + Math.abs(zc) < random.nextInt(3) + 3)
{
//Place Cracked Stone Bricks
world.setBlock(x + xc, y - 1, z + zc, blockID, 2, 2);
}
}
}
}
//Use Chiseled Stone Bricks to top off the pillars around the door
world.setBlock(x, y + 2, z + 1, blockID, 3, 2);
world.setBlock(x, y + 2, z - 1, blockID, 3, 2);
}
else
{
//Build the gateway out of Unraveled Fabric. Since nearly all the blocks in Limbo are of
//that type, there is no point replacing the ground. Just build the tops of the columns here.
blockID = properties.LimboBlockID;
world.setBlock(x, y + 2, z + 1, blockID, 0, 2);
world.setBlock(x, y + 2, z - 1, blockID, 0, 2);
}
//Place the shiny transient door into a dungeon
ItemRiftBlade.placeDoorBlock(world, x, y + 1, z, 0, mod_pocketDim.transientDoor);
//Build the columns around the door
world.setBlock(x, y + 1, z - 1, blockID, 0, 2);
world.setBlock(x, y + 1, z + 1, blockID, 0, 2);
world.setBlock(x, y, z - 1, blockID, 0, 2);
world.setBlock(x, y, z + 1, blockID, 0, 2);
}
}
}
}
|
package org.voltdb.utils;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.TimeZone;
import org.voltcore.utils.Pair;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.common.Constants;
import org.voltdb.types.TimestampType;
import au.com.bytecode.opencsv_voltpatches.CSVWriter;
/*
* Utility methods for work with VoltTables.
*/
public class VoltTableUtil {
/*
* Ugly hack to allow SnapshotConverter which
* shares this code with the server to specify it's own time zone.
* You wouldn't want to convert to anything other then GMT if you want to get the data back into
* Volt using the CSV loader because that relies on the server to coerce the date string
* and the server only supports GMT.
*/
public static TimeZone tz = VoltDB.VOLT_TIMEZONE;
// VoltTable status code to indicate null dependency table. Joining SPI replies to fragment
// task messages with this.
public static byte NULL_DEPENDENCY_STATUS = -1;
private static final ThreadLocal<SimpleDateFormat> m_sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
public SimpleDateFormat initialValue() {
SimpleDateFormat sdf = new SimpleDateFormat(
Constants.ODBC_DATE_FORMAT_STRING);
sdf.setTimeZone(tz);
return sdf;
}
};
public static void toCSVWriter(CSVWriter csv, VoltTable vt, List<VoltType> columnTypes) throws IOException {
final SimpleDateFormat sdf = m_sdf.get();
String[] fields = new String[vt.getColumnCount()];
while (vt.advanceRow()) {
for (int ii = 0; ii < vt.getColumnCount(); ii++) {
final VoltType type = columnTypes.get(ii);
if (type == VoltType.BIGINT
|| type == VoltType.INTEGER
|| type == VoltType.SMALLINT
|| type == VoltType.TINYINT) {
final long value = vt.getLong(ii);
if (vt.wasNull()) {
fields[ii] = Constants.CSV_NULL;
} else {
fields[ii] = Long.toString(value);
}
} else if (type == VoltType.FLOAT) {
final double value = vt.getDouble(ii);
if (vt.wasNull()) {
fields[ii] = Constants.CSV_NULL;
} else {
fields[ii] = Double.toString(value);
}
} else if (type == VoltType.DECIMAL) {
final BigDecimal bd = vt.getDecimalAsBigDecimal(ii);
if (vt.wasNull()) {
fields[ii] = Constants.CSV_NULL;
} else {
fields[ii] = bd.toString();
}
} else if (type == VoltType.STRING) {
final String str = vt.getString(ii);
if (vt.wasNull()) {
fields[ii] = Constants.CSV_NULL;
} else {
fields[ii] = str;
}
} else if (type == VoltType.TIMESTAMP) {
final TimestampType timestamp = vt.getTimestampAsTimestamp(ii);
if (vt.wasNull()) {
fields[ii] = Constants.CSV_NULL;
} else {
fields[ii] = sdf.format(timestamp.asApproximateJavaDate());
fields[ii] += String.format("%03d", timestamp.getUSec());
}
} else if (type == VoltType.VARBINARY) {
byte bytes[] = vt.getVarbinary(ii);
if (vt.wasNull()) {
fields[ii] = Constants.CSV_NULL;
} else {
fields[ii] = Encoder.hexEncode(bytes);
}
}
}
csv.writeNext(fields);
}
csv.flush();
}
public static Pair<Integer,byte[]> toCSV(
VoltTable vt,
char delimiter,
char fullDelimiters[],
int lastNumCharacters) throws IOException {
ArrayList<VoltType> types = new ArrayList<VoltType>(vt.getColumnCount());
for (int ii = 0; ii < vt.getColumnCount(); ii++) {
types.add(vt.getColumnType(ii));
}
return toCSV(vt, types, delimiter, fullDelimiters, lastNumCharacters);
}
/*
* Returns the number of characters generated and the csv data
* in UTF-8 encoding.
*/
public static Pair<Integer,byte[]> toCSV(
VoltTable vt,
ArrayList<VoltType> columns,
char delimiter,
char fullDelimiters[],
int lastNumCharacters) throws IOException {
StringWriter sw = new StringWriter((int)(lastNumCharacters * 1.2));
CSVWriter writer;
if (fullDelimiters != null) {
writer = new CSVWriter(sw,
fullDelimiters[0], fullDelimiters[1], fullDelimiters[2], String.valueOf(fullDelimiters[3]));
}
else if (delimiter == ',')
// CSV
writer = new CSVWriter(sw, delimiter);
else {
// TSV
writer = CSVWriter.getStrictTSVWriter(sw);
}
toCSVWriter(writer, vt, columns);
String csvString = sw.toString();
return Pair.of(csvString.length(), csvString.getBytes(com.google_voltpatches.common.base.Charsets.UTF_8));
}
/**
* Utility to aggregate a list of tables sharing a schema. Common for
* sysprocs to do this, to aggregate results.
*/
public static VoltTable unionTables(Collection<VoltTable> operands) {
VoltTable result = null;
// Locate the first non-null table to get the schema
for (VoltTable vt : operands) {
if (vt != null) {
VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[vt.getColumnCount()];
for (int ii = 0; ii < vt.getColumnCount(); ii++) {
columns[ii] = new VoltTable.ColumnInfo(vt.getColumnName(ii),
vt.getColumnType(ii));
}
result = new VoltTable(columns);
result.setStatusCode(vt.getStatusCode());
break;
}
}
if (result != null) {
for (VoltTable vt : operands) {
if (vt != null) {
vt.resetRowPosition();
while (vt.advanceRow()) {
result.add(vt);
}
}
}
result.resetRowPosition();
}
return result;
}
/**
* Extract a table's schema.
* @param vt input table with source schema
* @return schema as column info array
*/
public static VoltTable.ColumnInfo[] extractTableSchema(VoltTable vt)
{
VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[vt.getColumnCount()];
for (int ii = 0; ii < vt.getColumnCount(); ii++) {
columns[ii] = new VoltTable.ColumnInfo(vt.getColumnName(ii),
vt.getColumnType(ii));
}
return columns;
}
}
|
package com.jme.math;
/**
* <code>Ray</code> defines a line segment which has an origin and a direction.
* That is, a point and an infinite ray is cast from this point. The ray is
* defined by the following equation: R(t) = origin + t*direction for t >= 0.
* @author Mark Powell
* @version $Id: Ray.java,v 1.13 2005-10-30 15:21:13 Mojomonkey Exp $
*/
public class Ray {
/** The ray's begining point. */
public Vector3f origin;
/** The direction of the ray. */
public Vector3f direction;
protected static final Vector3f tempVa=new Vector3f();
protected static final Vector3f tempVb=new Vector3f();
protected static final Vector3f tempVc=new Vector3f();
protected static final Vector3f tempVd=new Vector3f();
/**
* Constructor instantiates a new <code>Ray</code> object. As default, the
* origin is (0,0,0) and the direction is (0,0,0).
*
*/
public Ray() {
origin = new Vector3f();
direction = new Vector3f();
}
/**
* Constructor instantiates a new <code>Ray</code> object. The origin and
* direction are given.
* @param origin the origin of the ray.
* @param direction the direction the ray travels in.
*/
public Ray(Vector3f origin, Vector3f direction) {
this.origin = origin;
this.direction = direction;
}
/**
* <code>intersect</code> determines if the Ray intersects a triangle.
* @param t the Triangle to test against.
* @return true if the ray collides.
*/
public boolean intersect(Triangle t) {
return intersect(t.get(0), t.get(1), t.get(2));
}
/**
* <code>intersect</code> determines if the Ray intersects a triangle
* defined by the specified points.
*
* @param v0
* first point of the triangle.
* @param v1
* second point of the triangle.
* @param v2
* third point of the triangle.
* @return true if the ray collides.
*/
public boolean intersect(Vector3f v0,Vector3f v1,Vector3f v2){
Vector3f edge1=v1.subtract(v0,tempVa);
Vector3f edge2=v2.subtract(v0,tempVb);
Vector3f pvec=direction.cross(edge2,tempVc);
float det=edge1.dot(pvec);
if (det > -FastMath.FLT_EPSILON && det < FastMath.FLT_EPSILON)
return false;
det=1f/det;
Vector3f tvec=origin.subtract(v0,tempVd);
float u=tvec.dot(pvec) *det;
if (u < 0.0f || u > 1.0f)
return false;
Vector3f qvec=tvec.cross(edge1,tempVc);
float v=direction.dot(qvec) * det;
if (v < 0.0f || v + u > 1.0f)
return false;
return true;
}
/**
* <code>intersectWhere</code> determines if the Ray intersects a triangle. It then
* stores the point of intersection in the given loc vector
* @param t the Triangle to test against.
* @param loc
* storage vector to save the collision point in (if the ray
* collides)
* @return true if the ray collides.
*/
public boolean intersectWhere(Triangle t, Vector3f loc) {
return intersectWhere(t.get(0), t.get(1), t.get(2), loc);
}
/**
* <code>intersectWhere</code> determines if the Ray intersects a triangle
* defined by the specified points and if so it stores the point of
* intersection in the given loc vector.
*
* @param v0
* first point of the triangle.
* @param v1
* second point of the triangle.
* @param v2
* third point of the triangle.
* @param loc
* storage vector to save the collision point in (if the ray
* collides)
* @return true if the ray collides.
*/
public boolean intersectWhere(Vector3f v0, Vector3f v1, Vector3f v2,
Vector3f loc) {
Vector3f edge1 = v1.subtract(v0, tempVa);
Vector3f edge2 = v2.subtract(v0, tempVb);
Vector3f pvec = direction.cross(edge2, tempVc);
float det = edge1.dot(pvec);
if (det > -FastMath.FLT_EPSILON && det < FastMath.FLT_EPSILON)
return false;
det = 1f / det;
Vector3f tvec = origin.subtract(v0, tempVd);
float u = tvec.dot(pvec) * det;
if (u < 0.0 || u > 1.0)
return false;
Vector3f qvec = tvec.cross(edge1, tempVc);
float v = direction.dot(qvec) * det;
if (v < 0.0 || v + u > 1.0)
return false;
float t = edge2.dot(qvec) * det;
loc.set(origin).addLocal(direction.x * t, direction.y * t,
direction.z * t);
return true;
}
/**
* <code>intersectWherePlanar</code> determines if the Ray intersects a
* triangle and if so it stores the point of
* intersection in the given loc vector as t, u, v where t is the distance
* from the origin to the point of intersection and u,v is the intersection
* point in terms of the triangle plane.
*
* @param t the Triangle to test against.
* @param loc
* storage vector to save the collision point in (if the ray
* collides) as t, u, v
* @return true if the ray collides.
*/
public boolean intersectWherePlanar(Triangle t, Vector3f loc) {
return intersectWherePlanar(t.get(0), t.get(1), t.get(2), loc);
}
/**
* <code>intersectWherePlanar</code> determines if the Ray intersects a
* triangle defined by the specified points and if so it stores the point of
* intersection in the given loc vector as t, u, v where t is the distance
* from the origin to the point of intersection and u,v is the intersection
* point in terms of the triangle plane.
*
* @param v0
* first point of the triangle.
* @param v1
* second point of the triangle.
* @param v2
* third point of the triangle.
* @param loc
* storage vector to save the collision point in (if the ray
* collides) as t, u, v
* @return true if the ray collides.
*/
public boolean intersectWherePlanar(Vector3f v0, Vector3f v1, Vector3f v2,
Vector3f loc) {
Vector3f edge1 = v1.subtract(v0, tempVa);
Vector3f edge2 = v2.subtract(v0, tempVb);
Vector3f pvec = direction.cross(edge2, tempVc);
float det = edge1.dot(pvec);
if (det > -FastMath.FLT_EPSILON && det < FastMath.FLT_EPSILON)
return false;
det = 1f / det;
Vector3f tvec = origin.subtract(v0, tempVd);
float u = tvec.dot(pvec) * det;
if (u < 0.0 || u > 1.0)
return false;
Vector3f qvec = tvec.cross(edge1, tempVc);
float v = direction.dot(qvec) * det;
if (v < 0.0 || v + u > 1.0)
return false;
float t = edge2.dot(qvec) * det;
loc.set(t, u, v);
return true;
}
/**
*
* <code>getOrigin</code> retrieves the origin point of the ray.
* @return the origin of the ray.
*/
public Vector3f getOrigin() {
return origin;
}
/**
*
* <code>setOrigin</code> sets the origin of the ray.
* @param origin the origin of the ray.
*/
public void setOrigin(Vector3f origin) {
this.origin = origin;
}
/**
*
* <code>getDirection</code> retrieves the direction vector of the ray.
* @return the direction of the ray.
*/
public Vector3f getDirection() {
return direction;
}
/**
*
* <code>setDirection</code> sets the direction vector of the ray.
* @param direction the direction of the ray.
*/
public void setDirection(Vector3f direction) {
this.direction = direction;
}
}
|
public class IdResponse {
private int id;
public IdResponse(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
import Misc.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class getProfile {
public static void getProfile(HttpServletRequest req, HttpServletResponse resp, Connection connection, String id1, String id2) throws IOException {
try {
String select_sql = "Select * from Connections where (requester_id = ? and target_id = ?) or (requester_id = ? and target_id = ?)";
PreparedStatement stmt = connection.prepareStatement(select_sql);
Long req_id, target_id;
try {
req_id = Long.parseLong(id1);
target_id = Long.parseLong(id2);
stmt.setLong(1, req_id);
stmt.setLong(2, target_id);
stmt.setLong(3, target_id);
stmt.setLong(4, req_id);
}
catch (NumberFormatException e) {
resp.setStatus(Constants.BAD_REQUEST);
return;
}
resp.getWriter().print("Getting Status!\n");
String status = getConnStatus(resp, connection, id1, id2);
resp.getWriter().print("Done!\n");
resp.getWriter().print("Status: " + status);
}
catch (SQLException e) {
resp.setStatus(Constants.INTERNAL_SERVER_ERROR);
resp.getWriter().print(e.getMessage());
}
}
public static String getConnStatus(HttpServletResponse resp, Connection connection, String id1, String id2) throws SQLException, IOException{
resp.getWriter().print("Calling getConStatus with id1: " + id1 + ", id2:" + id2 + "\n");
String select_sql = "Select * from Connections where (requester_id = ? and target_id = ?) or (requester_id = ? and target_id = ?)";
PreparedStatement stmt = connection.prepareStatement(select_sql);
Long req_id, target_id;
try {
req_id = Long.parseLong(id1);
target_id = Long.parseLong(id2);
stmt.setLong(1, req_id);
stmt.setLong(2, target_id);
stmt.setLong(3, target_id);
stmt.setLong(4, req_id);
}
catch (NumberFormatException e) {
resp.setStatus(Constants.BAD_REQUEST);
return "";
}
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return getStatusString(req_id, target_id, rs);
}
return Constants.REL_UNCONNECTED;
}
public static String getStatusString(Long req_id, Long target_id, ResultSet rs) throws SQLException{
Long connReq = rs.getLong(Constants.REQ_ID);
Long connTarget = rs.getLong(Constants.TARGET_ID);
String status = rs.getString(Constants.STATUS);
if (status == Constants.ACCEPTED)
return Constants.REL_ACCEPTED;
if (req_id == connReq) {
if (status == Constants.PENDING)
return Constants.REL_PENDING;
else if (status == Constants.REJECTED)
return Constants.REL_REJECTED;
else
return "";
}
else if (req_id == connTarget){
if (status == Constants.PENDING)
return Constants.REL_AWAITING_YOUR_APPROVAL;
else if (status == Constants.REJECTED)
return Constants.REL_REJECTED_BY_YOU;
else
return "";
}
else
return "";
}
}
|
package ia158;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.motor.EV3MediumRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.robotics.RegulatedMotor;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Main class for the robot controll.
*/
public class Main {
private static long START_SEARCHING_TIME = 3000;
private static long TIME_BEFORE_SHOOT = 1000;
private static String eduroam = "147.251.45.255";
private static String robot = "10.0.1.255";
private static Long lostTargetTime;
private static Long targetingTime;
private static Action lastAction = Action.NONE;
public static void main(String[] args) throws IOException {
// Init
InetAddress group = InetAddress.getByName(robot);
DatagramSocket socket = new DatagramSocket(9999, group);
long start = System.currentTimeMillis();
lostTargetTime = start;
targetingTime = null;
// Motors
RegulatedMotor rightWheels = new EV3LargeRegulatedMotor(MotorPort.A);
RegulatedMotor leftWheels = new EV3LargeRegulatedMotor(MotorPort.B);
RegulatedMotor shoot = new EV3MediumRegulatedMotor(MotorPort.C);
// Run
while (System.currentTimeMillis() < start + 60000) {
// receive packet
byte[] buffer = new byte[1];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Action action = Action.fromByte(buffer[0]);
System.out.println("Action: "+action);
switch (action) {
case RIGHT:
lostTargetTime = null;
targetingTime = null;
if (lastAction.equals(Action.RIGHT)) {
break;
}
// start rotating right
rightWheels.backward();
leftWheels.forward();
lastAction = action;
break;
case LEFT:
lostTargetTime = null;
targetingTime = null;
if (lastAction.equals(Action.LEFT)) {
break;
}
// start rotating left
rightWheels.forward();
leftWheels.backward();
lastAction = action;
break;
case SHOOT:
// stop rotating
rightWheels.stop(true);
leftWheels.stop(true);
lostTargetTime = null;
if (targetingTime == null) {
targetingTime = System.currentTimeMillis();
} else if (System.currentTimeMillis() > targetingTime + TIME_BEFORE_SHOOT) {
shoot.rotate(360, true);
targetingTime = null;
}
lastAction = action;
break;
case NONE:
targetingTime = null;
if (Action.SHOOT.equals(lastAction)) {
if (lostTargetTime != null && System.currentTimeMillis() > lostTargetTime + START_SEARCHING_TIME) {
// start searching
rightWheels.backward();
leftWheels.forward();
lastAction = Action.RIGHT;
lostTargetTime = null;
} else if (lostTargetTime == null) {
lostTargetTime = System.currentTimeMillis();
}
}
break;
}
}
}
}
|
package model;
import java.util.Date;
/**
*
* @author c0687174
*/
public class Bill {
private int bill_id;
private int group_id;
private int user_id;
private String bill_description;
private double bill_amount;
private Date bill_date;
private String bill_type;
public Bill() {
}
public Bill(int bill_id, int group_id, int user_id, String bill_des, double bill_amount, Date bill_date, String bill_type) {
this.bill_id = bill_id;
this.group_id = group_id;
this.user_id = user_id;
this.bill_description = bill_des;
this.bill_amount = bill_amount;
this.bill_date = bill_date;
this.bill_type = bill_type;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getBill_id() {
return bill_id;
}
public void setBill_id(int bill_id) {
this.bill_id = bill_id;
}
public int getGroup_id() {
return group_id;
}
public void setGroup_id(int group_id) {
this.group_id = group_id;
}
public String getBill_description() {
return bill_description;
}
public void setBill_description(String bill_description) {
this.bill_description = bill_description;
}
public double getBill_amount() {
return bill_amount;
}
public void setBill_amount(double bill_amount) {
this.bill_amount = bill_amount;
}
public Date getBill_date() {
return bill_date;
}
public void setBill_date(Date bill_date) {
this.bill_date = bill_date;
}
public String getBill_type() {
return bill_type;
}
public void setBill_type(String bill_type) {
this.bill_type = bill_type;
}
}
|
package scotty;
/**
* Command line interface tokens.
*/
public interface Cli {
String HELP = "help";
String DATABASE = "database";
String TEMPLATE = "template";
String CONTEXT = "context";
String OUTPUT = "output";
}
|
package io.flutter.actions;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import icons.FlutterIcons;
import io.flutter.FlutterBundle;
import io.flutter.FlutterUtils;
import io.flutter.run.daemon.DeviceService;
import io.flutter.run.daemon.FlutterDevice;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
public class DeviceSelectorAction extends ComboBoxAction implements DumbAware {
final private List<AnAction> actions = new ArrayList<>();
private final List<Project> knownProjects = Collections.synchronizedList(new ArrayList<>());
@NotNull
@Override
protected DefaultActionGroup createPopupActionGroup(JComponent button) {
final DefaultActionGroup group = new DefaultActionGroup();
group.addAll(actions);
return group;
}
@Override
protected boolean shouldShowDisabledActions() {
return true;
}
@Override
public void update(final AnActionEvent e) {
// Suppress device actions in all but the toolbars.
final String place = e.getPlace();
if (!Objects.equals(place, ActionPlaces.NAVIGATION_BAR_TOOLBAR) && !Objects.equals(place, ActionPlaces.MAIN_TOOLBAR)) {
e.getPresentation().setVisible(false);
return;
}
// Only show device menu when the device daemon process is running.
final Project project = e.getProject();
if (!isSelectorVisible(project)) {
e.getPresentation().setVisible(false);
return;
}
super.update(e);
if (!knownProjects.contains(project)) {
knownProjects.add(project);
Disposer.register(project, () -> knownProjects.remove(project));
DeviceService.getInstance(project).addListener(() -> update(project, e.getPresentation()));
update(project, e.getPresentation());
}
}
private void update(Project project, Presentation presentation) {
FlutterUtils.invokeAndWait(() -> {
updateVisibility(project, presentation);
updateActions(project, presentation);
});
}
private void updateVisibility(final Project project, final Presentation presentation) {
final boolean visible = isSelectorVisible(project);
presentation.setVisible(visible);
final JComponent button = (JComponent)presentation.getClientProperty("customComponent");
if (button != null) {
button.setVisible(visible);
if (button.getParent() != null) {
button.getParent().doLayout();
}
}
}
private boolean isSelectorVisible(@Nullable Project project) {
return project != null && DeviceService.getInstance(project).getStatus() != DeviceService.State.INACTIVE;
}
private void updateActions(@NotNull Project project, Presentation presentation) {
actions.clear();
final DeviceService service = DeviceService.getInstance(project);
final Collection<FlutterDevice> devices = service.getConnectedDevices();
for (FlutterDevice item : devices) {
actions.add(new SelectDeviceAction(item));
}
if (actions.isEmpty()) {
final boolean isLoading = service.getStatus() == DeviceService.State.LOADING;
final String message = isLoading ? FlutterBundle.message("devicelist.loading") : FlutterBundle.message("devicelist.empty");
actions.add(new NoDevicesAction(message));
}
// Show the 'Open iOS Simulator' action.
if (SystemInfo.isMac) {
boolean simulatorOpen = false;
for (AnAction action : actions) {
if (action instanceof SelectDeviceAction) {
final SelectDeviceAction deviceAction = (SelectDeviceAction)action;
final FlutterDevice device = deviceAction.device;
if (device.isIOS() && device.emulator()) {
simulatorOpen = true;
}
}
}
actions.add(new Separator());
actions.add(new OpenSimulatorAction(!simulatorOpen));
}
final FlutterDevice selectedDevice = service.getSelectedDevice();
for (AnAction action : actions) {
if (action instanceof SelectDeviceAction) {
final SelectDeviceAction deviceAction = (SelectDeviceAction)action;
if (Objects.equals(deviceAction.device, selectedDevice)) {
final Presentation template = action.getTemplatePresentation();
presentation.setIcon(template.getIcon());
presentation.setText(template.getText());
presentation.setEnabled(true);
return;
}
}
}
if (devices.isEmpty()) {
presentation.setText("<no devices>");
} else {
presentation.setText(null);
}
}
// It's not clear if we need TransparentUpdate, but apparently it will make the UI refresh
// the display more often?
private static class NoDevicesAction extends AnAction implements TransparentUpdate {
NoDevicesAction(String message) {
super(message, null, null);
getTemplatePresentation().setEnabled(false);
}
@Override
public void actionPerformed(AnActionEvent e) {
// No-op
}
}
private static class SelectDeviceAction extends AnAction {
@NotNull
private final FlutterDevice device;
SelectDeviceAction(@NotNull FlutterDevice device) {
super(device.deviceName(), null, FlutterIcons.Phone);
this.device = device;
}
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = e.getProject();
final DeviceService service = project == null ? null : DeviceService.getInstance(project);
if (service != null) {
service.setSelectedDevice(device);
}
}
}
}
|
package io.flutter.samples;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.OutputListener;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.projectImport.ProjectOpenProcessor;
import io.flutter.FlutterBundle;
import io.flutter.FlutterUtils;
import io.flutter.module.FlutterModuleBuilder;
import io.flutter.module.FlutterProjectType;
import io.flutter.pub.PubRoot;
import io.flutter.sdk.FlutterCreateAdditionalSettings;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;
public class FlutterSampleManager {
// TODO(pq): remove after testing.
private static final boolean DISABLE_SAMPLES = false;
private static final long SAMPLE_LISTING_PROCESS_TIMEOUT_IN_MS = 30000L;
private static final String SNIPPETS_REMOTE_INDEX_URL = "https://docs.flutter.io/snippets/index.json";
private static final Logger LOG = Logger.getInstance(FlutterSampleManager.class);
@NotNull
private final FlutterSdk sdk;
private List<FlutterSample> flutterSamples;
public FlutterSampleManager(@NotNull FlutterSdk sdk) {
this.sdk = sdk;
}
public List<FlutterSample> getSamples() {
if (DISABLE_SAMPLES) {
return Collections.emptyList();
}
if (flutterSamples != null) {
return flutterSamples;
}
// Set samples to an empty list to:
// 1. ensure we don't call the flutter tool multiple times
// 2. leave things in a sensible default state if an exception occurs
flutterSamples = Collections.emptyList();
final Timer timer = new Timer();
final Task.Backgroundable task = new Task.Backgroundable(null, "Initializing Flutter Sample Listing", true) {
OSProcessHandler process;
public void run(@NotNull ProgressIndicator indicator) {
try {
final File tempDir = Files.createTempDirectory("flutter-samples-index").toFile();
tempDir.deleteOnExit();
final File tempFile = new File(tempDir, "index.json");
try {
final GeneralCommandLine commandLine = sdk.flutterListSamples(tempFile).createGeneralCommandLine(null);
process = new OSProcessHandler(commandLine);
timer.schedule(new TimerTask() {
@Override
public void run() {
LOG.info("Flutter sample listing timed out, process cancelled.");
onCancel();
}
}, SAMPLE_LISTING_PROCESS_TIMEOUT_IN_MS);
process.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull ProcessEvent event) {
timer.cancel();
try {
final byte[] bytes = Files.readAllBytes(tempFile.toPath());
final String content = new String(bytes);
flutterSamples = FlutterSampleManager.readSamples(content);
}
catch (IOException e) {
LOG.warn(e);
}
}
});
process.startNotify();
// TODO(pq): consider something to allow for a retry after some amount of ellapsed time.
}
catch (ExecutionException e) {
LOG.warn(e);
timer.cancel();
}
}
catch (IOException e) {
LOG.warn(e);
timer.cancel();
}
}
@Override
public void onCancel() {
if (process == null) {
return;
}
final Process p = process.getProcess();
try {
if (p.isAlive()) {
p.destroyForcibly();
}
}
catch (Exception e) {
LOG.warn(e);
}
}
};
task.setCancelText("Cancel Flutter Sample List initialization").queue();
task.queue();
return flutterSamples;
}
// Called at project initialization.
public static void initialize(Project project) {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk != null) {
// Trigger a sample listing.
sdk.getSamples();
}
}
public static List<FlutterSample> readSamples(String indexFileContents) {
final List<FlutterSample> samples = new ArrayList<>();
final JsonArray json = new JsonParser().parse(indexFileContents).getAsJsonArray();
for (JsonElement element : json) {
final JsonObject sample = element.getAsJsonObject();
samples.add(new FlutterSample(sample.getAsJsonPrimitive("element").getAsString(),
sample.getAsJsonPrimitive("library").getAsString(),
sample.getAsJsonPrimitive("id").getAsString(),
sample.getAsJsonPrimitive("file").getAsString(),
sample.getAsJsonPrimitive("sourcePath").getAsString(),
sample.getAsJsonPrimitive("description").getAsString()));
}
// Sort by display label.
samples.sort(Comparator.comparing(FlutterSample::getDisplayLabel));
return samples;
}
private static JsonArray readSampleIndex(final URL sampleUrl) throws IOException {
final BufferedInputStream in = new BufferedInputStream(sampleUrl.openStream());
final StringBuilder contents = new StringBuilder();
final byte[] bytes = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(bytes)) != -1) {
contents.append(new String(bytes, 0, bytesRead));
}
return new JsonParser().parse(contents.toString()).getAsJsonArray();
}
private static JsonArray readSampleIndex() {
// Try fetching snippets index remotely, and fall back to local cache.
try {
return readSampleIndex(new URL(SNIPPETS_REMOTE_INDEX_URL));
}
catch (IOException ignored) {
try {
return readSampleIndex(FlutterSampleManager.class.getResource("index.json"));
}
catch (IOException e) {
FlutterUtils.warn(LOG, e);
}
}
return new JsonArray();
}
public static String createSampleProject(@NotNull FlutterSample sample, @NotNull Project project) {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
return "unable to find Flutter SDK";
}
final File projectRoot = new File(ProjectUtil.getBaseDir());
final String projectNamePrefix = deriveValidPackageName(sample.getElement());
final String projectDir = FileUtil.createSequentFileName(projectRoot, projectNamePrefix + "_sample", "");
final File dir = new File(projectRoot, projectDir);
if (!dir.mkdir()) {
return "unable to create project root: " + dir.getPath();
}
final VirtualFile baseDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dir);
if (baseDir == null) {
return "unable to find project root (" + dir.getPath() + ") on refresh";
}
final OutputListener outputListener = new OutputListener() {
@Override
public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
// TODO(pq): consider showing progress in the status line.
}
@Override
public void processTerminated(@NotNull ProcessEvent event) {
// TODO(pq): handle event.getExitCode().
}
};
final PubRoot root =
FlutterModuleBuilder.runFlutterCreateWithProgress(baseDir, sdk, project, outputListener, getCreateSettings(sample));
final ProjectOpenProcessor openProcessor = ProjectOpenProcessor.getImportProvider(baseDir);
if (openProcessor == null) {
return "unable to find a processor to finish opening the project: " + baseDir.getPath();
}
openProcessor.doOpenProject(baseDir, null, true);
return null;
}
private static String deriveValidPackageName(String name) {
return name.split("\\.")[0].toLowerCase();
}
private static FlutterCreateAdditionalSettings getCreateSettings(@NotNull FlutterSample sample) {
return new FlutterCreateAdditionalSettings.Builder()
.setDescription(sample.getElement() + " Sample Project")
.setType(FlutterProjectType.APP)
.setKotlin(false)
.setOrg(FlutterBundle.message("flutter.module.create.settings.org.default_text"))
.setSwift(false)
.setSampleContent(sample)
.setOffline(false)
.build();
}
}
|
package org.apache.commons.lang;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and
* primitive wrapper arrays (like <code>Integer[]</code>).</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code>
* array input. However, an Object array that contains a <code>null</code>
* element may throw an exception. Each method documents its behaviour.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author <a href="mailto:fredrik@westermarck.com">Fredrik Westermarck</a>
* @author Nikolay Metchev
* @author Matthew Hawthorne
* @author Tim O'Brien
* @author Pete Gieser
* @author Gary Gregory
* @author <a href="mailto:equinus100@hotmail.com">Ashwin S</a>
* @since 2.0
* @version $Id: ArrayUtils.java,v 1.36 2004/01/30 01:51:36 ggregory Exp $
*/
public class ArrayUtils {
/**
* An empty immutable <code>Object</code> array.
*/
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/**
* An empty immutable <code>Class</code> array.
*/
public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
/**
* An empty immutable <code>String</code> array.
*/
public static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* An empty immutable <code>long</code> array.
*/
public static final long[] EMPTY_LONG_ARRAY = new long[0];
/**
* An empty immutable <code>Long</code> array.
*/
public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];
/**
* An empty immutable <code>int</code> array.
*/
public static final int[] EMPTY_INT_ARRAY = new int[0];
/**
* An empty immutable <code>Integer</code> array.
*/
public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];
/**
* An empty immutable <code>short</code> array.
*/
public static final short[] EMPTY_SHORT_ARRAY = new short[0];
/**
* An empty immutable <code>Short</code> array.
*/
public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];
/**
* An empty immutable <code>byte</code> array.
*/
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/**
* An empty immutable <code>Byte</code> array.
*/
public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];
/**
* An empty immutable <code>double</code> array.
*/
public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
/**
* An empty immutable <code>Double</code> array.
*/
public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];
/**
* An empty immutable <code>float</code> array.
*/
public static final float[] EMPTY_FLOAT_ARRAY = new float[0];
/**
* An empty immutable <code>Float</code> array.
*/
public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];
/**
* An empty immutable <code>boolean</code> array.
*/
public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];
/**
* An empty immutable <code>Boolean</code> array.
*/
public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];
/**
* An empty immutable <code>char</code> array.
*/
public static final char[] EMPTY_CHAR_ARRAY = new char[0];
/**
* An empty immutable <code>Character</code> array.
*/
public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];
/**
* <p>ArrayUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>ArrayUtils.clone(new int[] {2})</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public ArrayUtils() {
}
// Basic methods handling multi-dimensional arrays
/**
* <p>Outputs an array as a String, treating <code>null</code> as an empty array.</p>
*
* <p>Multi-dimensional arrays are handled correctly, including
* multi-dimensional primitive arrays.</p>
*
* <p>The format is that of Java source code, for example <code>{a,b}</code>.</p>
*
* @param array the array to get a toString for, may be <code>null</code>
* @return a String representation of the array, '{}' if null array input
*/
public static String toString(final Object array) {
return toString(array, "{}");
}
/**
* <p>Outputs an array as a String handling <code>null</code>s.</p>
*
* <p>Multi-dimensional arrays are handled correctly, including
* multi-dimensional primitive arrays.</p>
*
* <p>The format is that of Java source code, for example <code>{a,b}</code>.</p>
*
* @param array the array to get a toString for, may be <code>null</code>
* @param stringIfNull the String to return if the array is <code>null</code>
* @return a String representation of the array
*/
public static String toString(final Object array, final String stringIfNull) {
if (array == null) {
return stringIfNull;
}
return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString();
}
/**
* <p>Get a hashCode for an array handling multi-dimensional arrays correctly.</p>
*
* <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p>
*
* @param array the array to get a hashCode for, may be <code>null</code>
* @return a hashCode for the array, zero if null array input
*/
public static int hashCode(final Object array) {
return new HashCodeBuilder().append(array).toHashCode();
}
/**
* <p>Compares two arrays, using equals(), handling multi-dimensional arrays
* correctly.</p>
*
* <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p>
*
* @param array1 the left hand array to compare, may be <code>null</code>
* @param array2 the right hand array to compare, may be <code>null</code>
* @return <code>true</code> if the arrays are equal
*/
public static boolean isEquals(final Object array1, final Object array2) {
return new EqualsBuilder().append(array1, array2).isEquals();
}
// To map
public static Map toMap(final Object[] array) {
if (array == null) {
return null;
}
final Map map = new HashMap((int) (array.length * 1.5));
for (int i = 0; i < array.length; i++) {
Object object = array[i];
if (object instanceof Map.Entry) {
Map.Entry entry = (Map.Entry) object;
map.put(entry.getKey(), entry.getValue());
} else if (object instanceof Object[]) {
Object[] entry = (Object[]) object;
if (entry.length < 2) {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', has a length less than 2");
}
map.put(entry[0], entry[1]);
} else {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', is neither of type Map.Entry nor an Array");
}
}
return map;
}
// Clone
/**
* <p>Shallow clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>The objects in the array are not cloned, thus there is no special
* handling for multi-dimensional arrays.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to shallow clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static Object[] clone(final Object[] array) {
if (array == null) {
return null;
}
return (Object[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static long[] clone(final long[] array) {
if (array == null) {
return null;
}
return (long[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static int[] clone(int[] array) {
if (array == null) {
return null;
}
return (int[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static short[] clone(final short[] array) {
if (array == null) {
return null;
}
return (short[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static char[] clone(final char[] array) {
if (array == null) {
return null;
}
return (char[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static byte[] clone(final byte[] array) {
if (array == null) {
return null;
}
return (byte[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static double[] clone(final double[] array) {
if (array == null) {
return null;
}
return (double[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static float[] clone(final float[] array) {
if (array == null) {
return null;
}
return (float[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, <code>null</code> if <code>null</code> input
*/
public static boolean[] clone(final boolean[] array) {
if (array == null) {
return null;
}
return (boolean[]) array.clone();
}
// Subarrays
/**
* <p>Produces a new array containing the elements between
* the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* <p>The component type of the subarray is always the same as
* that of the input array. Thus, if the input is an array of type
* <code>Date</code>, the following usage is envisaged:</p>
*
* <pre>
* Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);
* </pre>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static Object[] subarray(Object[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
Class type = array.getClass().getComponentType();
if (newSize <= 0) {
return (Object[]) Array.newInstance(type, 0);
}
Object[] subarray = (Object[]) Array.newInstance(type, newSize);
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>long</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_LONG_ARRAY;
}
long[] subarray = new long[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>int</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_INT_ARRAY;
}
int[] subarray = new int[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>short</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_SHORT_ARRAY;
}
short[] subarray = new short[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>char</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_CHAR_ARRAY;
}
char[] subarray = new char[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>byte</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_BYTE_ARRAY;
}
byte[] subarray = new byte[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>double</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_DOUBLE_ARRAY;
}
double[] subarray = new double[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>float</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_FLOAT_ARRAY;
}
float[] subarray = new float[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
/**
* <p>Produces a new <code>boolean</code> array containing the elements
* between the start and end indices.</p>
*
* <p>The start index is inclusive, the end index exclusive.
* Null array input produces null output.</p>
*
* @param array the array
* @param startIndexInclusive the starting index. Undervalue (<0)
* is promoted to 0, overvalue (>array.length) results
* in an empty array.
* @param endIndexExclusive elements up to endIndex-1 are present in the
* returned subarray. Undervalue (< startIndex) produces
* empty array, overvalue (>array.length) is demoted to
* array length.
* @return a new array containing the elements between
* the start and end indices.
*/
public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
}
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return EMPTY_BOOLEAN_ARRAY;
}
boolean[] subarray = new boolean[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
// Is same length
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final Object[] array1, final Object[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final long[] array1, final long[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final int[] array1, final int[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final short[] array1, final short[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final char[] array1, final char[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final byte[] array1, final byte[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final double[] array1, final double[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final float[] array1, final float[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
public static boolean isSameType(final Object array1, final Object array2) {
if (array1 == null || array2 == null) {
throw new IllegalArgumentException("The Array must not be null");
}
return array1.getClass().getName().equals(array2.getClass().getName());
}
// Reverse
/**
* <p>Reverses the order of the given array.</p>
*
* <p>There is no special handling for multi-dimensional arrays.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final Object[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
Object tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final long[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
long tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final short[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
short tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final char[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
char tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final byte[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final double[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
double tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final float[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
float tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* <p>Reverses the order of the given array.</p>
*
* <p>This method does nothing if <code>null</code> array input.</p>
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(final boolean[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
boolean tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
// IndexOf search
// Object IndexOf
/**
* <p>Find the index of the given object in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @return the index of the object within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final Object[] array, final Object objectToFind) {
return indexOf(array, objectToFind, 0);
}
/**
* <p>Find the index of the given object in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return <code>-1</code>.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the index to start searching at
* @return the index of the object within the array starting at the index,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
/**
* <p>Find the last index of the given object within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @return the last index of the object within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final Object[] array, final Object objectToFind) {
return lastIndexOf(array, objectToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given object in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return <code>-1</code>. A startIndex larger than
* the array length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the start index to travers backwards from
* @return the last index of the object within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
if (objectToFind == null) {
for (int i = startIndex; i >= 0; i
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i >= 0; i
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
/**
* <p>Checks if the object is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param objectToFind the object to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final Object[] array, final Object objectToFind) {
return (indexOf(array, objectToFind) != -1);
}
// long IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final long[] array, final long valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final long[] array, final long valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final long[] array, final long valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final long[] array, final long valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
// int IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final int[] array, final int valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final int[] array, final int valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final int[] array, final int valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final int[] array, final int valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
// short IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final short[] array, final short valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final short[] array, final short valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final short[] array, final short valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final short[] array, final short valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
// byte IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final byte[] array, final byte valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final byte[] array, final byte valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final byte[] array, final byte valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
// double IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final double[] array, final double valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value within a given tolerance in the array.
* This method will return the index of the first value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param tolerance tolerance of the search
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {
return indexOf(array, valueToFind, 0, tolerance);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final double[] array, final double valueToFind, int startIndex) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the index of the given value in the array starting at the given index.
* This method will return the index of the first value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @param tolerance tolerance of the search
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final double[] array, final double valueToFind, int startIndex, double tolerance) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
double min = valueToFind - tolerance;
double max = valueToFind + tolerance;
for (int i = startIndex; i < array.length; i++) {
if (array[i] >= min && array[i] <= max) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final double[] array, final double valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value within a given tolerance in the array.
* This method will return the index of the last value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param tolerance tolerance of the search
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value in the array starting at the given index.
* This method will return the index of the last value which falls between the region
* defined by valueToFind - tolerance and valueToFind + tolerance.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @param tolerance search for value within plus/minus this amount
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, double tolerance) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
double min = valueToFind - tolerance;
double max = valueToFind + tolerance;
for (int i = startIndex; i >= 0; i
if (array[i] >= min && array[i] <= max) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final double[] array, final double valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
/**
* <p>Checks if a value falling within the given tolerance is in the
* given array. If the array contains a value within the inclusive range
* defined by (value - tolerance) to (value + tolerance).</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array
* is passed in.</p>
*
* @param array the array to search
* @param valueToFind the value to find
* @param tolerance the array contains the tolerance of the search
* @return true if value falling within tolerance is in array
*/
public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {
return (indexOf(array, valueToFind, 0, tolerance) != -1);
}
// float IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final float[] array, final float valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final float[] array, final float valueToFind, int startIndex) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final float[] array, final float valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final float[] array, final float valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
// boolean IndexOf
/**
* <p>Find the index of the given value in the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final boolean[] array, final boolean valueToFind) {
return indexOf(array, valueToFind, 0);
}
/**
* <p>Find the index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.</p>
*
* @param array the array to search through for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the index to start searching at
* @return the index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Find the last index of the given value within the array.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param valueToFind the object to find
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {
return lastIndexOf(array, valueToFind, Integer.MAX_VALUE);
}
/**
* <p>Find the last index of the given value in the array starting at the given index.</p>
*
* <p>This method returns <code>-1</code> if <code>null</code> array input.</p>
*
* <p>A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.</p>
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index to travers backwards from
* @return the last index of the value within the array,
* <code>-1</code> if not found or <code>null</code> array input
*/
public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
if (ArrayUtils.isEmpty(array)) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
for (int i = startIndex; i >= 0; i
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
/**
* <p>Checks if the value is in the given array.</p>
*
* <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p>
*
* @param array the array to search through
* @param valueToFind the value to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(final boolean[] array, final boolean valueToFind) {
return (indexOf(array, valueToFind) != -1);
}
// Primitive/Object array converters
// Long array converters
/**
* <p>Converts an array of object Longs to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Long</code> array, may be <code>null</code>
* @return a <code>long</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static long[] toPrimitive(final Long[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_LONG_ARRAY;
}
final long[] result = new long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].longValue();
}
return result;
}
/**
* <p>Converts an array of object Long to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Long</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return a <code>long</code> array, <code>null</code> if null array input
*/
public static long[] toPrimitive(final Long[] array, final long valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_LONG_ARRAY;
}
final long[] result = new long[array.length];
for (int i = 0; i < array.length; i++) {
Long b = array[i];
result[i] = (b == null ? valueForNull : b.longValue());
}
return result;
}
/**
* <p>Converts an array of primitive longs to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>long</code> array
* @return a <code>Long</code> array, <code>null</code> if null array input
*/
public static Long[] toObject(final long[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_LONG_OBJECT_ARRAY;
}
final Long[] result = new Long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Long(array[i]);
}
return result;
}
// Int array converters
/**
* <p>Converts an array of object Integers to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Integer</code> array, may be <code>null</code>
* @return an <code>int</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static int[] toPrimitive(final Integer[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_INT_ARRAY;
}
final int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].intValue();
}
return result;
}
/**
* <p>Converts an array of object Integer to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Integer</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return an <code>int</code> array, <code>null</code> if null array input
*/
public static int[] toPrimitive(final Integer[] array, final int valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_INT_ARRAY;
}
final int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
Integer b = array[i];
result[i] = (b == null ? valueForNull : b.intValue());
}
return result;
}
/**
* <p>Converts an array of primitive ints to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array an <code>int</code> array
* @return an <code>Integer</code> array, <code>null</code> if null array input
*/
public static Integer[] toObject(final int[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_INTEGER_OBJECT_ARRAY;
}
final Integer[] result = new Integer[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Integer(array[i]);
}
return result;
}
// Short array converters
/**
* <p>Converts an array of object Shorts to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Short</code> array, may be <code>null</code>
* @return a <code>byte</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static short[] toPrimitive(final Short[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_SHORT_ARRAY;
}
final short[] result = new short[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].shortValue();
}
return result;
}
/**
* <p>Converts an array of object Short to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Short</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return a <code>byte</code> array, <code>null</code> if null array input
*/
public static short[] toPrimitive(final Short[] array, final short valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_SHORT_ARRAY;
}
final short[] result = new short[array.length];
for (int i = 0; i < array.length; i++) {
Short b = array[i];
result[i] = (b == null ? valueForNull : b.shortValue());
}
return result;
}
/**
* <p>Converts an array of primitive shorts to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>short</code> array
* @return a <code>Short</code> array, <code>null</code> if null array input
*/
public static Short[] toObject(final short[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_SHORT_OBJECT_ARRAY;
}
final Short[] result = new Short[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Short(array[i]);
}
return result;
}
// Byte array converters
/**
* <p>Converts an array of object Bytes to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Byte</code> array, may be <code>null</code>
* @return a <code>byte</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static byte[] toPrimitive(final Byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BYTE_ARRAY;
}
final byte[] result = new byte[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].byteValue();
}
return result;
}
/**
* <p>Converts an array of object Bytes to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Byte</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return a <code>byte</code> array, <code>null</code> if null array input
*/
public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BYTE_ARRAY;
}
final byte[] result = new byte[array.length];
for (int i = 0; i < array.length; i++) {
Byte b = array[i];
result[i] = (b == null ? valueForNull : b.byteValue());
}
return result;
}
/**
* <p>Converts an array of primitive bytes to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>byte</code> array
* @return a <code>Byte</code> array, <code>null</code> if null array input
*/
public static Byte[] toObject(final byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BYTE_OBJECT_ARRAY;
}
final Byte[] result = new Byte[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Byte(array[i]);
}
return result;
}
// Double array converters
/**
* <p>Converts an array of object Doubles to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Double</code> array, may be <code>null</code>
* @return a <code>double</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static double[] toPrimitive(final Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].doubleValue();
}
return result;
}
/**
* <p>Converts an array of object Doubles to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Double</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return a <code>double</code> array, <code>null</code> if null array input
*/
public static double[] toPrimitive(final Double[] array, final double valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
Double b = array[i];
result[i] = (b == null ? valueForNull : b.doubleValue());
}
return result;
}
/**
* <p>Converts an array of primitive doubles to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>double</code> array
* @return a <code>Double</code> array, <code>null</code> if null array input
*/
public static Double[] toObject(final double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_OBJECT_ARRAY;
}
final Double[] result = new Double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Double(array[i]);
}
return result;
}
// Float array converters
/**
* <p>Converts an array of object Floats to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Float</code> array, may be <code>null</code>
* @return a <code>float</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static float[] toPrimitive(final Float[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_FLOAT_ARRAY;
}
final float[] result = new float[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].floatValue();
}
return result;
}
/**
* <p>Converts an array of object Floats to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Float</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return a <code>float</code> array, <code>null</code> if null array input
*/
public static float[] toPrimitive(final Float[] array, final float valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_FLOAT_ARRAY;
}
final float[] result = new float[array.length];
for (int i = 0; i < array.length; i++) {
Float b = array[i];
result[i] = (b == null ? valueForNull : b.floatValue());
}
return result;
}
/**
* <p>Converts an array of primitive floats to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>float</code> array
* @return a <code>Float</code> array, <code>null</code> if null array input
*/
public static Float[] toObject(final float[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_FLOAT_OBJECT_ARRAY;
}
final Float[] result = new Float[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Float(array[i]);
}
return result;
}
// Boolean array converters
/**
* <p>Converts an array of object Booleans to primitives.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Boolean</code> array, may be <code>null</code>
* @return a <code>boolean</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static boolean[] toPrimitive(final Boolean[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BOOLEAN_ARRAY;
}
final boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].booleanValue();
}
return result;
}
/**
* <p>Converts an array of object Booleans to primitives handling <code>null</code>.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>Boolean</code> array, may be <code>null</code>
* @param valueForNull the value to insert if <code>null</code> found
* @return a <code>boolean</code> array, <code>null</code> if null array input
*/
public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BOOLEAN_ARRAY;
}
final boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
Boolean b = array[i];
result[i] = (b == null ? valueForNull : b.booleanValue());
}
return result;
}
/**
* <p>Converts an array of primitive booleans to objects.</p>
*
* <p>This method returns <code>null</code> if <code>null</code> array input.</p>
*
* @param array a <code>boolean</code> array
* @return a <code>Boolean</code> array, <code>null</code> if null array input
*/
public static Boolean[] toObject(final boolean[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BOOLEAN_OBJECT_ARRAY;
}
final Boolean[] result = new Boolean[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE);
}
return result;
}
/**
* <p>Checks if an array of Objects is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final Object[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive longs is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final long[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive ints is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final int[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive shorts is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final short[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive chars is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final char[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive bytes is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final byte[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive doubles is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final double[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive floats is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final float[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Checks if an array of primitive booleans is empty or <code>null</code>.</p>
*
* @param array the array to test
* @return <code>true</code> if the array is empty or <code>null</code>
* @since 2.1
*/
public static boolean isEmpty(final boolean[] array) {
if (array == null || array.length == 0) {
return true;
}
return false;
}
/**
* <p>Joins the elements of the provided arrays into a single new array.</p>
* <p>The new array contains all of the element of the first array followed
* by all of the elements from the second array.</p>
*
* <pre>
* ArrayUtils.join(null, null) = null
* ArrayUtils.join(array1, null) = array1
* ArrayUtils.join(null, array2) = array2
* ArrayUtils.join([], []) = []
* ArrayUtils.join([null], [null]) = [null, null]
* ArrayUtils.join(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
* </pre>
*
* @param array1 the first array of values to join together, may be null
* @param array2 the second array of values to join together, may be null
* @return The new joined array, <code>null</code> if null array inputs.
* The type of the joined array is the type of the first array.
* @since 2.1
*/
public static Object[] join(Object[] array1, Object[] array2) {
if (array1 == null) {
return array2;
} else if (array2 == null) {
return array1;
} else {
Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length
+ array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
}
/**
* <p>Adds the element to the end of the array.</p>
*
* <p>The new array contains the same elements of the input
* array plus the given element in the last position. The component type of
* the new array is the same as that of the input array.</p>
*
* <p>If the input array is <code>null</code>, a new one element array is returned
* whose component type is the same as the element.</p>
*
* <pre>
* ArrayUtils.add(null, null) = [null]
* ArrayUtils.add(null, "a") = ["a"]
* ArrayUtils.add(["a"], null) = ["a", null]
* ArrayUtils.add(["a"], "b") = ["a", "b"]
* ArrayUtils.add(["a", "b"], "c") = ["a", "b", "c"]
* </pre>
*
* @param array the array to "add" the element to, may be <code>null</code>
* @param element the object to add
* @return A new array containing the existing elements and the new element
* @since 2.1
*/
public static Object[] add(Object[] array, Object element) {
Object joinedArray;
int elementPos;
if (array != null) {
joinedArray = Array.newInstance(array.getClass().getComponentType(), array.length + 1);
System.arraycopy(array, 0, joinedArray, 0, array.length);
elementPos = array.length;
} else {
// null input array, use the element type
joinedArray = Array.newInstance(element != null ? element.getClass() : Object.class, 1);
elementPos = 0;
}
Array.set(joinedArray, elementPos, element);
return (Object[]) joinedArray;
}
/**
* <p>Inserts the specified element at the specified position in the array.
* Shifts the element currently at that position (if any) and any subsequent
* elements to the right (adds one to their indices).</p>
*
* <p>This method returns a new array with the same elements of the input
* array plus the given element on the specified position. The component
* type of the returned array is always the same as that of the input
* array.</p>
*
* <p>If the input array is <code>null</code>, a new one element array is returned
* whose component type is the same as the element.</p>
*
* <pre>
* ArrayUtils.add(null, 0, null) = [null]
* ArrayUtils.add(null, 0, "a") = ["a"]
* ArrayUtils.add(["a"], 1, null) = ["a", null]
* ArrayUtils.add(["a"], 1, "b") = ["a", "b"]
* ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"]
* </pre>
*
* @param array the array to add the element to, may be <code>null</code>
* @param index the position of the new object
* @param element the object to add
* @return A new array containing the existing elements and the new element
* @throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index > array.length).
*/
public static Object[] add(final Object[] array, final int index, final Object element) {
if (array == null) {
if (index != 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
}
Object joinedArray = Array.newInstance(element != null ? element.getClass() : Object.class, 1);
Array.set(joinedArray, 0, element);
return (Object[]) joinedArray;
}
int length = array.length;
if (index > length || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
}
Object result = Array.newInstance(array.getClass().getComponentType(), length + 1);
System.arraycopy(array, 0, result, 0, index);
Array.set(result, index, element);
if (index < length) {
System.arraycopy(array, index, result, index + 1, length - index);
}
return (Object[]) result;
}
}
|
package cs437.som.demo;
import cs437.som.SOMBuilderConfigPanel;
import cs437.som.SelfOrganizingMap;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
/**
* A form for running multiple EdgeDetectors and comparing their output to a
* reference image.
*/
public class EdgeDetectionRunner implements PropertyChangeListener {
private static Pattern positiveInteger = Pattern.compile("[1-9]\\d*");
private JRadioButton exhaustiveRadioButton;
private JRadioButton sampledRadioButton;
private JTextField iterationCountInput;
private SOMBuilderConfigPanel mapConfig;
private JComboBox<String> outputImageCmb;
private JButton trainButton;
private JButton runButton;
private JPanel edgeDetectionRunnerForm;
private JLabel referenceLabel;
private JLabel outputLabel;
private JFrame holdingFrame;
private BufferedImage inputImage = null;
private BufferedImage outputImage = null;
private BufferedImage normalImage = null;
private EdgeDetector ed = null;
/**
* Create a new EdgeDetectionRunner.
*/
public EdgeDetectionRunner() {
createUIComponents();
validateForm();
createHoldingFrame();
}
/**
* Create an enclosing JFrame and show it.
*/
private void createHoldingFrame() {
holdingFrame = new JFrame();
holdingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
holdingFrame.getContentPane().add(edgeDetectionRunnerForm);
holdingFrame.pack();
holdingFrame.setVisible(true);
}
/**
* Set up listeners on the training style radio buttons.
*/
private void setupTrainingRadios() {
iterationCountInput.setEnabled(false);
exhaustiveRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (exhaustiveRadioButton.isSelected()) {
iterationCountInput.setEnabled(false);
trainButton.setEnabled(true);
}
}
});
sampledRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (sampledRadioButton.isSelected()) {
iterationCountInput.setEnabled(true);
}
}
});
}
/**
* Validate the current input and (en-/)disable controls appropriately.
*/
private void validateForm() {
boolean mapValid = mapConfig.isValid();
boolean iterationCountValid = validateIterationCount();
boolean exhaustiveSelected = exhaustiveRadioButton.isSelected();
boolean eneableTrain = mapValid &&
(exhaustiveSelected || iterationCountValid);
trainButton.setEnabled(eneableTrain);
runButton.setEnabled(ed != null);
}
/**
* Validate the contents of {@code iterationCountInput} and update
* its background color appropriately.
*
* @return True if the contents are valid; false otherwise.
*/
private boolean validateIterationCount() {
boolean iterationCountIsValid = false;
if (positiveInteger.matcher(iterationCountInput.getText()).matches()) {
iterationCountInput.setBackground(Color.WHITE);
iterationCountIsValid = true;
} else {
iterationCountInput.setBackground(Color.RED);
}
return iterationCountIsValid;
}
/**
* Create and train an EdgeDetector based on the form input.
*/
private void trainMap() {
if (exhaustiveRadioButton.isSelected()) {
createExhaustiveSOM();
} else {
createSampleSOM();
}
runButton.setEnabled(true);
}
/**
* Create and train an EdgeDetector that uses sampled input.
*/
private void createSampleSOM() {
int iterations = Integer.parseInt(iterationCountInput.getText());
SelfOrganizingMap som = mapConfig.createSOM(9, iterations);
ed = EdgeDetector.trainRandomlyFromMap(som, iterations);
}
/**
* Create and train an EdgeDetector that uses exhaustive training.
*/
private void createExhaustiveSOM() {
int iterations = EdgeDetector.threeRaiseNine;
SelfOrganizingMap som = mapConfig.createSOM(9, iterations);
ed = EdgeDetector.trainExhaustivelyFromMap(som);
}
/**
* Run the currently trained map and display the results.
*/
private void runMap() {
try {
inputImage = ImageIO.read(new File("image.jpg"));
} catch (IOException ignored) { }
outputImage = ed.runOnImage(inputImage);
normalImage = ed.normalizeImage(outputImage);
displayImages();
holdingFrame.pack();
}
/**
* Display the input and output images, if they exist.
*/
private void displayImages() {
if (inputImage != null) {
referenceLabel.setIcon(new ImageIcon(inputImage));
displayOutputImage();
}
}
/**
* Display the output images, if they exist.
*/
private void displayOutputImage() {
if (outputImage == null || normalImage == null) {
return;
}
if (outputImageCmb.getSelectedIndex() == 0) {
outputLabel.setIcon(new ImageIcon(outputImage));
} else {
outputLabel.setIcon(new ImageIcon(normalImage));
}
}
@Override
public String toString() {
return "EdgeDetectionRunner";
}
/**
* Custom creation and initialization of UI components.
*/
private void createUIComponents() {
mapConfig.addPropertyChangeListener(this);
setupTrainingRadios();
iterationCountInput.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
validateIterationCount();
}
});
trainButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { trainMap(); }
});
runButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { runMap(); }
});
outputImageCmb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { displayOutputImage(); }
});
}
/**
* Listen for validity changes on the SOMBuilderConfigPanel.
*
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getOldValue() != evt.getNewValue()) {
validateForm();
}
}
public static void main(String[] args) {
new EdgeDetectionRunner();
}
}
|
package org.relique.jdbc.csv;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.Hashtable;
/**
* This class implements the Connection interface for the CsvJdbc driver.
*
* @author Jonathan Ackerman
* @author Sander Brienen
* @author Michael Maraya
* @version $Id: CsvConnection.java,v 1.6 2002/08/24 23:37:30 mmaraya Exp $
*/
public class CsvConnection implements Connection {
/** Directory where the CSV files to use are located */
private String path;
/** File extension to use */
private String extension = CsvDriver.DEFAULT_EXTENSION;
/** Field separator to use */
private char separator = CsvDriver.DEFAULT_SEPARATOR;
/** Should headers be suppressed */
private boolean suppressHeaders = CsvDriver.DEFAULT_SUPPRESS;
/** Collection of all created Statements */
private Vector statements = new Vector();
/** Stores whether this Connection is closed or not */
private boolean closed;
/**
* Creates a new CsvConnection that takes the supplied path
* @param path directory where the CSV files are located
*/
protected CsvConnection(String path) {
// validate argument(s)
if(path == null || path.length() == 0) {
throw new IllegalArgumentException(
"'path' argument may not be empty or null");
}
this.path = path;
}
/**
* Creates a new CsvConnection that takes the supplied path and properties
* @param path directory where the CSV files are located
* @param info set of properties containing custom options
*/
protected CsvConnection(String path, Properties info) {
this(path);
// check for properties
if(info != null) {
// set the file extension to be used
if(info.getProperty(CsvDriver.FILE_EXTENSION) != null) {
extension = info.getProperty(CsvDriver.FILE_EXTENSION);
}
// set the separator character to be used
if(info.getProperty(CsvDriver.SEPARATOR) != null) {
separator = info.getProperty(CsvDriver.SEPARATOR).charAt(0);
}
// set the header suppression flag
if(info.getProperty(CsvDriver.SUPPRESS_HEADERS) != null) {
suppressHeaders = Boolean.valueOf(info.getProperty(
CsvDriver.SUPPRESS_HEADERS)).booleanValue();
}
}
}
/**
* Creates a <code>Statement</code> object for sending
* SQL statements to the database.
* SQL statements without parameters are normally
* executed using <code>Statement</code> objects. If the same SQL statement
* is executed many times, it may be more efficient to use a
* <code>PreparedStatement</code> object.
* <P>
* Result sets created using the returned <code>Statement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @return a new default <code>Statement</code> object
* @exception SQLException if a database access error occurs
*/
public Statement createStatement() throws SQLException {
CsvStatement statement = new CsvStatement(this);
statements.add(statement);
return statement;
}
/**
* Creates a <code>PreparedStatement</code> object for sending
* parameterized SQL statements to the database.
* <P>
* A SQL statement with or without IN parameters can be
* pre-compiled and stored in a <code>PreparedStatement</code> object. This
* object can then be used to efficiently execute this statement
* multiple times.
*
* <P><B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain <code>SQLException</code> objects.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @return a new default <code>PreparedStatement</code> object containing the
* pre-compiled SQL statement
* @exception SQLException if a database access error occurs
*/
public PreparedStatement prepareStatement(String sql) throws SQLException {
throw new UnsupportedOperationException(
"Connection.prepareStatement(String) unsupported");
}
/**
* Creates a <code>CallableStatement</code> object for calling
* database stored procedures.
* The <code>CallableStatement</code> object provides
* methods for setting up its IN and OUT parameters, and
* methods for executing the call to a stored procedure.
*
* <P><B>Note:</B> This method is optimized for handling stored
* procedure call statements. Some drivers may send the call
* statement to the database when the method <code>prepareCall</code>
* is done; others
* may wait until the <code>CallableStatement</code> object
* is executed. This has no
* direct effect on users; however, it does affect which method
* throws certain SQLExceptions.
* <P>
* Result sets created using the returned <code>CallableStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?'
* parameter placeholders. Typically this statement is a JDBC
* function call escape string.
* @return a new default <code>CallableStatement</code> object containing the
* pre-compiled SQL statement
* @exception SQLException if a database access error occurs
*/
public CallableStatement prepareCall(String sql) throws SQLException {
throw new UnsupportedOperationException(
"Connection.prepareCall(String) unsupported");
}
/**
* Converts the given SQL statement into the system's native SQL grammar.
* A driver may convert the JDBC SQL grammar into its system's
* native SQL grammar prior to sending it. This method returns the
* native form of the statement that the driver would have sent.
*
* @param sql an SQL statement that may contain one or more '?'
* parameter placeholders
* @return the native form of this statement
* @exception SQLException if a database access error occurs
*/
public String nativeSQL(String sql) throws SQLException {
throw new UnsupportedOperationException(
"Connection.nativeSQL(String) unsupported");
}
/**
* Sets this connection's auto-commit mode to the given state.
* If a connection is in auto-commit mode, then all its SQL
* statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped into
* transactions that are terminated by a call to either
* the method <code>commit</code> or the method <code>rollback</code>.
* By default, new connections are in auto-commit
* mode.
* <P>
* The commit occurs when the statement completes or the next
* execute occurs, whichever comes first. In the case of
* statements returning a <code>ResultSet</code> object,
* the statement completes when the last row of the
* <code>ResultSet</code> object has been retrieved or the
* <code>ResultSet</code> object has been closed. In advanced cases, a
* single statement may return multiple results as well as output
* parameter values. In these cases, the commit occurs when all results and
* output parameter values have been retrieved.
* <P>
* <B>NOTE:</B> If this method is called during a transaction, the
* transaction is committed.
*
* @param autoCommit <code>true</code> to enable auto-commit mode;
* <code>false</code> to disable it
* @exception SQLException if a database access error occurs
* @see #getAutoCommit
*/
public void setAutoCommit(boolean autoCommit) throws SQLException {
throw new UnsupportedOperationException(
"Connection.setAutoCommit(boolean) unsupported");
}
/**
* Retrieves the current auto-commit mode for this <code>Connection</code>
* object.
*
* @return the current state of this <code>Connection</code> object's
* auto-commit mode
* @exception SQLException if a database access error occurs
* @see #setAutoCommit
*/
public boolean getAutoCommit() throws SQLException {
throw new UnsupportedOperationException(
"Connection.getAutoCommit() unsupported");
}
/**
* Makes all changes made since the previous
* commit/rollback permanent and releases any database locks
* currently held by this <code>Connection</code> object.
* This method should be
* used only when auto-commit mode has been disabled.
*
* @exception SQLException if a database access error occurs or this
* <code>Connection</code> object is in auto-commit mode
* @see #setAutoCommit
*/
public void commit() throws SQLException {
throw new UnsupportedOperationException(
"Connection.commit() unsupported");
}
/**
* Undoes all changes made in the current transaction
* and releases any database locks currently held
* by this <code>Connection</code> object. This method should be
* used only when auto-commit mode has been disabled.
*
* @exception SQLException if a database access error occurs or this
* <code>Connection</code> object is in auto-commit mode
* @see #setAutoCommit
*/
public void rollback() throws SQLException {
throw new UnsupportedOperationException(
"Connection.rollback() unsupported");
}
/**
* Releases this <code>Connection</code> object's database and JDBC
* resources immediately instead of waiting for them to be automatically
* released.
* <P>
* Calling the method <code>close</code> on a <code>Connection</code>
* object that is already closed is a no-op.
* <P>
* <B>Note:</B> A <code>Connection</code> object is automatically
* closed when it is garbage collected. Certain fatal errors also
* close a <code>Connection</code> object.
*
* @exception SQLException if a database access error occurs
*/
public void close() throws SQLException {
// close all created statements
for(Enumeration i = statements.elements(); i.hasMoreElements(); ) {
CsvStatement statement = (CsvStatement)i.nextElement();
statement.close();
}
// set this Connection as closed
closed = true;
}
/**
* Retrieves whether this <code>Connection</code> object has been
* closed. A connection is closed if the method <code>close</code>
* has been called on it or if certain fatal errors have occurred.
* This method is guaranteed to return <code>true</code> only when
* it is called after the method <code>Connection.close</code> has
* been called.
* <P>
* This method generally cannot be called to determine whether a
* connection to a database is valid or invalid. A typical client
* can determine that a connection is invalid by catching any
* exceptions that might be thrown when an operation is attempted.
*
* @return <code>true</code> if this <code>Connection</code> object
* is closed; <code>false</code> if it is still open
* @exception SQLException if a database access error occurs
*/
public boolean isClosed() throws SQLException {
return closed;
}
/**
* Retrieves a <code>DatabaseMetaData</code> object that contains
* metadata about the database to which this
* <code>Connection</code> object represents a connection.
* The metadata includes information about the database's
* tables, its supported SQL grammar, its stored
* procedures, the capabilities of this connection, and so on.
*
* @return a <code>DatabaseMetaData</code> object for this
* <code>Connection</code> object
* @exception SQLException if a database access error occurs
*/
public DatabaseMetaData getMetaData() throws SQLException {
throw new UnsupportedOperationException(
"Connection.getMetaData() unsupported");
}
/**
* Puts this connection in read-only mode as a hint to the driver to enable
* database optimizations.
*
* <P><B>Note:</B> This method cannot be called during a transaction.
*
* @param readOnly <code>true</code> enables read-only mode;
* <code>false</code> disables it
* @exception SQLException if a database access error occurs or this
* method is called during a transaction
*/
public void setReadOnly(boolean readOnly) throws SQLException {
throw new UnsupportedOperationException(
"Connection.setReadOnly(boolean) unsupported");
}
/**
* Retrieves whether this <code>Connection</code>
* object is in read-only mode.
*
* @return <code>true</code> if this <code>Connection</code> object
* is read-only; <code>false</code> otherwise
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly() throws SQLException {
return true;
}
/**
* Sets the given catalog name in order to select
* a subspace of this <code>Connection</code> object's database
* in which to work.
* <P>
* If the driver does not support catalogs, it will
* silently ignore this request.
*
* @param catalog the name of a catalog (subspace in this
* <code>Connection</code> object's database) in which to work
* @exception SQLException if a database access error occurs
* @see #getCatalog
*/
public void setCatalog(String catalog) throws SQLException {
// silently ignore this request
}
/**
* Retrieves this <code>Connection</code> object's current catalog name.
*
* @return the current catalog name or <code>null</code> if there is none
* @exception SQLException if a database access error occurs
* @see #setCatalog
*/
public String getCatalog() throws SQLException {
return null;
}
/**
* Attempts to change the transaction isolation level for this
* <code>Connection</code> object to the one given.
* The constants defined in the interface <code>Connection</code>
* are the possible transaction isolation levels.
* <P>
* <B>Note:</B> If this method is called during a transaction, the result
* is implementation-defined.
*
* @param level one of the following <code>Connection</code> constants:
* <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
* <code>Connection.TRANSACTION_READ_COMMITTED</code>,
* <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
* <code>Connection.TRANSACTION_SERIALIZABLE</code>.
* (Note that <code>Connection.TRANSACTION_NONE</code> cannot be used
* because it specifies that transactions are not supported.)
* @exception SQLException if a database access error occurs
* or the given parameter is not one of the <code>Connection</code>
* constants
* @see DatabaseMetaData#supportsTransactionIsolationLevel
* @see #getTransactionIsolation
*/
public void setTransactionIsolation(int level) throws SQLException {
throw new UnsupportedOperationException(
"Connection.setTransactionIsolation(int) unsupported");
}
/**
* Retrieves this <code>Connection</code> object's current
* transaction isolation level.
*
* @return the current transaction isolation level, which will be one
* of the following constants:
* <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
* <code>Connection.TRANSACTION_READ_COMMITTED</code>,
* <code>Connection.TRANSACTION_REPEATABLE_READ</code>,
* <code>Connection.TRANSACTION_SERIALIZABLE</code>, or
* <code>Connection.TRANSACTION_NONE</code>.
* @exception SQLException if a database access error occurs
* @see #setTransactionIsolation
*/
public int getTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_NONE;
}
/**
* Retrieves the first warning reported by calls on this
* <code>Connection</code> object. If there is more than one
* warning, subsequent warnings will be chained to the first one
* and can be retrieved by calling the method
* <code>SQLWarning.getNextWarning</code> on the warning
* that was retrieved previously.
* <P>
* This method may not be
* called on a closed connection; doing so will cause an
* <code>SQLException</code> to be thrown.
*
* <P><B>Note:</B> Subsequent warnings will be chained to this
* SQLWarning.
*
* @return the first <code>SQLWarning</code> object or <code>null</code>
* if there are none
* @exception SQLException if a database access error occurs or
* this method is called on a closed connection
* @see SQLWarning
*/
public SQLWarning getWarnings() throws SQLException {
throw new UnsupportedOperationException(
"Connection.getWarnings() unsupported");
}
/**
* Clears all warnings reported for this <code>Connection</code> object.
* After a call to this method, the method <code>getWarnings</code>
* returns <code>null</code> until a new warning is
* reported for this <code>Connection</code> object.
*
* @exception SQLException if a database access error occurs
*/
public void clearWarnings() throws SQLException {
throw new UnsupportedOperationException(
"Connection.getWarnings() unsupported");
}
/**
* Creates a <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>createStatement</code> method
* above, but it allows the default result set
* type and concurrency to be overridden.
*
* @param resultSetType a result set type; one of
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency a concurrency type; one of
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @return a new <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type and
* concurrency
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type and concurrency
*/
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
throw new UnsupportedOperationException(
"Connection.createStatement(int, int) unsupported");
}
/**
* Creates a <code>PreparedStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>prepareStatement</code> method
* above, but it allows the default result set
* type and concurrency to be overridden.
*
* @param sql a <code>String</code> object that is the SQL statement to
* be sent to the database; may contain one or more ? IN
* parameters
* @param resultSetType a result set type; one of
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency a concurrency type; one of
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @return a new PreparedStatement object containing the
* pre-compiled SQL statement that will produce <code>ResultSet</code>
* objects with the given type and concurrency
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type and concurrency
*/
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
throw new UnsupportedOperationException(
"Connection.prepareStatement(String, int, int) unsupported");
}
/**
* Creates a <code>CallableStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>prepareCall</code> method
* above, but it allows the default result set
* type and concurrency to be overridden.
*
* @param sql a <code>String</code> object that is the SQL statement to
* be sent to the database; may contain on or more ? parameters
* @param resultSetType a result set type; one of
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency a concurrency type; one of
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @return a new <code>CallableStatement</code> object containing the
* pre-compiled SQL statement that will produce <code>ResultSet</code>
* objects with the given type and concurrency
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type and concurrency
*/
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
throw new UnsupportedOperationException(
"Connection.prepareCall(String, int, int) unsupported");
}
/**
* Retrieves the <code>Map</code> object associated with this
* <code>Connection</code> object.
* Unless the application has added an entry, the type map returned
* will be empty.
*
* @return the <code>java.util.Map</code> object associated
* with this <code>Connection</code> object
* @exception SQLException if a database access error occurs
* @see #setTypeMap
*/
public Map getTypeMap() throws SQLException {
throw new UnsupportedOperationException(
"Connection.getTypeMap() unsupported");
}
/**
* Installs the given <code>TypeMap</code> object as the type map for
* this <code>Connection</code> object. The type map will be used for the
* custom mapping of SQL structured types and distinct types.
*
* @param map the <code>java.util.Map</code> object to install
* as the replacement for this <code>Connection</code>
* object's default type map
* @exception SQLException if a database access error occurs or
* the given parameter is not a <code>java.util.Map</code>
* object
* @see #getTypeMap
*/
public void setTypeMap(Map map) throws SQLException {
throw new UnsupportedOperationException(
"Connection.setTypeMap(Map) unsupported");
}
// Properties
/**
* Accessor method for the path property
* @return current value for the path property
*/
protected String getPath() {
return path;
}
/**
* Accessor method for the extension property
* @return current value for the extension property
*/
protected String getExtension() {
return extension;
}
/**
* Accessor method for the separator property
* @return current value for the separator property
*/
protected char getSeperator() {
return separator;
}
/**
* Accessor method for the suppressHeaders property
* @return current value for the suppressHeaders property
*/
protected boolean isSuppressHeaders() {
return suppressHeaders;
}
/**
* Changes the holdability of <code>ResultSet</code> objects
* created using this <code>Connection</code> object to the given
* holdability.
*
* @param holdability a <code>ResultSet</code> holdability constant; one of
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @throws SQLException if a database access occurs, the given parameter
* is not a <code>ResultSet</code> constant indicating holdability,
* or the given holdability is not supported
* @see #getHoldability
* @see ResultSet
*/
}
|
package net.sf.aceunit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Special variant of MethodList which supports a parametrized annotation.
*
* @author <a href="mailto:cher@riedquat.de">Christian Hujer</a>
*/
public class MethodList2 extends MethodList {
/**
* The regular expression to use for finding annotated methods.
*/
@NotNull
private final Pattern pattern;
/**
* The arguments.
*/
private final Map<String, String> args = new HashMap<>();
/**
* The default value returned by {@link #getArg(String)} in case no method was annotated with this annotation.
*/
private final String defaultValue;
/**
* Create a MethodList.
* The MethodList is initially empty.
* Invoke {@link #findMethods(String)} to fill this MethodList.
*
* @param annotation Annotation to find.
* @param symName Name to use for symbols related to this MethodList.
* @param title Title to use e.g. in comments.
* @param defaultValue Default value to return by {@link #getArg(String)} for not annotated methods.
*/
public MethodList2(@NotNull final String annotation, @NotNull final String symName, @NotNull final String title, @Nullable final String defaultValue) {
super(annotation, symName, title);
pattern = Pattern.compile("\\b" + annotation + "\\b\\s*\\((.*?)\\).*?(\\b\\S+?\\b)\\s*?\\(", Pattern.MULTILINE | Pattern.DOTALL);
this.defaultValue = defaultValue;
}
/**
* Finds all annotated methods in the specified C source.
*
* @param cSource C source to search.
*/
public void findMethods(@NotNull final String cSource) {
methodNames.clear();
args.clear();
final Matcher matcher = pattern.matcher(cSource);
while (matcher.find()) {
final String methodName = matcher.group(2);
methodNames.add(methodName);
String arg = matcher.group(1);
if (arg == null) {
arg = "";
}
arg = arg.trim();
if (arg.length() == 0) {
arg = "1";
}
args.put(methodName, arg);
}
}
/**
* Returns the loop annotation argument of the specified method.
*
* @param methodName Method for which to get the loop argument.
* @return Loop argument of the specified method.
*/
@Nullable
public String getArg(@NotNull final String methodName) {
return args.containsKey(methodName) ? args.get(methodName) : defaultValue;
}
}
|
package dr.app.beauti.options;
import dr.app.beauti.enumTypes.FixRateType;
import java.util.List;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
* @version $Id$
*/
public class PriorOptions extends ModelOptions {
// Instance variables
private final BeautiOptions options;
public PriorOptions(BeautiOptions options) {
this.options = options;
}
/**
* return a list of parameters that are required
*
* @param params the parameter list
*/
public void selectParameters(List<Parameter> params) {
double growthRateMaximum = 1E6;
// double birthRateMaximum = 1E6;
// double substitutionRateMaximum = 100;
// double logStdevMaximum = 10;
// double substitutionParameterMaximum = 100;
double[] rootAndRate = options.clockModelOptions.calculateInitialRootHeightAndRate(options.getNonTraitsDataList());
double avgInitialRootHeight = rootAndRate[0];
double avgInitialRate = rootAndRate[1];
if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN
|| options.clockModelOptions.getRateOptionClockModel() == FixRateType.RELATIVE_TO) {
growthRateMaximum = 1E6 * avgInitialRate;
// birthRateMaximum = 1E6 * avgInitialRate;
}
// if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
// double rate = options.clockModelOptions.getMeanRelativeRate();
// growthRateMaximum = 1E6 * rate;
// birthRateMaximum = 1E6 * rate;
// if (options.hasData()) {
// initialRootHeight = meanDistance / rate;
// initialRootHeight = round(initialRootHeight, 2);
// } else {
// if (options.maximumTipHeight > 0) {
// initialRootHeight = options.maximumTipHeight * 10.0;
// initialRate = round((meanDistance * 0.2) / initialRootHeight, 2);
// double timeScaleMaximum = MathUtils.round(avgInitialRootHeight * 1000.0, 2);
for (Parameter param : params) {
if (!options.hasData()) param.setPriorEdited(false);
if (!param.isPriorEdited()) {
switch (param.scaleType) {
case TIME_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(timeScaleMaximum, param.upper);
param.initial = avgInitialRootHeight;
break;
case T50_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(timeScaleMaximum, param.upper);
param.initial = avgInitialRootHeight / 5.0;
break;
case GROWTH_RATE_SCALE:
param.initial = avgInitialRootHeight / 1000;
if (param.getBaseName().startsWith("logistic")) {
param.stdev = Math.log(1000) / avgInitialRootHeight;
// System.out.println("logistic");
} else {
param.stdev = Math.log(10000) / avgInitialRootHeight;
// System.out.println("not logistic");
}
break;
case BIRTH_RATE_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(birthRateMaximum, param.upper);
break;
case SUBSTITUTION_RATE_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(substitutionRateMaximum, param.upper);
param.initial = avgInitialRate;
break;
case LOG_STDEV_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(logStdevMaximum, param.upper);
break;
case SUBSTITUTION_PARAMETER_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(substitutionParameterMaximum, param.upper);
break;
case UNITY_SCALE:
param.lower = 0.0;
param.upper = 1.0;
break;
case ROOT_RATE_SCALE:
param.initial = avgInitialRate;
param.shape = 0.5;
param.scale = param.initial / 0.5;
break;
case LOG_VAR_SCALE:
param.initial = avgInitialRate;
param.shape = 2.0;
param.scale = param.initial / 2.0;
break;
}
if (param.isNodeHeight) { //TODO only affecting "treeModel.rootHeight", need to review
param.lower = options.maximumTipHeight;
// param.upper = timeScaleMaximum;
// param.initial = avgInitialRootHeight;
if (param.getOptions() instanceof PartitionTreeModel) {
param.initial = ((PartitionTreeModel) param.getOptions()).getInitialRootHeight();
} else {
param.initial = avgInitialRootHeight;
}
}
}
}
// dataReset = false;
}
}
|
package dr.evolution.coalescent;
import dr.evolution.tree.Tree;
import dr.evolution.util.Units;
import dr.math.Binomial;
import dr.math.MultivariateFunction;
/**
* A likelihood function for the coalescent. Takes a tree and a demographic model.
*
* Parts of this class were derived from C++ code provided by Oliver Pybus.
*
* @version $Id: Coalescent.java,v 1.12 2005/05/24 20:25:55 rambaut Exp $
*
* @author Andrew Rambaut
* @author Alexei Drummond
*/
public class Coalescent implements MultivariateFunction, Units {
// PUBLIC STUFF
public Coalescent(Tree tree, DemographicFunction demographicFunction) {
this(new TreeIntervals(tree), demographicFunction);
}
public Coalescent(IntervalList intervals, DemographicFunction demographicFunction) {
this.intervals = intervals;
this.demographicFunction = demographicFunction;
}
/**
* Calculates the log likelihood of this set of coalescent intervals,
* given a demographic model.
*/
public double calculateLogLikelihood() {
return calculateLogLikelihood(intervals, demographicFunction);
}
/**
* Calculates the log likelihood of this set of coalescent intervals,
* given a demographic model.
*/
public static double calculateLogLikelihood(IntervalList intervals, DemographicFunction demographicFunction) {
double logL = 0.0;
double startTime = 0.0;
final int n = intervals.getIntervalCount();
for (int i = 0; i < n; i++) {
final double duration = intervals.getInterval(i);
final double finishTime = startTime + duration;
final double intervalArea = demographicFunction.getIntegral(startTime, finishTime);
final int lineageCount = intervals.getLineageCount(i);
final double kChoose2 = Binomial.choose2(lineageCount);
// common part
logL += -kChoose2 * intervalArea;
if (intervals.getIntervalType(i) == IntervalType.COALESCENT) {
final double demographicAtCoalPoint = demographicFunction.getDemographic(finishTime);
// if value at end is many orders of magnitude different than mean over interval reject the interval
// This is protection against cases where ridiculous infitisimal
// population size at the end of a linear interval drive coalescent values to infinity.
if( duration == 0.0 || demographicAtCoalPoint > 1e-12 * (duration/intervalArea) ) {
// AR - this was causing some initial trees to fail. Kept the warning in but removed the exception.
// logL -= Math.log(demographicAtCoalPoint);
} else {
// remove this at some stage
System.err.println("Warning: " + i + " " + demographicAtCoalPoint + " " + (intervalArea/duration) );
// return Double.NEGATIVE_INFINITY;
}
logL -= Math.log(demographicAtCoalPoint);
}
startTime = finishTime;
}
return logL;
}
/**
* Calculates the log likelihood of this set of coalescent intervals,
* using an analytical integration over theta.
*/
public static double calculateAnalyticalLogLikelihood(IntervalList intervals) {
if (!intervals.isCoalescentOnly()) {
throw new IllegalArgumentException("Can only calculate analytical likelihood for pure coalescent intervals");
}
final double lambda = getLambda(intervals);
final int n = intervals.getSampleCount();
// assumes a 1/theta prior
//logLikelihood = Math.log(1.0/Math.pow(lambda,n));
// assumes a flat prior
return (1-n) * Math.log(lambda); // Math.log(1.0/Math.pow(lambda,n-1));
}
/**
* Returns a factor lambda such that the likelihood can be expressed as
* 1/theta^(n-1) * exp(-lambda/theta). This allows theta to be integrated
* out analytically. :-)
*/
private static double getLambda(IntervalList intervals) {
double lambda = 0.0;
for (int i= 0; i < intervals.getIntervalCount(); i++) {
lambda += (intervals.getInterval(i) * intervals.getLineageCount(i));
}
lambda /= 2;
return lambda;
}
// MultivariateFunction IMPLEMENTATION
public double evaluate(double[] argument) {
for (int i = 0; i < argument.length; i++) {
demographicFunction.setArgument(i, argument[i]);
}
return calculateLogLikelihood();
}
public int getNumArguments() {
return demographicFunction.getNumArguments();
}
public double getLowerBound(int n) {
return demographicFunction.getLowerBound(n);
}
public double getUpperBound(int n) {
return demographicFunction.getUpperBound(n);
}
// Units IMPLEMENTATION
/**
* Sets the units these coalescent intervals are
* measured in.
*/
public final void setUnits(Type u)
{
demographicFunction.setUnits(u);
}
/**
* Returns the units these coalescent intervals are
* measured in.
*/
public final Type getUnits()
{
return demographicFunction.getUnits();
}
/** The demographic function. */
DemographicFunction demographicFunction = null;
/** The intervals. */
IntervalList intervals = null;
}
|
package edu.ew.view.playground;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import edu.ew.model.Energy;
import edu.ew.model.EnergyPalette;
import edu.ew.model.EnergySet;
import edu.ew.model.Player;
import edu.ew.view.ViewConstants;
/**
*
* @author Selcuk Gulcan
*
*/
@SuppressWarnings("serial")
public class EnergyPanel extends JPanel implements Observer{
private static final Dimension SIZE = new Dimension(
ViewConstants.frameWidth - ViewConstants.cardViewPanelSize.width, 70);
private static final Dimension SIZE_ONE = new Dimension( 70, 70);
private ArrayList<OneEnergy> energies;
private JLabel life;
public EnergyPanel() {
super();
setLayout( new GridLayout( 1, 11));
setPreferredSize( SIZE);
setMaximumSize( getPreferredSize());
setBackground( PlaygroundConstants.background);
energies = new ArrayList<OneEnergy>();
for( int i = 0; i < 10; i++)
energies.add( new OneEnergy());
for( int i = 0; i < 5; i++)
add( energies.get( i));
life=new JLabel( "20");
life.setFont( PlaygroundConstants.bigFont);
life.setForeground( Color.red);
life.setIcon( ViewConstants.life);
life.setIconTextGap(-48);
life.setOpaque(true);
life.setLayout(null);
life.setBackground( Color.white);
add(life);
//life.setText("12");
add( life);
//add( new JLabel( ViewConstants.life));
for( int i = 5; i < 10; i++)
add( energies.get( i));
}
public void setEnergy( int index, Energy energy) {
energies.get(index).set(energy);
}
public void addEnergy( Energy energy) {
getFirstEmpty().set( energy);
}
public void clear() {
Iterator<OneEnergy> it = energies.iterator();
while( it.hasNext()) {
OneEnergy current = it.next();
current.removeAll();
current.setFull( false);
}
}
public void addUsedEnergy( Energy energy) {
OneEnergy slot = getFirstEmpty();
slot.set( energy);
slot.use();
}
public OneEnergy getFirstEmpty() {
for( int i = 0; i < energies.size(); i++)
if( !energies.get(i).isFull())
return energies.get(i);
return null;
}
public class OneEnergy extends JPanel {
private boolean full;
public OneEnergy() {
setPreferredSize( SIZE_ONE);
setMaximumSize( getPreferredSize());
setBackground( PlaygroundConstants.background);
full = false;
}
public boolean isFull() {
return full;
}
public void setFull( boolean status) {
full = status;
}
public void use() {
setBackground( Color.gray);
update( getGraphics());
revalidate();
repaint();
}
public void set( Energy energy) {
setBackground( Color.white);
full = true;
removeAll();
switch (energy) {
case AIR:
add( new JLabel( ViewConstants.airBig));
break;
case EARTH:
add( new JLabel( ViewConstants.earthBig));
break;
case FIRE:
add( new JLabel( ViewConstants.fireBig));
break;
case PURE:
add( new JLabel( ViewConstants.pureBig));
break;
case TRIVIAL:
break;
case WATER:
add( new JLabel( ViewConstants.waterBig));
break;
default:
break;
}
update( getGraphics());
}
}
@Override
public void update(Observable o, Object arg) {
if( o instanceof Player) {
Player p = (Player)o;
life.setText( "" + p.getHealth());
update( getGraphics());
}
else if( o instanceof EnergyPalette) {
System.out.println( "portals online");
clear();
EnergyPalette palette = (EnergyPalette)o;
EnergySet max = palette.getMaxEnergies();
EnergySet active = palette.getActiveEnergies();
int no = 0;
no = max.getAir() - active.getAir();
for( int i = 0; i < no; i++)
addUsedEnergy( Energy.AIR);
for( int i = 0; i < active.getAir(); i++)
addEnergy( Energy.AIR);
no = max.getEarth() - active.getEarth();
for( int i = 0; i < no; i++)
addUsedEnergy( Energy.EARTH);
for( int i = 0; i < active.getEarth(); i++)
addEnergy( Energy.EARTH);
no = max.getFire() - active.getFire();
for( int i = 0; i < no; i++)
addUsedEnergy( Energy.FIRE);
for( int i = 0; i < active.getFire(); i++)
addEnergy( Energy.FIRE);
no = max.getWater() - active.getWater();
for( int i = 0; i < no; i++)
addUsedEnergy( Energy.WATER);
for( int i = 0; i < active.getWater(); i++)
addEnergy( Energy.WATER);
no = max.getPure() - active.getPure();
for( int i = 0; i < no; i++) {
addUsedEnergy( Energy.PURE);
}
for( int i = 0; i < active.getPure(); i++) {
addEnergy( Energy.PURE);
}
update( getGraphics());
revalidate();
repaint();
}
}
}
|
package edu.usfca.vas.layout.Views;
import com.teamdev.jxmaps.LatLng;
import com.teamdev.jxmaps.swing.MapView;
import java.util.*;
public class MapTest implements Runnable {
private MapsView mapView;
private Thread t;
private ArrayList<Double[]> curMarked;
public MapTest(MapsView view) {
this.mapView =view;
curMarked = new ArrayList<>();
}
public void run(){
while(true){
markRandomLocationInNewYork();
Random r = new Random();
int num = r.nextInt(6);
if(curMarked.size()>15) //make sure there are no more than 15 markers on the map
num =0;
if(num !=0){
removeRandomLocation();
}
try{
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void start(){
if (t==null) {
Thread t = new Thread(this, "Marker Creation Thread");
t.start();
}
}
private void markRandomLocationInNewYork(){
Random r = new Random();
/*40.879466, 74.004525;
40.709482, 73.957904;*/
double lat = 40.709482 + (40.879466 - 40.709482) * r.nextDouble();
double lng = 73.957904 + (74.004525 - 73.957904) * r.nextDouble();
lng *= -1;
Double[] latLng = {lat,lng};
curMarked.add(latLng);
mapView.markLatLng(lat,lng);
}
private void removeRandomLocation(){
if(!curMarked.isEmpty()){
Random r = new Random();
int randIndex = r.nextInt(curMarked.size());
Double[] latlng = curMarked.get(randIndex);
mapView.removeMarker(latlng[0],latlng[1]);
curMarked.remove(randIndex);
}
}
}
|
package eu.project.rapid.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Pattern;
import eu.project.rapid.common.RapidMessages.AnimationMsg;
/**
* These are some utilities to be used on the Rapid project.
* In particular, some important functions are used by the AS and AC.
* @author sokol
*/
public class RapidUtils {
private static final String TAG = "RapidUtils";
private static final String IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
private static boolean demoAnimate = true;
private static final Thread demoServerThread;
private static BlockingQueue<String> commandQueue = new ArrayBlockingQueue<String>(1000);
private static String demoServerIp;
private static int demoServerPort;
static {
demoServerThread = new Thread() {
public void run() {
System.out.println("Started thread that consumes the commands to send to the Demo server");
while (true) {
try {
String cmd = commandQueue.take();
sendAnimationMsg(cmd);
} catch (InterruptedException e) {
}
}
}
};
demoServerThread.start();
}
/**
* Utility to execute a shell command on a Mac OS.
*
* @param command
* @param asRoot
* @param password
* @return
*/
public static String executeCommand(String command, boolean asRoot, String password) {
Process p = null;
String[] cmd = new String[] {"/bin/bash", "-c", command};
try {
if (asRoot) {
cmd = new String[] {"/bin/bash", "-c", "echo " + password + "|sudo -S " + command};
}
System.out.println("Executing command: " + command);
p = Runtime.getRuntime().exec(cmd);
// you can pass the system command or a script to exec command.
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
// read the output from the command
StringBuilder sb = new StringBuilder();
String s = "";
while ((s = stdInput.readLine()) != null) {
// System.out.println("Std OUT: "+s);
sb.append(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println("Std ERROR : " + s);
}
System.out.println(sb.toString());
stdInput.close();
stdError.close();
writer.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String executeCommand(String command) {
return executeCommand(command, false, null);
}
public static byte[] serialize(Object obj) throws IOException {
byte[] serializedObj;
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
try {
o.writeObject(obj);
o.flush();
serializedObj = b.toByteArray();
} finally {
o.close();
}
return serializedObj;
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
return RapidUtils.deserialize(bytes, 0, bytes.length);
}
public static Object deserialize(byte[] bytes, int offset, int length)
throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream b = new ByteArrayInputStream(bytes, offset, length);
ObjectInputStream o = new ObjectInputStream(b);
obj = o.readObject();
o.close();
return obj;
}
/**
* Connect to the animation server and send the messages that represent the sequence of
* operations.
*
* @param config
* @param millis
* @param msgs
*/
public static synchronized void sendAnimationMsg(Configuration config, String msg) {
sendAnimationMsg(config.getAnimationServerIp(), config.getAnimationServerPort(), msg);
}
public static synchronized void sendAnimationMsg(Configuration config, AnimationMsg msg) {
sendAnimationMsg(config.getAnimationServerIp(), config.getAnimationServerPort(), msg.toString());
}
/**
* Connect to the animation server and send the messages that represent the sequence of
* operations.
*
* @param config
* @param millis
* @param msgs
*/
public static synchronized void sendAnimationMsg(final String ip, final int port,
final String msg) {
if (demoAnimate) {
RapidUtils.demoServerIp = ip;
RapidUtils.demoServerPort = port;
boolean added = false;
while (!added) {
try {
commandQueue.put(msg);
added = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void closeQuietly(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(ObjectInputStream oIs) {
if (oIs != null) {
try {
oIs.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(ObjectOutputStream oOs) {
if (oOs != null) {
try {
oOs.close();
} catch (IOException e) {
}
}
}
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
private static void sendAnimationMsg(String msg) {
Socket socket = null;
PrintWriter pout = null;
try {
System.out.println(TAG + " - Sending animation msg: " + msg);
socket = new Socket(demoServerIp, demoServerPort);
pout = new PrintWriter(socket.getOutputStream(), true);
pout.print(msg);
} catch (UnknownHostException e) {
System.err.println("Could not connect to animation server: " + demoServerIp + ":"
+ demoServerPort + ": " + e);
} catch (IOException e) {
System.err.println("Could not connect to animation server: " + demoServerIp + ":"
+ demoServerPort + ": " + e);
} catch (Exception e) {
System.err.println("Could not connect to animation server: " + demoServerIp + ":"
+ demoServerPort + ": " + e);
} finally {
if (pout != null) {
pout.close();
}
closeQuietly(socket);
}
}
/**
* Validate ip address with regular expression
* @param ip ip address for validation
* @return true valid ip address, false invalid ip address
*/
public static boolean validateIpAddress(final String ip){
Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
return pattern.matcher(ip).matches();
}
public static String getVmIpLinux() {
String localIpAddress = "";
Enumeration<NetworkInterface> e;
try {
e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration<InetAddress> ee = n.getInetAddresses();
boolean stop = false;
while (ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
if (i.getHostAddress().startsWith("10.0.")) {
localIpAddress = i.getHostAddress();
stop = true;
break;
}
}
if (stop)
break;
}
} catch (SocketException e1) {
System.err.println("Error while getting VM IP: " + e1);
}
return localIpAddress;
}
/**
* Connects to the DS and returns the IP of the demo animation server.
* @param dsIp
* @param dsPort
* @return IP of the demo animation server or null.
*/
public static String getDemoAnimationServerIpFromDs(String dsIp, int dsPort) {
String ip = null;
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
socket = new Socket(dsIp, dsPort);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
oos.writeByte(RapidMessages.GET_DEMO_SERVER_IP_DS);
oos.flush();
ip = ois.readUTF();
} catch (UnknownHostException e) {
System.err.println("Could not connect to DS for getting demo server IP: " + e);
} catch (IOException e) {
System.err.println("Could not connect to DS for getting demo server IP: " + e);
} finally {
closeQuietly(ois);
closeQuietly(oos);
closeQuietly(socket);
}
return ip;
}
}
|
package backtype.storm.utils;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.MultiThreadedClaimStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class allows publishers to start publishing before consumer is set up,
* making it much easier to structure code around the disruptor.
*/
public class DisruptorQueue {
private static final Object MARKER = new Object();
private static final Object HALT_PROCESSING = new Object();
Disruptor _disruptor;
ExecutorService _executor;
WaiterEventHandler _handler;
RingBuffer<MutableObject> _buffer;
public DisruptorQueue(Number bufferSize) {
_executor = Executors.newSingleThreadExecutor();
_disruptor = new Disruptor(new ObjectEventFactory(), _executor, new MultiThreadedClaimStrategy(bufferSize.intValue()), new BlockingWaitStrategy());
_handler = new WaiterEventHandler();
_disruptor.handleEventsWith(_handler);
_buffer = _disruptor.start();
}
public void setHandler(EventHandler handler) {
_handler.setHandler(handler);
publish(MARKER);
}
public void publish(Object o) {
final long id = _buffer.next();
final MutableObject m = _buffer.get(id);
m.setObject(o);
_buffer.publish(id);
}
public void haltProcessing() {
publish(HALT_PROCESSING);
}
public void shutdown() {
_disruptor.shutdown();
_executor.shutdown();
}
static class WaiterEventHandler implements EventHandler<MutableObject> {
AtomicBoolean started = new AtomicBoolean(false);
volatile EventHandler _promise = null;
EventHandler _cached = null;
List<CachedEvent> _toHandle = new ArrayList<CachedEvent>();
boolean halted = false;
public void setHandler(EventHandler handler) {
if(_promise!=null) {
throw new RuntimeException("Cannot set event handler more than once");
}
_promise = handler;
}
@Override
public void onEvent(MutableObject t, long sequence, boolean isBatchEnd) throws Exception {
Object o = t.getObject();
if(o==HALT_PROCESSING) {
_cached = null;
halted = true;
}
if(_cached!=null && o != MARKER) {
handleEvent(o, sequence, isBatchEnd);
} else {
if(!halted) {
if(_promise!=null) {
_cached = _promise;
for(CachedEvent e: _toHandle) {
handleEvent(e.o, e.seq, e.isBatchEnd);
}
_toHandle.clear();
if(o != MARKER) handleEvent(o, sequence, isBatchEnd);
} else {
if(o==MARKER) {
throw new RuntimeException("Got marker object before promise was set");
}
_toHandle.add(new CachedEvent(o, sequence, isBatchEnd));
}
}
}
}
private void handleEvent(Object o, long sequence, boolean isBatchEnd) throws Exception {
_cached.onEvent(o, sequence, isBatchEnd);
}
}
static class CachedEvent {
public Object o;
public long seq;
public boolean isBatchEnd;
public CachedEvent(Object o, long seq, boolean isBatchEnd) {
this.o = o;
this.seq = seq;
this.isBatchEnd = isBatchEnd;
}
}
static class ObjectEventFactory implements EventFactory<MutableObject> {
@Override
public MutableObject newInstance() {
return new MutableObject();
}
}
}
|
package storm.kafka;
import backtype.storm.spout.RawScheme;
import backtype.storm.spout.Scheme;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BasePartitionedTransactionalSpout;
import backtype.storm.transactional.TransactionAttempt;
import backtype.storm.transactional.TransactionalOutputCollector;
import backtype.storm.transactional.partitioned.IPartitionedTransactionalSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import kafka.api.FetchRequest;
import kafka.javaapi.consumer.SimpleConsumer;
import kafka.javaapi.message.ByteBufferMessageSet;
import kafka.message.Message;
import kafka.message.MessageSet;
public class TransactionalKafkaSpout extends BasePartitionedTransactionalSpout<BatchMeta> {
public static final String ATTEMPT_FIELD = TransactionalKafkaSpout.class.getCanonicalName() + "/attempt";
public static class Config implements Serializable {
public List<String> hosts;
public int port = 9092;
public int partitionsPerHost;
public int fetchSizeBytes = 1024*1024;
public int socketTimeoutMs = 10000;
public int bufferSizeBytes = 1024*1024;
public Scheme scheme = new RawScheme();
public String topic;
public Config(List<String> hosts, int partitionsPerHost, String topic) {
this.hosts = hosts;
this.partitionsPerHost = partitionsPerHost;
this.topic = topic;
}
}
Config _config;
public TransactionalKafkaSpout(Config config) {
_config = config;
}
class Coordinator implements IPartitionedTransactionalSpout.Coordinator {
@Override
public int numPartitions() {
return computeNumPartitions();
}
@Override
public void close() {
}
}
class Emitter implements IPartitionedTransactionalSpout.Emitter<BatchMeta> {
Map<Integer, SimpleConsumer> _kafka = new HashMap<Integer, SimpleConsumer>();
@Override
public BatchMeta emitPartitionBatchNew(TransactionAttempt attempt, TransactionalOutputCollector collector, int partition, BatchMeta lastMeta) {
SimpleConsumer consumer = connect(partition);
long offset = 0;
if(lastMeta!=null) {
offset = lastMeta.nextOffset;
}
ByteBufferMessageSet msgs = consumer.fetch(new FetchRequest(_config.topic, partition % _config.partitionsPerHost, offset, _config.fetchSizeBytes));
long endoffset = offset;
for(Message msg: msgs) {
emit(attempt, collector, msg);
endoffset += MessageSet.entrySize(msg);
}
BatchMeta newMeta = new BatchMeta();
newMeta.offset = offset;
newMeta.nextOffset = endoffset;
return newMeta;
}
@Override
public void emitPartitionBatch(TransactionAttempt attempt, TransactionalOutputCollector collector, int partition, BatchMeta meta) {
SimpleConsumer consumer = connect(partition);
ByteBufferMessageSet msgs = consumer.fetch(new FetchRequest(_config.topic, partition % _config.partitionsPerHost, meta.offset, _config.fetchSizeBytes));
long currOffset = meta.offset;
for(Message msg: msgs) {
if(currOffset == meta.nextOffset) break;
if(currOffset > meta.nextOffset) {
throw new RuntimeException("Error when re-emitting batch. overshot the end offset");
}
emit(attempt, collector, msg);
currOffset += MessageSet.entrySize(msg);
}
}
private void emit(TransactionAttempt attempt, TransactionalOutputCollector collector, Message msg) {
List<Object> values = _config.scheme.deserialize(Utils.toByteArray(msg.payload()));
List<Object> toEmit = new ArrayList<Object>();
toEmit.add(attempt);
toEmit.addAll(values);
collector.emit(toEmit);
}
private SimpleConsumer connect(int partition) {
if(!_kafka.containsKey(partition)) {
int hostIndex = partition % _config.hosts.size();
_kafka.put(partition, new SimpleConsumer(_config.hosts.get(hostIndex), _config.port, _config.socketTimeoutMs, _config.bufferSizeBytes));
}
return _kafka.get(partition);
}
@Override
public void close() {
for(SimpleConsumer consumer: _kafka.values()) {
consumer.close();
}
}
}
@Override
public IPartitionedTransactionalSpout.Coordinator getCoordinator(Map conf, TopologyContext context) {
return new Coordinator();
}
@Override
public IPartitionedTransactionalSpout.Emitter getEmitter(Map conf, TopologyContext context) {
return new Emitter();
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
List<String> fields = new ArrayList<String>(_config.scheme.getOutputFields().toList());
fields.add(0, ATTEMPT_FIELD);
declarer.declare(new Fields(fields));
}
private int computeNumPartitions() {
return _config.hosts.size() * _config.partitionsPerHost;
}
@Override
public Map<String, Object> getComponentConfiguration() {
backtype.storm.Config conf = new backtype.storm.Config();
conf.registerSerialization(BatchMeta.class);
return conf;
}
}
|
package lia.util.net.common;
import ch.ethz.ssh2.StreamGobbler;
import com.sshtools.common.configuration.SshToolsConnectionProfile;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.session.SessionChannelClient;
import org.ietf.jgss.GSSException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Adrian Muraru
*/
public class GSISSHControlStream implements ControlStream {
// configuration parameters
private final String hostname;
private final String username;
private final int port;
/**
* the SSH connection & session
*/
private SshClient conn;
private SessionChannelClient sess;
private String cmd;
private String customShell;
/**
* Creates a new GSI SSH control connection on the default ssh port.
* <p>
* Same as {@link #GSISSHControlStream(String, String, int) GSISSHControlStream(hostname, username, 22)}
*
* @param hostname: remote host
* @param username: remote account
* @throws IOException in case of failure
*/
public GSISSHControlStream(String hostname, String username) {
this(hostname, username, 22);
}
/**
* Creates a new SSH control connection on the specified remote GSI sshd server port
*
* @param port: remote GSI-sshd port
* @param hostname: remote host
* @param username: remote account
* @throws IOException in case of failure
*/
public GSISSHControlStream(String hostname, String username, int port) {
this.hostname = hostname;
this.username = username;
this.port = port;
}
// TEST
public static void main(String[] args) throws IOException {
ControlStream cs = new GSISSHControlStream(args[0], args[1]);
cs.startProgram(args[2]);
/* read stdout */
InputStream stdout = new StreamGobbler(cs.getProgramStdOut());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
System.out.println("ExitCode:" + cs.getExitCode());
cs.close();
}
public void connect() throws IOException {
lia.gsi.ssh.GSIAuthenticationClient gsiAuth = null;
try {
gsiAuth = new lia.gsi.ssh.GSIAuthenticationClient();
gsiAuth.setUsername(username);
} catch (GSSException e) {
throw new IOException("Cannot load grid credentials.");
}
conn = new SshClient();
SshToolsConnectionProfile properties = new SshToolsConnectionProfile();
// TODO: add new "port" parameter
properties.setPort(port);
properties.setForwardingAutoStartMode(false);
properties.setHost(hostname);
properties.setUsername(username);
conn.setUseDefaultForwarding(false);
conn.connect(properties);
try {
// Authenticate the user
int result = conn.authenticate(gsiAuth, hostname);
if (result != AuthenticationProtocolState.COMPLETE) {
throw new IOException("GSI authentication failed");
}
// Open a session channel
sess = conn.openSessionChannel();
sess.requestPseudoTerminal("javash", 0, 0, 0, 0, "");
} catch (Throwable t) {
throw new IOException(t.getMessage());
}
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#startProgram(java.lang.String)
*/
public void startProgram(String cmd, String customShell) throws IOException {
this.cmd = customShell + " --login -c '" + cmd + " 2>&1'";
this.sess.executeCommand(this.cmd);
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#getProgramStdOut()
*/
public InputStream getProgramStdOut() {
return this.sess.getInputStream();
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#getProgramStdErr()
*/
public InputStream getProgramStdErr() throws IOException {
return this.sess.getStderrInputStream();
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#waitForControlMessage(java.lang.String, boolean, boolean)
*/
public void waitForControlMessage(String expect, boolean allowEOF, boolean grabRemainingLog) throws IOException {
/* read stdout */
// InputStream stdout = new StreamGobbler(getProgramStdOut());
BufferedReader br = new BufferedReader(new InputStreamReader(getProgramStdOut()));
final String outputPrefix = "[" + this.hostname + "]$ ";
while (true) {
String line = br.readLine();
if (line == null) {
if (allowEOF)
return;
// else
throw new IOException("[" + this.cmd + "] exited. No control message received]");
}
System.err.println(outputPrefix + line);
if (line.trim().equalsIgnoreCase(expect)) {
LogWriter lw = grabRemainingLog
? new LogWriter(br, "fdt_" + this.hostname + ".log")
: new LogWriter(br);
lw.setDaemon(true);
lw.start();
return;
}
}
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#waitForControlMessage(java.lang.String, boolean)
*/
public void waitForControlMessage(String expect, boolean allowEOF) throws IOException {
this.waitForControlMessage(expect, allowEOF, false);
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#waitForControlMessage(java.lang.String)
*/
public void waitForControlMessage(String expect) throws IOException {
this.waitForControlMessage(expect, false, true);
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#saveStdErr()
*/
public void saveStdErr() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(getProgramStdErr()));
LogWriter lw = new LogWriter(br, "fdt_" + this.hostname + ".err");
lw.setDaemon(true);
lw.start();
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#getExitCode()
*/
public int getExitCode() {
return this.sess.getExitCode();
}
/*
* (non-Javadoc)
*
* @see lia.util.net.common.ControlStream#close()
*/
public void close() {
try {
if (this.sess != null) {
this.sess.close();
}
} catch (IOException e) {
}
if (this.conn != null) {
this.conn.disconnect();
}
}
/**
* asynch write in a local log file of the remote stderr stream
*/
static class LogWriter extends Thread {
BufferedReader br;
String logFile;
public LogWriter(BufferedReader br) {
this.br = br;
this.logFile = null;
}
public LogWriter(BufferedReader br, String fileName) {
this.br = br;
this.logFile = fileName;
}
public void run() {
BufferedWriter out = null;
try {
if (this.logFile != null) {
out = new BufferedWriter(new FileWriter(logFile, false));
final Date date = new Date();
out.write("==============" + new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z").format(date) + "================\n");
}
while (true) {
String line = br.readLine();
if (line == null) {
if (out != null)
out.close();
return;
}
if (out != null) {
out.write(line + "\n");
out.flush();
}
}
} catch (IOException e) {
System.err.println("Cannot write remote log:" + logFile);
try {
if (out != null)
out.close();
} catch (IOException e1) {
}
return;
}
}
}
}
|
package com.qiniu.io;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.qiniu.auth.Client;
import com.qiniu.auth.JSONObjectRet;
import com.qiniu.conf.Conf;
import com.qiniu.utils.IOnProcess;
import com.qiniu.utils.InputStreamAt;
import com.qiniu.utils.MultipartEntity;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
public class IO {
public static String UNDEFINED_KEY = null;
private static Client mClient;
private static String mUptoken;
public IO(Client client, String uptoken) {
mClient = client;
mUptoken = uptoken;
}
private static Client defaultClient() {
if (mClient == null) {
mClient = Client.defaultClient();
}
return mClient;
}
/**
*
*
* @param key , UNDEFINED_KEY key
* @param isa
* @param extra
* @param ret
*/
public void put(String key, InputStreamAt isa, PutExtra extra, JSONObjectRet ret) {
MultipartEntity m = new MultipartEntity();
if (key != null) m.addField("key", key);
if (extra.checkCrc == PutExtra.AUTO_CRC32) {
try {
extra.crc32 = isa.crc32();
} catch (IOException e) {
ret.onFailure(e);
return;
}
}
if (extra.checkCrc != PutExtra.UNUSE_CRC32) m.addField("crc32", extra.crc32 + "");
for (Map.Entry<String, String> i: extra.params.entrySet()) {
m.addField(i.getKey(), i.getValue());
}
m.addField("token", mUptoken);
m.addFile("file", extra.mimeType, key == null ? "?" : key, isa);
Client client = defaultClient();
final Client.ClientExecutor executor = client.makeClientExecutor();
m.setProcessNotify(new IOnProcess() {
@Override
public void onProcess(long current, long total) {
executor.upload(current, total);
}
});
client.call(executor, Conf.UP_HOST, m, ret);
}
/**
* URI
*
* @param mContext
* @param key
* @param uri URI
* @param extra
* @param ret
*/
public void putFile(Context mContext, String key, Uri uri, PutExtra extra, final JSONObjectRet ret) {
if (!uri.toString().startsWith("file")) uri = convertFileUri(mContext, uri);
try {
File file = new File(new URI(uri.toString()));
if (file.exists()) {
putAndClose(key, InputStreamAt.fromFile(file), extra, ret);
return;
}
ret.onFailure(new Exception("file not exist: " + uri.toString()));
} catch (URISyntaxException e) {
e.printStackTrace();
ret.onFailure(e);
}
}
public void putFile(String key, File file, PutExtra extra, JSONObjectRet callback) {
putAndClose(key, InputStreamAt.fromFile(file), extra, callback);
}
public void putAndClose(final String key, final InputStreamAt input, final PutExtra extra, final JSONObjectRet ret) {
put(key, input, extra, new JSONObjectRet() {
@Override
public void onSuccess(JSONObject obj) {
input.close();
ret.onSuccess(obj);
}
@Override
public void onProcess(long current, long total) {
ret.onProcess(current, total);
}
@Override
public void onPause(Object tag) {
ret.onPause(tag);
}
@Override
public void onFailure(Exception ex) {
input.close();
ret.onFailure(ex);
}
});
}
public static Uri convertFileUri(Context mContext, Uri uri) {
String filePath;
if (uri != null && "content".equals(uri.getScheme())) {
Cursor cursor = mContext.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = uri.getPath();
}
return Uri.parse("file://" + filePath);
}
public static void put(String uptoken, String key, InputStreamAt input, PutExtra extra, JSONObjectRet callback) {
new IO(defaultClient(), uptoken).put(key, input, extra, callback);
}
public static void putFile(Context mContext, String uptoken, String key, Uri uri, PutExtra extra, JSONObjectRet callback) {
new IO(defaultClient(), uptoken).putFile(mContext, key, uri, extra, callback);
}
public static void putFile(String uptoken, String key, File file, PutExtra extra, JSONObjectRet callback) {
new IO(defaultClient(), uptoken).putFile(key, file, extra, callback);
}
}
|
package ru.qa.rtsoft;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTests {
@Test
public void testPoint1() {
Point p1 = new Point(2, 3);
Point p2 = new Point(-1, 5);
Assert.assertEquals(p2.distance(p1), 3.605551275463989);
}
@Test
public void testPoint2 () {
Point p1 = new Point(2, 3);
Point p2 = new Point(-1, 5);
Assert.assertEquals(p2.distance(p1), 3);
}
@Test
public void testPoint3 () {
Point p1 = new Point(2, 3);
Point p2 = new Point(2, 3);
Assert.assertEquals(p2.distance(p1), 3);
}
}
|
package algorithms.disjointSets;
/**
* a disjoint set implemented with linked lists.
* each set is a linked list.
*
* based upon pseudocode from "Introduction to Algorithms" by Cormen et al.
*
* @author nichole
*/
public class DisjointSetHelper {
/**
* make a set out of the given node.
* runtime complexity is O(1).
*
* @param x
* @return
*/
public <T> DisjointSet<T> makeSet(DisjointSetNode<T> x) {
x.setRepresentative(x);
DisjointSet<T> list = new DisjointSet<T>();
list.setHead(x);
list.setTail(x);
list.setNumberOfNodes(1);
return list;
}
/**
* find the set representative for the given node.
* runtime complexity is O(1).
* @param x
* @return
*/
public <T> DisjointSetNode<T> findSet(DisjointSetNode<T> x) {
return x.getRepresentative();
}
/**
* append the shorter list onto the end of the longer's list.
* runtime complexity is O(N_shorter).
* @param x
* @param y
* @return
*/
public <T> DisjointSet<T> union(DisjointSet<T> x, DisjointSet<T> y) {
if (x.equals(y)) {
return x;
}
DisjointSet<T> longer, shorter;
if (x.getNumberOfNodes() >= y.getNumberOfNodes()) {
longer = x;
shorter = y;
} else {
longer = y;
shorter = x;
}
// add next references to longer
// longer.tail.next might not be pointing to last of next, so walk to end
if (longer.getTail().getNext() != null) {
DisjointSetNode<T> tmp = longer.getTail().getNext();
while (tmp.getNext() != null) {
tmp = tmp.getNext();
}
longer.setTail(tmp);
}
longer.getTail().setNext(shorter.getHead());
DisjointSetNode<T> latest = shorter.getHead();
while (latest != null) {
latest.setRepresentative(longer.getHead());
latest = latest.getNext();
}
longer.setTail(shorter.getTail());
longer.setNumberOfNodes(longer.getNumberOfNodes() + shorter.getNumberOfNodes());
return longer;
}
public static <T> String print(DisjointSet<T> x) {
DisjointSetNode<T> current = x.getHead();
StringBuilder sb = new StringBuilder();
while (current != null) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(current.getMember().toString());
current = current.getNext();
}
return sb.toString();
}
}
|
package algorithms.imageProcessing;
import algorithms.MultiArrayMergeSort;
import algorithms.compGeometry.EllipseHelper;
import algorithms.compGeometry.PerimeterFinder;
import algorithms.compGeometry.clustering.KMeansPlusPlus;
import algorithms.imageProcessing.util.MatrixUtil;
import algorithms.misc.Histogram;
import algorithms.misc.HistogramHolder;
import algorithms.misc.MiscMath;
import algorithms.util.PairIntArray;
import algorithms.util.PolygonAndPointPlotter;
import algorithms.util.Errors;
import algorithms.util.PairFloat;
import algorithms.util.PairFloatArray;
import algorithms.util.PairInt;
import java.awt.Color;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ejml.simple.SimpleMatrix;
/**
*
* @author nichole
*/
public class ImageProcessor {
protected Logger log = Logger.getLogger(this.getClass().getName());
public void applySobelKernel(Image input) {
IKernel kernel = new SobelX();
Kernel kernelX = kernel.getKernel();
float normX = kernel.getNormalizationFactor();
kernel = new SobelY();
Kernel kernelY = kernel.getKernel();
float normY = kernel.getNormalizationFactor();
applyKernels(input, kernelX, kernelY, normX, normY);
}
public void applySobelKernel(GreyscaleImage input) {
IKernel kernel = new SobelX();
Kernel kernelX = kernel.getKernel();
float normX = kernel.getNormalizationFactor();
kernel = new SobelY();
Kernel kernelY = kernel.getKernel();
float normY = kernel.getNormalizationFactor();
applyKernels(input, kernelX, kernelY, normX, normY);
}
protected void applyKernels(Image input, Kernel kernelX, Kernel kernelY,
float normFactorX, float normFactorY) {
/*
assumes that kernelX is applied to a copy of the img
and kernelY is applied to a separate copy of the img and
then they are added in quadrature for the final result.
*/
Image imgX = input.copyImage();
Image imgY = input.copyImage();
applyKernel(imgX, kernelX, normFactorX);
applyKernel(imgY, kernelY, normFactorY);
Image img2 = combineConvolvedImages(imgX, imgY);
input.resetTo(img2);
}
protected void applyKernels(GreyscaleImage input, Kernel kernelX, Kernel kernelY,
float normFactorX, float normFactorY) {
/*
assumes that kernelX is applied to a copy of the img
and kernelY is applied to a separate copy of the img and
then they are added in quadrature for the final result.
*/
GreyscaleImage imgX = input.copyImage();
GreyscaleImage imgY = input.copyImage();
applyKernel(imgX, kernelX, normFactorX);
applyKernel(imgY, kernelY, normFactorY);
GreyscaleImage img2 = combineConvolvedImages(imgX, imgY);
input.resetTo(img2);
}
public Image combineConvolvedImages(Image imageX, Image imageY) {
Image img2 = new Image(imageX.getWidth(), imageX.getHeight());
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int rX = imageX.getR(i, j);
int gX = imageX.getG(i, j);
int bX = imageX.getB(i, j);
int rY = imageY.getR(i, j);
int gY = imageY.getG(i, j);
int bY = imageY.getB(i, j);
double r = Math.sqrt(rX*rX + rY*rY);
double g = Math.sqrt(gX*gX + gY*gY);
double b = Math.sqrt(bX*bX + bY*bY);
r = (r > 255) ? 255 : r;
g = (g > 255) ? 255 : g;
b = (b > 255) ? 255 : b;
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setRGB(i, j, (int)r, (int)g, (int)b);
}
}
return img2;
}
/**
* process only the green channel and set red and blue to zero
* @param imageX
* @param imageY
* @return
*/
public GreyscaleImage combineConvolvedImages(final GreyscaleImage imageX,
final GreyscaleImage imageY) {
GreyscaleImage img2 = imageX.createWithDimensions();
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int gX = imageX.getValue(i, j);
int gY = imageY.getValue(i, j);
//double g = Math.sqrt(0.5*(gX*gX + gY*gY));
//g = (g > 255) ? 255 : g;
double g = Math.sqrt(gX*gX + gY*gY);
if (g > 255) {
g = 255;
}
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setValue(i, j, (int)g);
}
}
return img2;
}
/**
* apply kernel to input. NOTE, that because the image is composed of
* vectors that should have values between 0 and 255, inclusive, if the
* kernel application results in a value outside of that range, the value
* is reset to 0 or 255.
* @param input
* @param kernel
* @param normFactor
*/
protected void applyKernel(Image input, Kernel kernel, float normFactor) {
int h = (kernel.getWidth() - 1) >> 1;
Image output = new Image(input.getWidth(), input.getHeight());
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
long rValue = 0;
long gValue = 0;
long bValue = 0;
// apply the kernel to pixels centered in (i, j)
for (int col = 0; col < kernel.getWidth(); col++) {
int x = col - h;
int imgX = i + x;
// edge corrections. use replication
if (imgX < 0) {
imgX = -1 * imgX - 1;
} else if (imgX >= input.getWidth()) {
int diff = imgX - input.getWidth();
imgX = input.getWidth() - diff - 1;
}
for (int row = 0; row < kernel.getHeight(); row++) {
int y = row - h;
int imgY = j + y;
// edge corrections. use replication
if (imgY < 0) {
imgY = -1 * imgY - 1;
} else if (imgY >= input.getHeight()) {
int diff = imgY - input.getHeight();
imgY = input.getHeight() - diff - 1;
}
int rPixel = input.getR(imgX, imgY);
int gPixel = input.getG(imgX, imgY);
int bPixel = input.getB(imgX, imgY);
int k = kernel.getValue(col, row);
rValue += k * rPixel;
gValue += k * gPixel;
bValue += k * bPixel;
}
}
rValue *= normFactor;
gValue *= normFactor;
bValue *= normFactor;
if (rValue < 0) {
rValue = 0;
}
if (rValue > 255) {
rValue = 255;
}
if (gValue < 0) {
gValue = 0;
}
if (gValue > 255) {
gValue = 255;
}
if (bValue < 0) {
bValue = 0;
}
if (bValue > 255) {
bValue = 255;
}
output.setRGB(i, j, (int)rValue, (int)gValue, (int)bValue);
}
}
input.resetTo(output);
}
/**
* apply kernel to input. NOTE, that because the image is composed of vectors
* that should have values between 0 and 255, inclusive, if the kernel application
* results in a value outside of that range, the value is reset to 0 or
* 255.
* @param input
* @param kernel
* @param normFactor
*/
protected void applyKernel(GreyscaleImage input, Kernel kernel, float normFactor) {
int h = (kernel.getWidth() - 1) >> 1;
GreyscaleImage output = input.createWithDimensions();
//TODO: consider changing normalization to be similar to Kernel1DHelper
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
long value = 0;
// apply the kernel to pixels centered in (i, j)
for (int col = 0; col < kernel.getWidth(); col++) {
int x = col - h;
int imgX = i + x;
// edge corrections. use replication
if (imgX < 0) {
imgX = -1 * imgX - 1;
} else if (imgX >= input.getWidth()) {
int diff = imgX - input.getWidth();
imgX = input.getWidth() - diff - 1;
}
for (int row = 0; row < kernel.getHeight(); row++) {
int y = row - h;
int imgY = j + y;
// edge corrections. use replication
if (imgY < 0) {
imgY = -1 * imgY - 1;
} else if (imgY >= input.getHeight()) {
int diff = imgY - input.getHeight();
imgY = input.getHeight() - diff - 1;
}
int pixel = input.getValue(imgX, imgY);
int k = kernel.getValue(col, row);
value += k * pixel;
}
}
value *= normFactor;
if (value < 0) {
value = 0;
}
if (value > 255) {
value = 255;
}
output.setValue(i, j, (int)value);
}
}
input.resetTo(output);
}
public Image computeTheta(Image convolvedX, Image convolvedY) {
Image output = new Image(convolvedX.getWidth(), convolvedX.getHeight());
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double rX = convolvedX.getR(i, j);
double gX = convolvedX.getG(i, j);
double bX = convolvedX.getB(i, j);
double rY = convolvedY.getR(i, j);
double gY = convolvedY.getG(i, j);
double bY = convolvedY.getB(i, j);
int thetaR = calculateTheta(rX, rY);
int thetaG = calculateTheta(gX, gY);
int thetaB = calculateTheta(bX, bY);
output.setRGB(i, j, thetaR, thetaG, thetaB);
}
}
return output;
}
public GreyscaleImage computeTheta(final GreyscaleImage convolvedX,
final GreyscaleImage convolvedY) {
GreyscaleImage output = convolvedX.createWithDimensions();
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double gX = convolvedX.getValue(i, j);
double gY = convolvedY.getValue(i, j);
int thetaG = calculateTheta(gX, gY);
output.setValue(i, j, thetaG);
}
}
return output;
}
public GreyscaleImage subtractImages(final GreyscaleImage image,
final GreyscaleImage subtrImage) {
if (image.getWidth() != subtrImage.getWidth()) {
throw new IllegalArgumentException("image widths must be the same");
}
if (image.getHeight() != subtrImage.getHeight()) {
throw new IllegalArgumentException("image heights must be the same");
}
GreyscaleImage output = image.createWithDimensions();
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int diff = image.getValue(i, j) - subtrImage.getValue(i, j);
output.setValue(i, j, diff);
}
}
return output;
}
protected int calculateTheta(double gradientX, double gradientY) {
if (gradientX == 0 && (gradientY != 0)) {
return 90;
}
if (gradientY == 0) {
return 0;
}
double div = gradientY/gradientX;
double theta = Math.atan(div)*180./Math.PI;
int angle = (int)theta;
// +x, +y -> +
// -x, +y -> -
// -x, -y -> +
// +x, -y -> -
if (!(gradientX < 0) && !(gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if ((gradientX < 0) && !(gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
} else if ((gradientX < 0) && (gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if (!(gradientX < 0) && (gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
}
return angle;
}
/**
* images bounded by zero's have to be shrunk to the columns and rows
* of the first non-zeroes in order to keep the lines that should be
* attached to the image edges from eroding completely.
*
* @param input
* @return
*/
public int[] shrinkImageToFirstNonZeros(final GreyscaleImage input) {
int xNZFirst = -1;
int xNZLast = -1;
int yNZFirst = -1;
int yNZLast = -1;
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
xNZFirst = i;
break;
}
}
if (xNZFirst > -1) {
break;
}
}
for (int j = 0; j < input.getHeight(); j++) {
for (int i = 0; i < input.getWidth(); i++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZFirst = j;
break;
}
}
if (yNZFirst > -1) {
break;
}
}
for (int i = (input.getWidth() - 1); i > -1; i
for (int j = (input.getHeight() - 1); j > -1; j
if (input.getValue(i, j) > 0) {
xNZLast = i;
break;
}
}
if (xNZLast > -1) {
break;
}
}
for (int j = (input.getHeight() - 1); j > -1; j
for (int i = (input.getWidth() - 1); i > -1; i
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZLast = j;
break;
}
}
if (yNZLast > -1) {
break;
}
}
if ((xNZFirst > 0) || (xNZLast < (input.getWidth() - 1))
|| (yNZFirst > 0) || (yNZLast < (input.getHeight() - 1))) {
//add a 2 pix border
xNZFirst -= 2;
yNZFirst -= 2;
if (xNZFirst < 0) {
xNZFirst = 0;
}
if (yNZFirst < 0) {
yNZFirst = 0;
}
if (xNZLast == -1) {
xNZLast = input.getWidth() - 1;
} else if (xNZLast < (input.getWidth() - 2)) {
// add a 1 pix border
xNZLast += 2;
} else if (xNZLast < (input.getWidth() - 1)) {
// add a 1 pix border
xNZLast++;
}
if (yNZLast == -1) {
yNZLast = input.getHeight() - 1;
} else if (yNZLast < (input.getHeight() - 2)) {
// add a 1 pix border
yNZLast += 2;
} else if (yNZLast < (input.getHeight() - 1)) {
// add a 1 pix border
yNZLast++;
}
int xLen = xNZLast - xNZFirst + 1;
int yLen = yNZLast - yNZFirst + 1;
GreyscaleImage output = new GreyscaleImage(xLen, yLen);
output.setXRelativeOffset(xNZFirst);
output.setYRelativeOffset(yNZFirst);
for (int i = xNZFirst; i <= xNZLast; i++) {
int iIdx = i - xNZFirst;
for (int j = yNZFirst; j <= yNZLast; j++) {
int jIdx = j - yNZFirst;
output.setValue(iIdx, jIdx, input.getValue(i, j));
}
}
input.resetTo(output);
return new int[]{xNZFirst, yNZFirst};
}
return new int[]{0, 0};
}
public void shrinkImage(final GreyscaleImage input,
int[] offsetsAndDimensions) {
//xOffset, yOffset, width, height
GreyscaleImage output = new GreyscaleImage(offsetsAndDimensions[2],
offsetsAndDimensions[3]);
output.setXRelativeOffset(offsetsAndDimensions[0]);
output.setYRelativeOffset(offsetsAndDimensions[1]);
int x = 0;
for (int col = offsetsAndDimensions[0]; col < offsetsAndDimensions[2];
col++) {
int y = 0;
for (int row = offsetsAndDimensions[1]; row < offsetsAndDimensions[3];
row++) {
int v = input.getValue(col, row);
output.setValue(x, y, v);
y++;
}
x++;
}
}
public void applyImageSegmentation(GreyscaleImage input, int kBands)
throws IOException, NoSuchAlgorithmException {
KMeansPlusPlus instance = new KMeansPlusPlus();
instance.computeMeans(kBands, input);
int[] binCenters = instance.getCenters();
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
for (int i = 0; i < binCenters.length; i++) {
int vc = binCenters[i];
int bisectorBelow = ((i - 1) > -1) ?
((binCenters[i - 1] + vc) / 2) : 0;
int bisectorAbove = ((i + 1) > (binCenters.length - 1)) ?
255 : ((binCenters[i + 1] + vc) / 2);
if ((v >= bisectorBelow) && (v <= bisectorAbove)) {
input.setValue(col, row, vc);
break;
}
}
}
}
}
public void convertToBinaryImage(GreyscaleImage input) {
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
if (v != 0) {
input.setValue(col, row, 1);
}
}
}
}
/**
* using the gradient's theta image, find the sky as the largest set of
* contiguous 0 values and apply the edge filter to it to reduce the
* boundary to a single pixel curve.
*
* NOTE that the theta image has a boundary that has been increased by
* the original image blur and then the difference of gaussians to make
* the gradient, so the distance of the skyline from the real image horizon
* is several pixels.
* For example, the canny edge filter used in "outdoorMode" results in
* gaussian kernels applied twice to give an effective sigma of
* sqrt(2*2 + 0.5*0.5) = 2.1. The FWHM of such a spread is then
* 2.355*2.1 = 6 pixels. The theta image skyline is probably blurred to a
* width larger than the combined FWHM, however, making it 7 or 8 pixels.
* Therefore, it's recommended that the image returned from this be followed
* with: edge extraction; then fit the edges to the intermediate canny edge
* filter product (the output of the 2 layer filter) by making a translation
* of the extracted skyline edge until the correlation with the filter2
* image is highest (should be within 10 pixel shift). Because this
* method does not assume orientation of the image, the invoker needs
* to also retrieve the centroid of the sky, so that is also returned
* in an output variable given in the arguments.
*
* @param theta
* @param gradientXY
* @param originalImage
* @param outputSkyCentroid container to hold the output centroid of
* the sky.
* @param edgeSettings
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public GreyscaleImage createSkyline(GreyscaleImage theta,
GreyscaleImage gradientXY, Image originalImage,
CannyEdgeFilterSettings edgeSettings, PairIntArray outputSkyCentroid)
throws IOException, NoSuchAlgorithmException {
GreyscaleImage mask = createBestSkyMask(theta, gradientXY, originalImage,
edgeSettings, outputSkyCentroid);
if (mask != null) {
multiply(mask, 255);
CannyEdgeFilter filter = new CannyEdgeFilter();
filter.setFilterImageTrim(theta.getXRelativeOffset(),
theta.getYRelativeOffset(), theta.getWidth(),
theta.getHeight());
filter.applyFilter(mask);
return mask;
}
return null;
}
/**
* NOT READY FOR USE YET.
*
* @param theta
* @return
*/
public GreyscaleImage createRoughSkyMask(GreyscaleImage theta) throws
IOException, NoSuchAlgorithmException {
if (theta == null) {
throw new IllegalArgumentException("theta cannot be null");
}
theta = theta.copyImage();
applyImageSegmentation(theta, 2);
subtractMinimum(theta);
convertToBinaryImage(theta);
removeSpurs(theta);
throw new UnsupportedOperationException("not ready for use yet");
//return theta;
}
protected int determineBinFactorForSkyMask(int numberOfThetaPixels) {
//TODO: this can be adjusted by the jvm settings for stack size
int defaultLimit = 87000;
if (numberOfThetaPixels <= defaultLimit) {
return 1;
}
double a = (double)numberOfThetaPixels/87000.;
// rounds down
int f2 = (int)a/2;
int binFactor = f2 * 2;
if ((a - binFactor) > 0) {
binFactor += 2;
}
return binFactor;
}
/**
* NOT READY FOR USE
*
* create a mask for what is interpreted as sky in the image and return
* a mask with 0's for sky and 1's for non-sky.
*
* Internally, the method looks at contiguous regions of zero value pixels
* in the theta image and it looks at color in the original image.
* The camera image plane can have a rotation such that the
* horizon might not be along rows in the image, that is the method
* looks for sky that is not necessarily at the top of the image, but
* should be on the boundary of the image
* (note that reflection of sky can be found the same way, but this
* method does not try to find sky that is not on the boundary of the
* image).
* (the "boundary" logic may change, in progress...)
*
* Note that if the image contains a silhouette of featureless
* foreground and a sky full of clouds, the method will interpret the
* foreground as sky so it is up to the invoker to invert the mask.
*
* NOTE: the cloud finding logic will currently fail if originalColorImage
* is black and white.
*
* @param theta
* @param gradientXY
* @param originalColorImage
* @param edgeSettings
* @param outputSkyCentroid container to hold the output centroid of
* the sky.
* @return
* @throws java.io.IOException
* @throws java.security.NoSuchAlgorithmException
*/
public GreyscaleImage createBestSkyMask(final GreyscaleImage theta,
GreyscaleImage gradientXY,
Image originalColorImage, CannyEdgeFilterSettings edgeSettings,
PairIntArray outputSkyCentroid) throws
IOException, NoSuchAlgorithmException {
if (theta == null) {
throw new IllegalArgumentException("theta cannot be null");
}
Image colorImg = originalColorImage;
GreyscaleImage thetaImg = theta;
GreyscaleImage gXYImg = gradientXY;
int binFactor = determineBinFactorForSkyMask(theta.getNPixels());
log.info("binFactor=" + binFactor);
if (binFactor > 1) {
thetaImg = binImage(theta, binFactor);
colorImg = binImage(originalColorImage, binFactor);
gXYImg = binImage(gradientXY, binFactor);
}
List<PairIntArray> zeroPointLists = getSortedContiguousZeros(thetaImg);
if (zeroPointLists.isEmpty()) {
GreyscaleImage mask = theta.createWithDimensions();
// return an image of all 1's
mask.fill(1);
return mask;
}
// now the coordinates in zeroPointLists are w.r.t. thetaImg
removeSetsThatAreDark(zeroPointLists, colorImg, thetaImg,
true, 0);
//TODO: assumes that largest smooth component of image is sky.
// if sky is small and a foreground object is large and featureless
// and not found as dark, this will fail.
// will adjust for that one day, possibly with color validation
reduceToLargest(zeroPointLists);
double[] avgYRGB = calculateYRGB(zeroPointLists.get(0), colorImg,
thetaImg.getXRelativeOffset(), thetaImg.getYRelativeOffset(),
true, 0);
removeHighContrastPoints(zeroPointLists, colorImg,
thetaImg, avgYRGB[0], true, 0);
if (zeroPointLists.isEmpty()) {
GreyscaleImage mask = theta.createWithDimensions();
// return an image of all 1's
mask.fill(1);
return mask;
}
Set<PairInt> points = combine(zeroPointLists);
int valueToSubtract = extractSkyFromGradientXY(gXYImg, points);
if (binFactor > 1) {
thetaImg = theta;
colorImg = originalColorImage;
gXYImg = gradientXY;
points = unbinZeroPointLists(points, binFactor);
//TODO: note, this might be better handled by the later
// "grow to skyline"
//correct for resolution, with the gradientXY minus valueToSubtract
addBackMissingZeros(points, gXYImg, binFactor, valueToSubtract);
}
findSunAndAddToSkyPoints(points, originalColorImage,
thetaImg.getXRelativeOffset(), thetaImg.getYRelativeOffset());
//removeConnectedClouds(points, clr);
/*
avgYRGB = calculateYRGB(zeroPointLists.get(0), originalColorImage,
theta.getXRelativeOffset(), theta.getYRelativeOffset(),
makeCorrectionsAlongX, convDispl);
*/
//gradientXY = subtractThresholdLevel(gradientXY);
//removeClouds(points, thetaImg, originalColorImage,
// makeCorrectionsAlongX, convDispl,
// (int)avgYRGB[1], (int)avgYRGB[2], (int)avgYRGB[3]);
//growZeroValuePoints(points, gradientXY);
GreyscaleImage mask = gradientXY.createWithDimensions();
mask.fill(1);
for (PairInt p : points) {
int x = p.getX();
int y = p.getY();
mask.setValue(x, y, 0);
}
//GreyscaleImage mask = growPointsToSkyline(points, originalColorImage,
// theta, avgYRGB, makeCorrectionsAlongX, convDispl);
MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper();
double[] xycen = curveHelper.calculateXYCentroids(points);
outputSkyCentroid.add((int)Math.round(xycen[0]), (int)Math.round(xycen[1]));
if (mask != null) {
// removeSpurs(mask);
}
return mask;
}
public Set<PairInt> combine(List<PairIntArray> points) {
Set<PairInt> set = new HashSet<PairInt>();
for (PairIntArray p : points) {
for (int i = 0; i < p.getN(); i++) {
int x = p.getX(i);
int y = p.getY(i);
PairInt pi = new PairInt(x, y);
set.add(pi);
}
}
return set;
}
public List<PairIntArray> getLargestSortedContiguousZeros(GreyscaleImage theta) {
return getSortedContiguousValues(theta, 0, false, true);
}
public List<PairIntArray> getSortedContiguousZeros(GreyscaleImage theta) {
return getSortedContiguousValues(theta, 0, false, false);
}
public List<PairIntArray> getLargestSortedContiguousNonZeros(GreyscaleImage theta) {
return getSortedContiguousValues(theta, 0, true, true);
}
private List<PairIntArray> getSortedContiguousValues(GreyscaleImage theta,
int value, boolean excludeValue, boolean limitToLargest) {
DFSContiguousValueFinder zerosFinder = new DFSContiguousValueFinder(theta);
if (excludeValue) {
zerosFinder.findGroupsNotThisValue(value);
} else {
zerosFinder.findGroups(value);
}
int nGroups = zerosFinder.getNumberOfGroups();
if (nGroups == 0) {
return new ArrayList<PairIntArray>();
}
int[] groupIndexes = new int[nGroups];
int[] groupN = new int[nGroups];
for (int gId = 0; gId < nGroups; gId++) {
int n = zerosFinder.getNumberofGroupMembers(gId);
groupIndexes[gId] = gId;
groupN[gId] = n;
}
MultiArrayMergeSort.sortByDecr(groupN, groupIndexes);
List<Integer> groupIds = new ArrayList<Integer>();
groupIds.add(Integer.valueOf(groupIndexes[0]));
if (nGroups > 1) {
float n0 = (float)groupN[0];
for (int i = 1; i < groupN.length; i++) {
if (limitToLargest) {
float number = groupN[i];
float frac = number/n0;
System.out.println(number);
//TODO: this should be adjusted by some metric.
// a histogram?
// since most images should have been binned to <= 300 x 300 pix,
// making an assumption about a group >= 100 pixels
if ((1 - frac) < 0.4) {
//if (number > 100) {
groupIds.add(Integer.valueOf(groupIndexes[i]));
} else {
break;
}
} else {
groupIds.add(Integer.valueOf(groupIndexes[i]));
}
}
}
List<PairIntArray> list = new ArrayList<PairIntArray>();
for (Integer gIndex : groupIds) {
int gIdx = gIndex.intValue();
PairIntArray points = zerosFinder.getXY(gIdx);
list.add(points);
}
return list;
}
public void multiply(GreyscaleImage input, float m) {
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
int f = (int)(m * v);
input.setValue(col, row, f);
}
}
}
public void subtractMinimum(GreyscaleImage input) {
int min = MiscMath.findMin(input.getValues());
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
int f = v - min;
input.setValue(col, row, f);
}
}
}
/**
* multiply these images, that is pixel by pixel multiplication.
* No corrections are made for integer overflow.
* @param input1
* @param input2
* @return
*/
public GreyscaleImage multiply(GreyscaleImage input1, GreyscaleImage input2) {
if (input1 == null) {
throw new IllegalArgumentException("input1 cannot be null");
}
if (input2 == null) {
throw new IllegalArgumentException("input2 cannot be null");
}
if (input1.getWidth() != input2.getWidth()) {
throw new IllegalArgumentException(
"input1 and input2 must have same widths");
}
if (input1.getHeight()!= input2.getHeight()) {
throw new IllegalArgumentException(
"input1 and input2 must have same heights");
}
GreyscaleImage output = input1.createWithDimensions();
for (int col = 0; col < input1.getWidth(); col++) {
for (int row = 0; row < input1.getHeight(); row++) {
int v = input1.getValue(col, row) * input2.getValue(col, row);
output.setValue(col, row, v);
}
}
return output;
}
/**
* compare each pixel and set output to 0 if both inputs are 0, else set
* output to 1.
* @param input1
* @param input2
* @return
*/
public GreyscaleImage binaryOr(GreyscaleImage input1, GreyscaleImage input2) {
if (input1 == null) {
throw new IllegalArgumentException("input1 cannot be null");
}
if (input2 == null) {
throw new IllegalArgumentException("input2 cannot be null");
}
if (input1.getWidth() != input2.getWidth()) {
throw new IllegalArgumentException(
"input1 and input2 must have same widths");
}
if (input1.getHeight()!= input2.getHeight()) {
throw new IllegalArgumentException(
"input1 and input2 must have same heights");
}
GreyscaleImage output = input1.createWithDimensions();
for (int col = 0; col < input1.getWidth(); col++) {
for (int row = 0; row < input1.getHeight(); row++) {
int v1 = input1.getValue(col, row);
int v2 = input2.getValue(col, row);
if ((v1 != 0) || (v2 != 0)) {
output.setValue(col, row, 1);
}
}
}
return output;
}
public void blur(GreyscaleImage input, float sigma) {
float[] kernel = Gaussian1D.getKernel(sigma);
Kernel1DHelper kernel1DHelper = new Kernel1DHelper();
GreyscaleImage output = input.createWithDimensions();
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, true);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, false);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
}
public void divideByBlurredSelf(GreyscaleImage input, float sigma) {
GreyscaleImage input2 = input.copyImage();
blur(input, sigma);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int v = input.getValue(i, j);
int vorig = input2.getValue(i, j);
if (v != 0) {
float r = (float)vorig/(float)v;
if ((i==250) && (j >= 50) && (j <= 150)) {
log.info(Float.toString(r));
}
input.setValue(i, j, (int)(100*r));
}
}
}
}
/**
* make a binary mask with the given zeroCoords as a group of starter points
* for the mask and also set to '0' any points within zeroCoords' bounds.
*
* @param theta
* @param zeroCoords
* @return
*/
public GreyscaleImage createMask(GreyscaleImage theta, PairIntArray zeroCoords) {
GreyscaleImage out = theta.createWithDimensions();
out.fill(1);
for (int pIdx = 0; pIdx < zeroCoords.getN(); pIdx++) {
int x = zeroCoords.getX(pIdx);
int y = zeroCoords.getY(pIdx);
out.setValue(x, y, 0);
}
return out;
}
/**
* make a binary mask with the given zeroCoords as a group of starter points
* for the mask and also set to '0' any points within zeroCoords' bounds.
*
* @param theta
* @param nonzeroCoords
* @return
*/
public GreyscaleImage createInvMask(GreyscaleImage theta,
PairIntArray nonzeroCoords) {
GreyscaleImage out = theta.createWithDimensions();
for (int pIdx = 0; pIdx < nonzeroCoords.getN(); pIdx++) {
int x = nonzeroCoords.getX(pIdx);
int y = nonzeroCoords.getY(pIdx);
out.setValue(x, y, 1);
}
return out;
}
/**
* this is meant to operate on an image with only 0's and 1's
* @param input
*/
public void removeSpurs(GreyscaleImage input) {
int width = input.getWidth();
int height = input.getHeight();
int nIterMax = 1000;
int nIter = 0;
int numRemoved = 1;
while ((nIter < nIterMax) && (numRemoved > 0)) {
numRemoved = 0;
for (int col = 0; col < input.getWidth(); col++) {
if ((col < 2) || (col > (width - 3))) {
continue;
}
for (int row = 0; row < input.getHeight(); row++) {
if ((row < 2) || (row > (height - 3))) {
continue;
}
int v = input.getValue(col, row);
if (v == 0) {
continue;
}
// looking for pixels having only one neighbor who subsequently
// has only 1 or 2 neighbors
// as long as neither are connected to image boundaries
int neighborIdx = getIndexIfOnlyOneNeighbor(input, col, row);
if (neighborIdx > -1) {
int neighborX = input.getCol(neighborIdx);
int neighborY = input.getRow(neighborIdx);
int nn = count8RegionNeighbors(input, neighborX, neighborY);
if (nn <= 2) {
input.setValue(col, row, 0);
numRemoved++;
}
} else {
int n = count8RegionNeighbors(input, col, row);
if (n == 0) {
input.setValue(col, row, 0);
numRemoved++;
}
}
}
}
log.info("numRemoved=" + numRemoved + " nIter=" + nIter);
nIter++;
}
if (nIter > 30) {
try {
multiply(input, 255);
ImageDisplayer.displayImage("segmented for sky", input);
int z = 1;
} catch (IOException ex) {
Logger.getLogger(ImageProcessor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
protected int count8RegionNeighbors(GreyscaleImage input, int x, int y) {
int width = input.getWidth();
int height = input.getHeight();
int count = 0;
for (int c = (x - 1); c <= (x + 1); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - 1); r <= (y + 1); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int v = input.getValue(c, r);
if (v > 0) {
count++;
}
}
}
return count;
}
protected int getIndexIfOnlyOneNeighbor(GreyscaleImage input, int x, int y) {
int width = input.getWidth();
int height = input.getHeight();
int count = 0;
int xNeighbor = -1;
int yNeighbor = -1;
for (int c = (x - 1); c <= (x + 1); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - 1); r <= (y + 1); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int v = input.getValue(c, r);
if (v > 0) {
if (count > 0) {
return -1;
}
xNeighbor = c;
yNeighbor = r;
count++;
}
}
}
if (count == 0) {
return -1;
}
int index = input.getIndex(xNeighbor, yNeighbor);
return index;
}
/**
* returns avg r, avg g, avg b
* @param points
* @param theta
* @param originalImage
* @param addAlongX
* @param addAmount
* @return
*/
private int[] getAvgMinMaxColor(PairIntArray points, GreyscaleImage theta,
Image originalImage, boolean addAlongX, int addAmount) {
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
double rSum = 0;
double gSum = 0;
double bSum = 0;
int count = 0;
for (int pIdx = 0; pIdx < points.getN(); pIdx++) {
int x = points.getX(pIdx);
int y = points.getY(pIdx);
int ox = x + xOffset;
int oy = y + yOffset;
//TODO: this may need corrections for other orientations
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalImage.getHeight() - 1))) {
continue;
}
int rgb = originalImage.getRGB(ox, oy);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
rSum += r;
gSum += g;
bSum += b;
count++;
}
if (count == 0) {
return new int[]{0, 0, 0};
}
rSum /= (double)count;
gSum /= (double)count;
bSum /= (double)count;
return new int[]{(int)Math.round(rSum), (int)Math.round(gSum),
(int)Math.round(bSum)};
}
/**
* look for gaps in zeroValuePoints and if the color of the points within
* the originalImage appears to be whiter than sky, consider the points
* to be clouds. cloud points are then added to zeroValuePoints because
* it's known that zeroValuePoints is subsequently used to mask out pixels
* that should not be used for a skyline edge (and hence corners).
*
* NOTE: this makes a correction for gaussian blurring, that is subtracting
* the 6 pixels from convolving w/ gaussian of sigma=2, then sigma=0.5
* which is what happens when "outdoorMode" is used to create the theta
* image.
*
* Note, this method won't find the clouds which are touching the horizon.
* The Brown & Lowe 2003 panoramic images of a snowy mountain shows
* 2 examples of complications with cloud removal.
* To the far left on the mountain horizon, one can see that clouds do
* obscure the mountain, and in the middle of the horizon of image,
* one can see that clouds and the mountain peak are surrounded by
* sky to left and right, though not completely below.
* In those cases where the clouds are touching the horizon, one probably
* wants to wait until have registered more than one image to understand
* motion and hence how to identify the clouds.
*
* @param points
* @param theta
* @param originalImage
* @return
*/
private void removeClouds(Set<PairInt> zeroValuePoints, GreyscaleImage theta,
Image originalImage, boolean addAlongX, int addAmount,
int rSky, int gSky, int bSky) {
/*
find the gaps in the set zeroValuePoints and determine if their
color is whiteish compared to the background sky or looks like the
background sky too.
easiest way, though maybe not fastest:
-- determine min and max of x and y of zeroValuePoints.
-- scan along each row to find the start column of the row and the
end column of the row.
-- repeat the scan of the row only within column boundaries and
search for each point in zeroValuePoints
-- if it is not present in zeroValuePoints,
check the originalImage value. if it is white with respect
to rgbSky, add it to zeroValuePoints
Can see that snowy mountain tops may be removed, so need to add to
the block within the row scan, a scan above and below the possible
cloud pixel to make sure that it is enclosed by sky pixels above
and below too.
would like to make a fast search of zeroValuePoints so using pixel index
as main data and putting all into a hash set
*/
if (zeroValuePoints.isEmpty()) {
return;
}
int xMin = Integer.MAX_VALUE;
int xMax = Integer.MIN_VALUE;
int yMin = Integer.MAX_VALUE;
int yMax = Integer.MIN_VALUE;
Set<Integer> zpSet = new HashSet<Integer>();
for (PairInt p : zeroValuePoints) {
int x = p.getX();
int y = p.getY();
int idx = theta.getIndex(x, y);
zpSet.add(Integer.valueOf(idx));
}
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
/*
blue sky: 143, 243, 253
white clouds on blue sky: 192, 242, 248 (increased red, roughly same blue)
red sky:
white clouds on red sky: (increased blue and green, roughly same red)
*/
boolean skyIsBlue = (bSky > rSky);
for (int row = yMin; row <= yMax; row++) {
int start = -1;
int stop = 0;
for (int col = xMin; col <= xMax; col++) {
int idx = theta.getIndex(col, row);
if (zpSet.contains(Integer.valueOf(idx))) {
stop = col;
if (start == -1) {
start = col;
}
}
}
if (start == -1) {
continue;
}
// any pixels not in set are potentially cloud pixels
for (int col = start; col <= stop; col++) {
int idx = theta.getIndex(col, row);
if (!zpSet.contains(Integer.valueOf(idx))) {
int x = theta.getCol(idx);
int y = theta.getRow(idx);
int ox = x + xOffset;
int oy = y + yOffset;
//TODO: this may need corrections for other orientations
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalImage.getHeight() - 1))) {
continue;
}
int red = originalImage.getR(ox, oy);
int green = originalImage.getG(ox, oy);
int blue = originalImage.getB(ox, oy);
// is it white or near the color?
boolean looksLikeACloudPixel = false;
boolean looksLikeASkyPixel = false;
looksLikeACloudPixel = ((blue >= bSky) && (red >= rSky)
&& (green >= gSky) &&
((skyIsBlue && (blue > bSky) && (green > gSky))
||
(!skyIsBlue && (red > rSky))));
if (skyIsBlue && !looksLikeACloudPixel) {
// expect blue ~ b, but red > r
int db = Math.abs(blue - bSky);
int dr = red - rSky;
// if dr is < 0, it's 'bluer', hence similar to sky
if ((db < 10) && (dr > 25)) {
// could be dark part of cloud, but could also be
// a rock formation for example
/*if ((((double)blue/(double)green) < 0.1) &&
(((double)blue/(double)red) > 2.)) {
looksLikeACloudPixel = true;
}*/
} else if ((dr < 0) && (db >= 0)) {
if ((green - gSky) > 0) {
looksLikeASkyPixel = true;
}
}
} else if (!looksLikeACloudPixel) {
// expect red ~ r, but blue > b and green > g
int dr = Math.abs(red - rSky);
int db = blue - bSky;
int dg = green - gSky;
if ((dr < 10) && (db > 25) && (dg > 25)) {
looksLikeACloudPixel = true;
} else if ((db < 0) && (dr >= 0)) {
if ((green - gSky) < 0) {
looksLikeASkyPixel = true;
}
}
}
if (looksLikeASkyPixel) {
PairInt p = new PairInt(col, row);
zeroValuePoints.add(p);
zpSet.add(Integer.valueOf(idx));
if (col < xMin) {
xMin = col;
}
if (col > xMax) {
xMax = col;
}
if (row < yMin) {
yMin = row;
}
if (row > yMax) {
yMax = row;
}
continue;
}
if (looksLikeACloudPixel) {
//further scan up and down to make sure enclosed by sky
boolean foundSkyPixel = false;
// search for sky pixel above current (that is, lower y)
if ((row - 1) == -1) {
foundSkyPixel = true;
}
if (!foundSkyPixel) {
for (int rowI = (row - 1); rowI >= yMin; rowI
int idxI = theta.getIndex(col, rowI);
if (zpSet.contains(Integer.valueOf(idxI))) {
foundSkyPixel = true;
break;
}
}
}
if (!foundSkyPixel) {
continue;
}
// search below for sky pixels, that is search higher y
foundSkyPixel = false;
if ((row + 1) == theta.getHeight()) {
foundSkyPixel = true;
}
if (!foundSkyPixel) {
for (int rowI = (row + 1); rowI <= yMax; rowI++) {
int idxI = theta.getIndex(col, rowI);
if (zpSet.contains(Integer.valueOf(idxI))) {
foundSkyPixel = true;
break;
}
}
}
if (!foundSkyPixel) {
// might be the peak of a snowy mountain
continue;
}
// this looks like a cloud pixel, so region should be
// considered 'sky'
PairInt p = new PairInt(col, row);
zeroValuePoints.add(p);
}
}
}
}
}
public GreyscaleImage binImageToKeepZeros(GreyscaleImage img,
int binFactor) {
if (img == null) {
throw new IllegalArgumentException("img cannot be null");
}
int w0 = img.getWidth();
int h0 = img.getHeight();
int w1 = w0/binFactor;
int h1 = h0/binFactor;
GreyscaleImage out = new GreyscaleImage(w1, h1);
out.setXRelativeOffset(Math.round(img.getXRelativeOffset()/2.f));
out.setYRelativeOffset(Math.round(img.getYRelativeOffset()/2.f));
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
int vSum = 0;
int count = 0;
boolean isZero = false;
// if there's a zero in the binFactor x binFactor block,
// v is set to 0
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
if ((ii < 0) || (ii > (w0 - 1))) {
continue;
}
if ((jj < 0) || (jj > (h0 - 1))) {
continue;
}
int v = img.getValue(ii, jj);
if (v == 0) {
isZero = true;
vSum = 0;
break;
}
vSum += v;
count++;
}
if (isZero) {
break;
}
}
if (vSum > 0) {
float v = (float)vSum/(float)count;
vSum = Math.round(v);
}
out.setValue(i, j, vSum);
}
}
return out;
}
public GreyscaleImage binImage(GreyscaleImage img,
int binFactor) {
if (img == null) {
throw new IllegalArgumentException("img cannot be null");
}
int w0 = img.getWidth();
int h0 = img.getHeight();
int w1 = w0/binFactor;
int h1 = h0/binFactor;
GreyscaleImage out = new GreyscaleImage(w1, h1);
out.setXRelativeOffset(Math.round(img.getXRelativeOffset()/2.f));
out.setYRelativeOffset(Math.round(img.getYRelativeOffset()/2.f));
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
int vSum = 0;
int count = 0;
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
if ((ii < 0) || (ii > (w0 - 1))) {
continue;
}
if ((jj < 0) || (jj > (h0 - 1))) {
continue;
}
int v = img.getValue(ii, jj);
vSum += v;
count++;
}
}
if (count > 0) {
float v = (float)vSum/(float)count;
vSum = Math.round(v);
}
out.setValue(i, j, vSum);
}
}
return out;
}
public Image binImage(Image img, int binFactor) {
if (img == null) {
throw new IllegalArgumentException("img cannot be null");
}
int w0 = img.getWidth();
int h0 = img.getHeight();
int w1 = w0/binFactor;
int h1 = h0/binFactor;
Image out = new Image(w1, h1);
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
long rSum = 0;
long gSum = 0;
long bSum = 0;
int count = 0;
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
if ((ii < 0) || (ii > (w0 - 1))) {
continue;
}
if ((jj < 0) || (jj > (h0 - 1))) {
continue;
}
int rgb = img.getRGB(ii, jj);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
rSum += r;
gSum += g;
bSum += b;
count++;
}
}
if (count > 0) {
rSum = Math.round((float)rSum/(float)count);
gSum = Math.round((float)gSum/(float)count);
bSum = Math.round((float)bSum/(float)count);
}
out.setRGB(i, j, (int)rSum, (int)gSum, (int)bSum);
}
}
return out;
}
public GreyscaleImage unbinMask(GreyscaleImage mask, int binFactor,
GreyscaleImage originalTheta) {
if (mask == null) {
throw new IllegalArgumentException("mask cannot be null");
}
if (originalTheta == null) {
throw new IllegalArgumentException("originalTheta cannot be null");
}
GreyscaleImage out = originalTheta.createWithDimensions();
int w0 = mask.getWidth();
int h0 = mask.getHeight();
int w1 = out.getWidth();
int h1 = out.getHeight();
for (int i = 0; i < w0; i++) {
for (int j = 0; j < h0; j++) {
int v = mask.getValue(i, j);
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
out.setValue(ii, jj, v);
}
}
}
}
if ((originalTheta.getWidth() & 1) == 1) {
// copy next to last column into last column
int i = originalTheta.getWidth() - 2;
for (int j = 0; j < h1; j++) {
int v = out.getValue(i, j);
out.setValue(i + 1, j, v);
}
}
if ((originalTheta.getHeight() & 1) == 1) {
// copy next to last row into last row
int j = originalTheta.getHeight() - 2;
for (int i = 0; i < w1; i++) {
int v = out.getValue(i, j);
out.setValue(i, j + 1, v);
}
}
// TODO: consider correction for oversampling at location of skyline
// using originalTheta
return out;
}
private List<PairIntArray> unbinZeroPointLists(List<PairIntArray> zeroPointLists,
int binFactor) {
if (zeroPointLists == null) {
throw new IllegalArgumentException("mask cannot be null");
}
List<PairIntArray> output = new ArrayList<PairIntArray>();
for (PairIntArray zeroPointList : zeroPointLists) {
PairIntArray transformed = new PairIntArray(zeroPointList.getN() *
binFactor);
for (int i = 0; i < zeroPointList.getN(); i++) {
int x = zeroPointList.getX(i);
int y = zeroPointList.getY(i);
for (int ii = (x*binFactor); ii < ((x + 1)*binFactor); ii++) {
for (int jj = (y*binFactor); jj < ((y + 1)*binFactor); jj++) {
transformed.add(ii, jj);
}
}
}
output.add(transformed);
}
return output;
}
private Set<PairInt> unbinZeroPointLists(Set<PairInt> zeroPoints,
int binFactor) {
if (zeroPoints == null) {
throw new IllegalArgumentException("zeroPoints cannot be null");
}
Set<PairInt> output = new HashSet<PairInt>();
for (PairInt zeroPoint : zeroPoints) {
int x = zeroPoint.getX();
int y = zeroPoint.getY();
for (int ii = (x*binFactor); ii < ((x + 1)*binFactor); ii++) {
for (int jj = (y*binFactor); jj < ((y + 1)*binFactor); jj++) {
PairInt p = new PairInt(ii, jj);
output.add(p);
}
}
}
return output;
}
/**
* iterate over each point in zeroPointLists and visit its 8 neighbors
* looking for those not in it's list. if not in list and is in the
* image as a zero value pixel, place it in the list. note that this is a method to use
* for correcting the zero points lists after down sampling to make the
* list and then up sampling to use it.
*
* @param zeroPointLists
* @param theta
*/
private void addBackMissingZeros(List<PairIntArray> zeroPointLists,
GreyscaleImage theta, int binFactor, int topNumberToCorrect) {
int width = theta.getWidth();
int height = theta.getHeight();
int end = topNumberToCorrect;
if (zeroPointLists.size() < end) {
end = zeroPointLists.size();
}
List<Set<Integer> > sets = new ArrayList<Set<Integer> >();
for (int ii = 0; ii < end; ii++) {
PairIntArray zeroValuePoints = zeroPointLists.get(ii);
Set<Integer> zpSet = new HashSet<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
int idx = theta.getIndex(x, y);
zpSet.add(Integer.valueOf(idx));
}
sets.add(zpSet);
}
for (int ii = 0; ii < end; ii++) {
PairIntArray zeroValuePoints = zeroPointLists.get(ii);
Set<Integer> zpSet = sets.get(ii);
Set<Integer> add = new HashSet<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
for (int c = (x - binFactor); c <= (x + binFactor); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - binFactor); r <= (y + binFactor); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int neighborIdx = theta.getIndex(c, r);
Integer index = Integer.valueOf(neighborIdx);
if (zpSet.contains(index)) {
continue;
}
int v = theta.getValue(c, r);
if (v == 0) {
add.add(index);
}
}
}
}
if (!add.isEmpty()) {
for (Integer a : add) {
int c = theta.getCol(a.intValue());
int r = theta.getRow(a.intValue());
zeroValuePoints.add(c, r);
zpSet.add(a);
}
}
}
}
/**
* remove points in zeropoint lists where there is a non-zero pixel in the
* theta image.
*
* @param zeroPointLists
* @param theta
*/
private void removeOverSampledZeros(List<PairIntArray> zeroPointLists,
GreyscaleImage theta) {
for (PairIntArray zeroValuePoints : zeroPointLists) {
List<Integer> remove = new ArrayList<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
int v = theta.getValue(x, y);
if (v > 0) {
remove.add(Integer.valueOf(pIdx));
}
}
if (!remove.isEmpty()) {
for (int i = (remove.size() - 1); i > -1; i
int idx = remove.get(i).intValue();
zeroValuePoints.removeRange(idx, idx);
}
}
}
}
public void printImageColorContrastStats(Image image, List<PairIntArray>
zeroPoints) {
}
public void printImageColorContrastStats(Image image, int rgbSkyAvg,
int plotNumber) throws IOException {
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
int rSky = (rgbSkyAvg >> 16) & 0xFF;
int gSky = (rgbSkyAvg >> 8) & 0xFF;
int bSky = rgbSkyAvg & 0xFF;
double[] yuvSky = MatrixUtil.multiply(m, new double[]{rSky, gSky, bSky});
double t313 = Math.pow(3, (1./3.));
int w = image.getWidth();
int h = image.getHeight();
int slice = 1;
PolygonAndPointPlotter plotter = new PolygonAndPointPlotter();
for (int i = 0; i < 6; i++) {
int startCol = -1;
int stopCol = -1;
int startRow = -1;
int stopRow = -1;
boolean plotAlongRows = true;
String labelSuffix = null;
switch(i) {
case 0:
//horizontal at low y
startCol = 0;
stopCol = w - 1;
startRow = slice;
stopRow = startRow + slice;
plotAlongRows = false;
labelSuffix = "horizontal stripe at low y";
break;
case 1:
//horizontal at mid y
startCol = 0;
stopCol = w - 1;
startRow = (h - slice)/2 ;
stopRow = startRow + slice;
plotAlongRows = false;
labelSuffix = "horizontal stripe at mid y";
break;
case 2:
//horizontal at high y
startCol = 0;
stopCol = w - 1;
startRow = (h - 2*slice) - 1;
stopRow = startRow + slice;
plotAlongRows = false;
labelSuffix = "horizontal stripe at high y";
break;
case 3:
//vertical at low x
startCol = slice;
stopCol = startCol + slice;
startRow = 0;
stopRow = h - 1;
plotAlongRows = true;
labelSuffix = "vertical stripe at low x";
break;
case 4:
//vertical at mid x
startCol = (w - slice)/2;
stopCol = startCol + slice;
startRow = 0;
stopRow = h - 1;
plotAlongRows = true;
labelSuffix = "vertical stripe at mid x";
break;
default:
//vertical at high x
startCol = (w - 2*slice) - 1;
stopCol = startCol + slice;
startRow = 0;
stopRow = h - 1;
plotAlongRows = true;
labelSuffix = "vertical stripe at high x";
break;
}
// contrast as y
// hue
// blue
// red
float[] contrast = null;
float[] hue = null;
float[] red = null;
float[] blue = null;
float[] white = null;
float[] axis = null;
if (!plotAlongRows) {
// plot along columns
contrast = new float[w];
hue = new float[w];
red = new float[w];
blue = new float[w];
white = new float[w];
axis = new float[w];
for (int col = startCol; col <= stopCol; col++) {
int row = startRow;
int r = image.getR(col, row);
int g = image.getG(col, row);
int b = image.getB(col, row);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
double hueValue = Math.atan2(t313 * (g - b), ((2 * r) - g - b));
double contrastValue = (yuvSky[0] - yuv[0])/yuv[0];
double whiteValue = (r + g + b)/3.;
contrast[col] = (float)contrastValue;
hue[col] = (float)hueValue;
blue[col] = (float)b;
red[col] = (float)r;
white[col] = (float)whiteValue;
axis[col] = col;
}
} else {
// plot along rows
contrast = new float[h];
hue = new float[h];
red = new float[h];
blue = new float[h];
white = new float[h];
axis = new float[h];
for (int row = startRow; row <= stopRow; row++) {
int col = startCol;
int r = image.getR(col, row);
int g = image.getG(col, row);
int b = image.getB(col, row);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
double hueValue = Math.atan2(t313 * (g - b), ((2 * r) - g - b));
double contrastValue = (yuvSky[0] - yuv[0])/yuv[0];
double whiteValue = (r + g + b)/3.;
contrast[row] = (float)contrastValue;
hue[row] = (float)hueValue;
blue[row] = (float)b;
red[row] = (float)r;
white[row] = (float)whiteValue;
axis[row] = row;
}
}
float xmn = MiscMath.findMin(axis);
float xmx = MiscMath.findMax(axis);
float ymn = MiscMath.findMin(contrast);
float ymx = 1.1f * MiscMath.findMax(contrast);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, contrast, null, null, null, null,
"contrast " + labelSuffix);
ymn = MiscMath.findMin(hue);
ymx = 1.1f * MiscMath.findMax(hue);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, hue, null, null, null, null, "hue " + labelSuffix);
ymn = MiscMath.findMin(blue);
ymx = 1.1f * MiscMath.findMax(blue);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, blue, null, null, null, null, "blue " + labelSuffix);
ymn = MiscMath.findMin(red);
ymx = 1.1f * MiscMath.findMax(red);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, red, null, null, null, null, "red " + labelSuffix);
ymn = MiscMath.findMin(white);
ymx = 1.1f * MiscMath.findMax(white);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, white, null, null, null, null, "white " + labelSuffix);
plotter.writeFile(plotNumber);
}
}
private void removeSetsThatAreDark(List<PairIntArray>
zeroPointLists, Image originalColorImage, GreyscaleImage theta,
boolean addAlongX, int addAmount) {
int colorLimit = 100;
List<Integer> remove = new ArrayList<Integer>();
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
PairIntArray points = zeroPointLists.get(gId);
int nBelowLimit = 0;
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
if ((r < colorLimit) && (b < colorLimit) && (g < colorLimit)) {
nBelowLimit++;
}
}
log.fine(gId + ") nBelowLimit=" + nBelowLimit
+ " (" + ((double)nBelowLimit/(double)points.getN()) + ")");
if (((double)nBelowLimit/(double)points.getN()) > 0.5) {
remove.add(Integer.valueOf(gId));
}
}
if (!remove.isEmpty()) {
for (int i = (remove.size() - 1); i > -1; i
zeroPointLists.remove(remove.get(i).intValue());
}
}
}
private void reduceToLargest(List<PairIntArray> zeroPointLists) {
int rmIdx = -1;
if (zeroPointLists.size() > 1) {
float n0 = (float)zeroPointLists.get(0).getN();
for (int i = 1; i < zeroPointLists.size(); i++) {
float number = zeroPointLists.get(i).getN();
float frac = number/n0;
System.out.println(number + " n0=" + n0);
//TODO: this should be adjusted by some metric.
// a histogram?
// since most images should have been binned to <= 300 x 300 pix,
// making an assumption about a group >= 100 pixels
if (frac < 0.1) {
rmIdx = i;
break;
}
}
}
if (rmIdx > -1) {
List<PairIntArray> out = new ArrayList<PairIntArray>();
for (int i = 0; i < rmIdx; i++) {
out.add(zeroPointLists.get(i));
}
zeroPointLists.clear();
zeroPointLists.addAll(out);
}
}
/**
* remove high contrast points from the sky points. this helps to remove
* points from structures like skyscraper windows which have repetitive
* structure on the scale of the combined convolutions of the gradient image
* that results in the repetitive structure not being a feature in the
* gradient and theta images, hence present in the theta image extracted
* skypoints when they should not be.
* @param zeroPointLists
* @param originalColorImage
* @param theta
* @param avgY
* @param addAlongX
* @param addAmount
*/
private void removeHighContrastPoints(List<PairIntArray>
zeroPointLists, Image originalColorImage, GreyscaleImage theta,
double avgY, boolean addAlongX, int addAmount) {
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
// remove points that have contrast larger than tail of histogram
HistogramHolder h = createContrastHistogram(avgY, zeroPointLists,
originalColorImage, xOffset, yOffset, addAlongX,
addAmount);
if (h == null) {
return;
}
/*
try {
h.plotHistogram("contrast", 1);
} catch (IOException e) {
log.severe(e.getMessage());
}
*/
int yPeakIdx = MiscMath.findYMaxIndex(h.getYHist());
int tailXIdx = h.getXHist().length - 1;
if (tailXIdx > yPeakIdx) {
float yPeak = h.getYHist()[yPeakIdx];
float crit = 0.03f;
float dy = Float.MIN_VALUE;
for (int i = (yPeakIdx + 1); i < h.getYHist().length; i++) {
float f = (float)h.getYHist()[i]/yPeak;
dy = Math.abs(h.getYHist()[i] - h.getYHist()[i - 1]);
System.out.println("x=" + h.getXHist()[i] + " f=" + f + " dy=" + dy);
if (f < crit) {
tailXIdx = i;
break;
}
}
}
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
//remove points w/ contrast higher than the tail of the histogram
double critContrast = h.getXHist()[tailXIdx];
Set<PairInt> debug = new HashSet<PairInt>();
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
PairIntArray points = zeroPointLists.get(gId);
Set<PairInt> pointsSet = new HashSet<PairInt>();
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
PairInt pi = new PairInt(x, y);
pointsSet.add(pi);
}
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
float contrast = (float)((avgY - yuv[0]) / yuv[0]);
if (contrast > critContrast) {
PairInt pi0 = new PairInt(x, y);
pointsSet.remove(pi0);
debug.add(pi0);
for (int xx = (x - 1); xx <= (x + 1); xx++) {
if ((xx < 0) || (xx > (theta.getWidth() - 1))) {
continue;
}
for (int yy = (y - 1); yy <= (y + 1); yy++) {
if ((yy < 0) || (yy > (theta.getHeight() - 1))) {
continue;
}
if ((xx == x) && (yy == y)) {
continue;
}
PairInt pi1 = new PairInt(xx, yy);
if (pointsSet.contains(pi1)) {
pointsSet.remove(pi1);
debug.add(pi1);
}
}
}
}
}
if (pointsSet.size() != points.getN()) {
PairIntArray points2 = new PairIntArray();
for (PairInt pi : pointsSet) {
points2.add(pi.getX(), pi.getY());
}
points.swapContents(points2);
}
}
// remove empty sets
for (int i = (zeroPointLists.size() - 1); i > -1; i
PairIntArray point = zeroPointLists.get(i);
if (point.getN() == 0) {
zeroPointLists.remove(i);
}
}
try {
Image img1 = theta.copyImageToGreen();
ImageIOHelper.addToImage(debug, 0, 0, img1);
ImageDisplayer.displayImage("removing high contrast", img1);
} catch (IOException ex) {
log.severe(ex.getMessage());
}
}
public double[] calculateYRGB(PairIntArray points, Image originalColorImage,
int xOffset, int yOffset, boolean addAlongX, int addAmount) {
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
double avgY = 0;
double avgR = 0;
double avgG = 0;
double avgB = 0;
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
avgY += yuv[0];
avgR += r;
avgG += g;
avgB += b;
}
avgY /= (double)points.getN();
avgR /= (double)points.getN();
avgG /= (double)points.getN();
avgB /= (double)points.getN();
return new double[]{avgY, avgR, avgG, avgB};
}
private HistogramHolder createContrastHistogram(double avgY,
List<PairIntArray> zeroPointLists, Image originalColorImage,
int xOffset, int yOffset, boolean addAlongX, int addAmount) {
if (zeroPointLists.isEmpty()) {
return null;
}
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
int nPoints = 0;
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
nPoints += zeroPointLists.get(gId).getN();
}
float[] yValues = new float[nPoints];
int count = 0;
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
PairIntArray points = zeroPointLists.get(gId);
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
float contrastValue = (float)((avgY - yuv[0]) / yuv[0]);
yValues[count] = contrastValue;
count++;
}
}
HistogramHolder h = Histogram.calculateSturgesHistogramRemoveZeroTail(
yValues, Errors.populateYErrorsBySqrt(yValues));
return h;
}
private void transformPointsToOriginalReferenceFrame(Set<PairInt> points,
GreyscaleImage theta, boolean makeCorrectionsAlongX, int addAmount) {
// transform points to original color image frame
int totalXOffset = theta.getXRelativeOffset();
int totalYOffset = theta.getYRelativeOffset();
if (makeCorrectionsAlongX) {
totalXOffset += addAmount;
} else {
totalYOffset += addAmount;
}
for (PairInt p : points) {
int x = p.getX();
int y = p.getY();
x += totalXOffset;
y += totalYOffset;
p.setX(x);
p.setY(y);
}
}
/**
* NOT READY FOR USE YET. THIS should be run on the binned images.
* The images which are more than half sky should especially be
* processed at binned size.
*
* @param points
* @param originalColorImage
* @param theta
* @param avgYRGB
* @param makeCorrectionsAlongX
* @param addAmount
* @return
*/
private GreyscaleImage growPointsToSkyline(Set<PairInt> points,
Image originalColorImage, GreyscaleImage theta, double[] avgYRGB,
boolean makeCorrectionsAlongX, int addAmount) {
// mask needs to be in the frame of the theta image
// transform points to original color image frame
int totalXOffset = theta.getXRelativeOffset();
int totalYOffset = theta.getYRelativeOffset();
if (makeCorrectionsAlongX) {
totalXOffset += addAmount;
} else {
totalYOffset += addAmount;
}
//transformPointsToOriginalReferenceFrame(points, theta,
// makeCorrectionsAlongX, addAmount);
double yAvg = avgYRGB[0];
double rColor = avgYRGB[1];
double gColor = avgYRGB[2];
double bColor = avgYRGB[3];
// (r-b)/255 < 0.2
boolean useBlue = (((rColor - bColor)/255.) < 0.2);
if (useBlue && (((rColor/bColor) > 1.0)) && (bColor < 128)) {
useBlue = false;
}
// determine contrast and blue or red for each point in points
Map<PairInt, PairFloat> contrastAndColorMap = calculateContrastAndBOrR(
points, useBlue, originalColorImage, avgYRGB,
totalXOffset, totalYOffset);
// determine differences in contrast and blue or red for each point
// from their neighbors (if they are in the map) and return
// the avg and st.dev. of
// {avg dContrast, stdDev dContrast, avg dBlueOrRed, stDev dBlueOrRed}
float[] diffsAvgAndStDev = calculateAvgAndStDevOfDiffs(
contrastAndColorMap);
log.fine("diffsAvgAndStDev=" + Arrays.toString(diffsAvgAndStDev));
float diffContrastAvg = diffsAvgAndStDev[0];
float diffContrastStDev = diffsAvgAndStDev[1];
float diffBlueOrRedAvg = diffsAvgAndStDev[2];
float diffBlueOrRedStDev = diffsAvgAndStDev[3];
// TODO: improve this setting. using + factor*stDev does not
// lead to result needing one factor either.
float contrastFactor = 1.f;
float colorFactor = -10f;
/*
given map of points and their contrasts and colors and the avg changes
in those and the std dev of that,
use dfs to look for neighbors of the points that fall within the critical
limits. when the point is within limit, it gets marked as a '0'
in the output image (which is otherwise '1')
*/
GreyscaleImage mask = theta.createWithDimensions();
mask.fill(1);
int width = theta.getWidth();
int height = theta.getHeight();
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
java.util.Stack<PairInt> stack = new java.util.Stack<PairInt>();
//O(N_sky)
for (PairInt p : points) {
int x = p.getX();
int y = p.getY();
stack.add(p);
mask.setValue(x, y, 0);
}
// null = unvisited, presence = visited
Set<PairInt> visited = new HashSet<PairInt>();
visited.add(stack.peek());
while (!stack.isEmpty()) {
PairInt uPoint = stack.pop();
int uX = uPoint.getX();
int uY = uPoint.getY();
//(1 + frac)*O(N) where frac is the fraction added back to stack
for (int vX = (uX - 1); vX <= (uX + 1); vX++) {
if ((vX < 0) || (vX > (width - 1))) {
continue;
}
for (int vY = (uY - 1); vY <= (uY + 1); vY++) {
if ((vY < 0) || (vY > (height - 1))) {
continue;
}
PairInt vPoint = new PairInt(vX, vY);
if (vPoint.equals(uPoint)) {
continue;
}
if (visited.contains(vPoint)) {
continue;
}
if (contrastAndColorMap.containsKey(vPoint)) {
continue;
}
if ((vX < 0) || (vX > (theta.getWidth() - 1))) {
continue;
}
if ((vY < 0) || (vY > (theta.getHeight() - 1))) {
continue;
}
int ox = vX + totalXOffset;
int oy = vY + totalYOffset;
visited.add(vPoint);
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int rV = originalColorImage.getR(ox, oy);
int gV = originalColorImage.getG(ox, oy);
int bV = originalColorImage.getB(ox, oy);
double[] rgbV = new double[]{rV, gV, bV};
double[] yuv = MatrixUtil.multiply(m, rgbV);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
float contrastV = (float)((yAvg - yuv[0]) / yuv[0]);
// if delta constrast and delta blue or red are within
// limits, add to stack and set in mask
PairFloat uContrastAndColor = contrastAndColorMap.get(uPoint);
float vMinusUContrast = contrastV - uContrastAndColor.getX();
boolean withinLimits = true;
// contrast: ucontrast >= (vContrast + 16*diffContrastStDev), v:42, s:26, sh:246, norw:22, hd:5, nm:64, az: 1
// color: -18 , v:-48, s:-12, sh:-80, norw:-15, hd:-16, nm:-79, az:+15 ((r-b)=132)
if ((ox == (517/2)) && (contrastV > uContrastAndColor.getX())) {
log.info("\ny = " + oy + " diffsAvgAndStDev=" + Arrays.toString(diffsAvgAndStDev));
int color = (useBlue ? bV : rV);
String str = String.format("useBlue=%b u(c, c)=(%f,%f) v(c,c)=(%f,%d) dContrast=%f dColor=%f",
useBlue, uContrastAndColor.getX(), uContrastAndColor.getY(),
contrastV, color, (contrastV - uContrastAndColor.getX()),
(color - uContrastAndColor.getY()));
log.info(str);
int z = 1;
}
if ((vMinusUContrast/diffContrastAvg) >= contrastFactor) {
// see if color has decreased
float vColor = useBlue ? bV : rV;
float VMinusUColor = vColor - uContrastAndColor.getY();
//TODO: consider either only -10 or abs
if ((VMinusUColor/diffBlueOrRedAvg) < colorFactor) {
//if (Math.abs(VMinusUColor/diffBlueOrRedAvg) > Math.abs(colorFactor)) {
withinLimits = false;
}
}
if (withinLimits) {
stack.add(vPoint);
mask.setValue(vX, vY, 0);
float vColor = useBlue ? bV : rV;
PairFloat vCC = new PairFloat(contrastV, vColor);
contrastAndColorMap.put(vPoint, vCC);
}
}
}
}
return mask;
}
private Map<PairInt, PairFloat> calculateContrastAndBOrR(
Set<PairInt> points, boolean useBlue, Image originalColorImage,
double[] avgYRGB, int totalXOffset, int totalYOffset) {
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
double yColor = avgYRGB[0];
Map<PairInt, PairFloat> map = new HashMap<PairInt, PairFloat>();
for (PairInt p : points) {
int x = p.getX();
int y = p.getY();
x += totalXOffset;
y += totalYOffset;
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
float contrast= (float) ((yColor - yuv[0]) / yuv[0]);
PairFloat crb = new PairFloat();
crb.setX(contrast);
if (useBlue) {
crb.setY(b);
} else {
crb.setY(r);
}
map.put(p, crb);
}
return map;
}
private float[] calculateAvgAndStDevOfDiffs(Map<PairInt, PairFloat>
contrastAndColorMap) {
// average difference from neighbors
double avgContrast = 0;
double avgColor = 0;
int count = 0;
Iterator<Entry<PairInt, PairFloat> > iter =
contrastAndColorMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<PairInt, PairFloat> entry = iter.next();
PairInt i = entry.getKey();
int x = i.getX();
int y = i.getY();
for (int xx = (x - 1); xx <= (x + 1); xx++) {
for (int yy = (y - 1); yy <= (y + 1); yy++) {
PairInt j = new PairInt(xx, yy);
if (contrastAndColorMap.containsKey(j)) {
PairFloat iCC = entry.getValue();
PairFloat jCC = contrastAndColorMap.get(j);
float diffContrast = Math.abs(iCC.getX() - jCC.getX());
float diffColor = Math.abs(iCC.getY() - jCC.getY());
avgContrast += diffContrast;
avgColor += diffColor;
count++;
}
}
}
}
avgContrast /= (double)count;
avgColor /= (double)count;
// standard deviation of avg difference from neighbors
double stDevContrast = 0;
double stDevColor = 0;
iter = contrastAndColorMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<PairInt, PairFloat> entry = iter.next();
PairInt i = entry.getKey();
int x = i.getX();
int y = i.getY();
for (int xx = (x - 1); xx <= (x + 1); xx++) {
for (int yy = (y - 1); yy <= (y + 1); yy++) {
PairInt j = new PairInt(xx, yy);
if (contrastAndColorMap.containsKey(j)) {
PairFloat iCC = entry.getValue();
PairFloat jCC = contrastAndColorMap.get(j);
float diffContrast = Math.abs(iCC.getX() - jCC.getX());
diffContrast -= avgContrast;
float diffColor = Math.abs(iCC.getY() - jCC.getY());
diffColor -= avgColor;
stDevContrast += (diffContrast * diffContrast);
stDevColor += (diffColor * diffColor);
}
}
}
}
stDevContrast = Math.sqrt(stDevContrast/((double)count - 1));
stDevColor = Math.sqrt(stDevColor/((double)count - 1));
return new float[]{(float)avgContrast, (float)stDevContrast,
(float)avgColor, (float)stDevColor};
}
/**
* using adaptive "thresholding" to subtract intensity levels from
* gradientXY, find the contiguous zero values connected to skyPoints
* and add them to skyPoints.
* @param gradientXY
* @param skyPoints
* @return
*/
public int extractSkyFromGradientXY(GreyscaleImage gradientXY,
Set<PairInt> skyPoints) {
int subtract = 0;
GreyscaleImage gXY2 = gradientXY.copyImage();
// x is pixelValue , y is number of pixels holding that value
PairIntArray gXYValues = Histogram.createADescendingSortByKeyArray(gXY2);
int nMaxIter = gXYValues.getN();
int nIter = 0;
float v0 = gXYValues.getY(gXYValues.getN() - 1);
int lastMinIdx = -1;
int nPrevCorrectedEmbeddedGroups0 = Integer.MAX_VALUE;
int prevSubtract0 = 0;
Set<PairInt> prevSkyPoints0 = null;
// subtracting thresholds that are >= 0.5,
boolean doNotSubtractMore = false;
while (nIter < nMaxIter) {
// subtract a threshold amount from gradientXY,
// starting from a value that's half of the peak, then intervals
if (nIter > 0) {
gXY2 = gradientXY.copyImage();
}
if (nIter < 5) {
float critFraction = (nIter == 0) ? 0.65f :
(nIter == 1) ? 0.45f :
(nIter == 2) ? 0.25f :
(nIter == 2) ? 0.1f : 0.05f;
subtract = gXYValues.getX(gXYValues.getN() - 1);
for (int i = (gXYValues.getN() - 1); i > -1; i
float f = (float)gXYValues.getY(i)/v0;
if (f >= critFraction) {
subtract = gXYValues.getX(i);
lastMinIdx = i;
} else {
break;
}
}
} else {
lastMinIdx
if (lastMinIdx < 1) {
break;
}
subtract = gXYValues.getX(lastMinIdx);
}
subtractWithCorrectForNegative(gXY2, subtract);
growZeroValuePoints(skyPoints, gXY2);
Set<PairInt> embeddedPoints = new HashSet<PairInt>();
int nCorrectedEmbeddedGroups = extractEmbeddedGroupPoints(
skyPoints, gXY2, embeddedPoints);
float nSkyPix = skyPoints.size();
log.info("nIter=" + nIter + ")"
+ " nCorrectedEmbeddedGroups=" + nCorrectedEmbeddedGroups
+ " nEmbeddedPixels=" + embeddedPoints.size()
+ " out of " + nSkyPix
+ " (level=" + ((float)gXYValues.getY(lastMinIdx)/v0)
+ " subtract=" + subtract + " out of max=" + gXYValues.getX(0)
+ ")"
);
if (
((nCorrectedEmbeddedGroups >= 2*nPrevCorrectedEmbeddedGroups0)
&& (prevSkyPoints0 != null))
) {
skyPoints.clear();
skyPoints.addAll(prevSkyPoints0);
subtract = prevSubtract0;
break;
}
doNotSubtractMore = (nIter == 0)
&& (embeddedPoints.isEmpty()
|| (((double) nCorrectedEmbeddedGroups
* (double) embeddedPoints.size() / nSkyPix) < 0.008));
if (doNotSubtractMore) {
break;
}
float fracPixels = (float)embeddedPoints.size()/nSkyPix;
//TODO: improve this
if (((nIter == 0) && (fracPixels < 0.01) && (nCorrectedEmbeddedGroups < 10)) ||
((nIter > 0) && (nCorrectedEmbeddedGroups < 4))) {
if ((nCorrectedEmbeddedGroups > 0) && (fracPixels < 0.008)) {
// this last subtraction can lead to the entire image being
// connected to zero value regions if the skyline is low
// contrast, so will assume that the image is not usually
// entirely sky, and will revert the subtraction if it's
// too much
int maxValue = Integer.MIN_VALUE;
for (PairInt p : embeddedPoints) {
int x = p.getX();
int y = p.getY();
int v = gXY2.getValue(x, y);
if (v > maxValue) {
maxValue = v;
}
}
float fractionOfMax = 0.5f * (gXYValues.getX(0) - subtract);
if ((maxValue > Float.MIN_VALUE) && (maxValue < fractionOfMax)) {
if ((nIter == 0) && (subtract == 0) && (maxValue > 1)) {
maxValue
}
/*TODO:rewrite here to copy previous state.
then invoke subtract and grow
then check and revert if needed */
Set<PairInt> prevSkyPoints = new HashSet<PairInt>();
prevSkyPoints.addAll(skyPoints);
int prevSubtract = subtract;
subtractWithCorrectForNegative(gXY2, maxValue);
growZeroValuePoints(skyPoints, gXY2);
log.info("--> subtracted " + maxValue);
// if nearly all pixels are sky pixels, revert solution.
float fracSky = (float) skyPoints.size() / (float) gXY2.getNPixels();
log.info("fracSky=" + fracSky);
if (fracSky > 0.8) {
// TODO: if subtract > 1, try again here with subtracting
// one less and check fraction again
// else revert
log.info("--> reverting to previous");
skyPoints.clear();
skyPoints.addAll(prevSkyPoints);
subtract = prevSubtract;
doNotSubtractMore = true;
}
}
}
try {
Image img1 = gradientXY.copyImageToGreen();
ImageIOHelper.addToImage(skyPoints, 0, 0, img1);
ImageDisplayer.displayImage("sky points nIter=" + nIter, img1);
} catch (IOException ex) {
log.severe(ex.getMessage());
}
if (doNotSubtractMore) {
break;
}
break;
}
try {
Image img1 = gradientXY.copyImageToGreen();
ImageIOHelper.addToImage(skyPoints, 0, 0, img1);
ImageDisplayer.displayImage("sky points nIter=" + nIter, img1);
} catch (IOException ex) {
log.severe(ex.getMessage());
}
if (doNotSubtractMore) {
break;
}
nPrevCorrectedEmbeddedGroups0 = nCorrectedEmbeddedGroups;
prevSubtract0 = subtract;
prevSkyPoints0 = new HashSet<PairInt>();
prevSkyPoints0.addAll(skyPoints);
nIter++;
}
return subtract;
}
private void growZeroValuePoints(Set<PairInt> points, GreyscaleImage
gradientXY) {
java.util.Stack<PairInt> stack = new java.util.Stack<PairInt>();
//O(N_sky)
for (PairInt p : points) {
stack.add(p);
}
// null = unvisited, presence = visited
Set<PairInt> visited = new HashSet<PairInt>();
visited.add(stack.peek());
int width = gradientXY.getWidth();
int height = gradientXY.getHeight();
while (!stack.isEmpty()) {
PairInt uPoint = stack.pop();
int uX = uPoint.getX();
int uY = uPoint.getY();
//(1 + frac)*O(N) where frac is the fraction added back to stack
for (int vX = (uX - 1); vX <= (uX + 1); vX++) {
if ((vX < 0) || (vX > (width - 1))) {
continue;
}
for (int vY = (uY - 1); vY <= (uY + 1); vY++) {
if ((vY < 0) || (vY > (height - 1))) {
continue;
}
PairInt vPoint = new PairInt(vX, vY);
if (vPoint.equals(uPoint)) {
continue;
}
if (visited.contains(vPoint)) {
continue;
}
if ((vX < 0) || (vX > (width - 1))) {
continue;
}
if ((vY < 0) || (vY > (height - 1))) {
continue;
}
visited.add(vPoint);
int v = gradientXY.getValue(vX, vY);
if (v == 0) {
stack.add(vPoint);
if (!points.contains(vPoint)) {
points.add(vPoint);
}
}
}
}
}
}
private boolean isPerimeterUnbound(Map<Integer, PairInt> gRowColRange,
int[] gRowMinMax, Set<PairInt> skyPoints, double[] groupXYCen,
int imageWidth, int imageHeight) {
boolean unbounded = false;
for (int r = gRowMinMax[0]; r <= gRowMinMax[1]; r++) {
PairInt cRange = gRowColRange.get(Integer.valueOf(r));
for (int k = 0; k < 2; k++) {
int c;
switch(k) {
case 0:
c = cRange.getX();
break;
default:
c = cRange.getY();
break;
}
if (c < groupXYCen[0]) {
// look for points to left
int xt = c - 1;
if (xt < 0) {
// bounded by edge of image
continue;
}
if (r < groupXYCen[1]) {
//look for points to left and top (=lower y)
int yt = r;
PairInt p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
//found a sky point to the left
yt
if (yt < 0) {
// bounded by edge of image
continue;
} else {
p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
}
} else {
//look for bounding points to left, bottom (=higher y)
int yt = r;
PairInt p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
yt++;
if (yt > (imageHeight - 1)) {
// bounded by edge of image
continue;
} else {
p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
}
}
} else {
// look for points to the right
int xt = c + 1;
if (xt > (imageWidth - 1)) {
// bounded by edge of image
continue;
}
if (r < groupXYCen[1]) {
//look for bounding points to right, top (=lower y),
int yt = r;
PairInt p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
yt
if (yt < 0) {
// bounded by edge of image
continue;
} else {
p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
}
} else {
//look for bounding points to right, bottom (=higher y)
int yt = r;
PairInt p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
yt++;
if (yt > (imageHeight - 1)) {
// bounded by edge of image
continue;
} else {
p = new PairInt(xt, yt);
if (!skyPoints.contains(p)) {
// not bounded on left
unbounded = true;
break;
}
}
}
}
}
if (unbounded) {
break;
}
}
return unbounded;
}
/**
* attempt to find sun by color (hsb) and elliptical shape of
* points with that color. those points are then added to the skyPoints.
* Note that if the sun is present in sky and in reflection, such as
* water, their location in x,y must be fittable by an ellipse, else they
* may not be found as sun points.
* @param skyPoints
* @param clr
* @param xOffset
* @param yOffset
*/
private void findSunAndAddToSkyPoints(Set<PairInt> skyPoints, Image clr,
int xOffset, int yOffset) {
// gather yellow points within bounds or connected to sky and
// place them in an array to test the shape.
// and if elliptical, add them and the enclosed points to skyPoints
Set<PairInt> yellowPoints = new HashSet<PairInt>();
for (PairInt p : skyPoints) {
int x = p.getX() + xOffset;
int y = p.getY() + yOffset;
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
int xx = x + dx;
int yy = y + dy;
if ((xx < 0) || xx > (clr.getWidth() - 1)) {
continue;
}
if ((yy < 0) || yy > (clr.getHeight() - 1)) {
continue;
}
int r = clr.getR(xx, yy);
int g = clr.getG(xx, yy);
int b = clr.getB(xx, yy);
// all normalized from 0 to 1
float[] hsb = new float[3];
Color.RGBtoHSB(r, g, b, hsb);
float h2 = hsb[0] * 360.f;
float s2 = hsb[1] * 100.f;
// red halo: ((h2 >= 30) && (h2 <= 40) && (s2 > 90) && (hsb[2] > 0.9))
// inward of that: ((h2 > 40) && (h2 <= 60) && (s2 > 35) && (s2 < 60))
if (
((h2 >= 30) && (h2 <= 40) && (s2 > 90) && (hsb[2] > 0.9))
|| ((h2 > 30) && (h2 <= 60) && (s2 > 35))
) {
PairInt p2 = new PairInt(xx - xOffset, yy - yOffset);
yellowPoints.add(p2);
}
}
}
}
if (yellowPoints.size() < 6) {
return;
}
//fit ellipse to yellowPoints. ellipse because of possible occlusion.
EllipseHelper ellipseHelper = new EllipseHelper();
double[] params = ellipseHelper.fitEllipseToPoints(yellowPoints);
if (params == null) {
// not close to an ellipse
return;
}
float xc = (float)params[0];
float yc = (float)params[1];
float a = (float)params[2];
float b = (float)params[3];
float alpha = (float)params[4];
//TODO: consider no filter for eccentricity
if (((a/b) - 1) < 10) {
// add to skyPoints, sun color points internal to perimeter of yellowPoints
PerimeterFinder finder = new PerimeterFinder();
int[] rowMinMax = new int[2];
Map<Integer, PairInt> rowColRange = finder.find(yellowPoints,
rowMinMax);
for (int row = rowMinMax[0]; row <= rowMinMax[1]; row++) {
PairInt cRange = rowColRange.get(Integer.valueOf(row));
int colStart = cRange.getX();
int colStop = cRange.getY();
for (int col = colStart; col <= colStop; col++) {
PairInt p = new PairInt(col, row);
if (skyPoints.contains(p)) {
continue;
}
col += xOffset;
row += yOffset;
int rr = clr.getR(col, row);
int gg = clr.getG(col, row);
int bb = clr.getB(col, row);
// all normalized from 0 to 1
float[] hsb = new float[3];
Color.RGBtoHSB(rr, gg, bb, hsb);
float h2 = hsb[0] * 360.f;
float s2 = hsb[1] * 100.f;
if (
// NOTE, if add (s2 > 40), large halo around sun is found
((rr >= 245/*251*/) && (hsb[2] >= 0.97/*0.98*/) && (s2 < 87))
) {
PairInt p2 = new PairInt(col - xOffset, row - yOffset);
yellowPoints.add(p2);
} else {
int z = 1;
}
}
}
}
skyPoints.addAll(yellowPoints);
//double[] stats = ellipseHelper.calculateEllipseResidualStats(
// yellowPoints.getX(), yellowPoints.getY(), xc, yc, a, b, alpha);
try {
Image img1 = clr.copyImage();
ImageIOHelper.addToImage(yellowPoints, xOffset, yOffset,
img1, 0, 0, 255);
//ImageIOHelper.addToImage(skyPoints, xOffset, yOffset, img1);
//ImageIOHelper.addToImage(cloudPoints.getX(), cloudPoints.getY(),
// img1, 1, 0, 255, 0);
ImageDisplayer.displayImage("sun points", img1);
} catch (IOException ex) {
log.severe(ex.getMessage());
}
}
private void removeSnowPoints(Set<PairInt> skyPoints, Image clr) {
for (PairInt p : skyPoints) {
int x = p.getX();
int y = p.getY();
if (y < 230) {
continue;
}
int r = clr.getR(x, y);
int g = clr.getG(x, y);
int b = clr.getB(x, y);
// all normalized from 0 to 1
float[] hsb = new float[3];
Color.RGBtoHSB(r, g, b, hsb);
float h2 = hsb[0] * 360.f;
float s2 = hsb[1] * 100.f;
if ((h2 > 57) && (h2 < 65) && (s2 < 50)) {
}
}
}
private void addBackMissingZeros(Set<PairInt> zeroPoints,
GreyscaleImage gXYImg, int binFactor, int valueToSubtract) {
int width = gXYImg.getWidth();
int height = gXYImg.getHeight();
GreyscaleImage img = gXYImg.copyImage();
MatrixUtil.add(img.getValues(), -1*valueToSubtract);
Set<PairInt> addPoints = new HashSet<PairInt>();
for (PairInt p : zeroPoints) {
int x = p.getX();
int y = p.getY();
for (int c = (x - binFactor); c <= (x + binFactor); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - binFactor); r <= (y + binFactor); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int neighborIdx = img.getIndex(c, r);
Integer index = Integer.valueOf(neighborIdx);
if (addPoints.contains(index)) {
continue;
}
if (zeroPoints.contains(index)) {
continue;
}
int v = img.getValue(c, r);
if (v == 0) {
addPoints.add(new PairInt(c, r));
}
}
}
}
zeroPoints.addAll(addPoints);
}
private void subtractWithCorrectForNegative(GreyscaleImage gXY2, int subtract) {
int nz = 0;
if (subtract > 0) {
for (int i = 0; i < gXY2.getNPixels(); i++) {
int v = gXY2.getValue(i);
v -= subtract;
if (v < 0) {
v = 0;
}
gXY2.setValue(i, v);
if (v == 0) {
nz++;
}
}
}
log.info("number of set 0's=" + nz);
}
private int extractEmbeddedGroupPoints(Set<PairInt> skyPoints,
GreyscaleImage gXY2, Set<PairInt> outputEmbeddedPoints) {
PerimeterFinder finder = new PerimeterFinder();
int[] rowMinMax = new int[2];
Map<Integer, PairInt> rowColRange = finder.find(skyPoints, rowMinMax);
DFSContiguousValueFinder contiguousNonZeroFinder =
new DFSContiguousValueFinder(gXY2);
contiguousNonZeroFinder.findGroupsNotThisValue(0, rowColRange,
rowMinMax);
int nEmbeddedGroups = contiguousNonZeroFinder.getNumberOfGroups();
int nCorrectedEmbeddedGroups = 0;
MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper();
for (int gId = 0; gId < nEmbeddedGroups; gId++) {
Set<PairInt> groupPoints = new HashSet<PairInt>();
int[] indexes = contiguousNonZeroFinder.getIndexes(gId);
for (int j = 0; j < indexes.length; j++) {
int x = gXY2.getCol(indexes[j]);
int y = gXY2.getRow(indexes[j]);
groupPoints.add(new PairInt(x, y));
}
// if a perimeter point is not bounded in cardinal directions by
// image offsides or a pixel within skyPoints
// the group should be considered unbounded (such as the
// tops of buildings would be when their shapes intersect
// the convex hull of the sky points for example.
// Note: the perimeter is ignoring concaveness on a row to
// make this approx faster. it's still better than a convex
// hull for this purpose.
int[] gRowMinMax = new int[2];
Map<Integer, PairInt> gRowColRange = finder.find(groupPoints,
gRowMinMax);
double[] gCen = curveHelper.calculateXYCentroids(groupPoints);
boolean unbounded = isPerimeterUnbound(gRowColRange, gRowMinMax,
skyPoints, gCen, gXY2.getWidth(), gXY2.getHeight());
if (!unbounded) {
nCorrectedEmbeddedGroups++;
outputEmbeddedPoints.addAll(groupPoints);
}
}
return nCorrectedEmbeddedGroups;
}
}
|
package plugin.google.maps;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import org.apache.cordova.CordovaWebView;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("deprecation")
public class MyPluginLayout extends FrameLayout implements ViewTreeObserver.OnScrollChangedListener, ViewTreeObserver.OnGlobalLayoutListener {
private CordovaWebView webView;
private View browserView;
private ViewGroup root;
private Context context;
private FrontLayerLayout frontLayer;
private ScrollView scrollView = null;
public FrameLayout scrollFrameLayout = null;
public HashMap<String, PluginMap> pluginMaps = new HashMap<String, PluginMap>();
private HashMap<String, TouchableWrapper> touchableWrappers = new HashMap<String, TouchableWrapper>();
private boolean isScrolling = false;
public boolean isDebug = false;
public HashMap<String, Bundle> HTMLNodes = new HashMap<String, Bundle>();
private HashMap<String, RectF> HTMLNodeRectFs = new HashMap<String, RectF>();
private Activity mActivity = null;
private Paint debugPaint = new Paint();
public boolean stopFlag = false;
public boolean needUpdatePosition = false;
private float zoomScale;
public Timer redrawTimer;
@Override
public void onGlobalLayout() {
Log.d("Layout", "---> onGlobalLayout");
ViewTreeObserver observer = browserView.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
observer.removeOnGlobalLayoutListener(this);
} else {
observer.removeGlobalOnLayoutListener(this);
}
observer.addOnScrollChangedListener(this);
}
private class ResizeTask extends TimerTask {
@Override
public void run() {
//final PluginMap pluginMap = pluginMaps.get(mapId);
//if (pluginMap.mapDivId == null) {
// return;
//int scrollX = browserView.getScrollX();
final int scrollY = browserView.getScrollY();
//final int webviewWidth = browserView.getWidth();
//final int webviewHeight = browserView.getHeight();
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Set<String> keySet = pluginMaps.keySet();
String[] toArrayBuf = new String[pluginMaps.size()];
String[] mapIds = keySet.toArray(toArrayBuf);
toArrayBuf = null;
keySet = null;
String mapId;
PluginMap pluginMap;
RectF drawRect;
for (int i = 0; i < mapIds.length; i++) {
mapId = mapIds[i];
pluginMap = pluginMaps.get(mapId);
if (pluginMap == null || pluginMap.mapDivId == null) {
continue;
}
drawRect = HTMLNodeRectFs.get(pluginMap.mapDivId);
if (drawRect == null) {
continue;
}
int width = (int)drawRect.width();
int height = (int)drawRect.height();
int x = (int) drawRect.left;
int y = (int) drawRect.top + scrollY;
ViewGroup.LayoutParams lParams = pluginMap.mapView.getLayoutParams();
if (lParams instanceof AbsoluteLayout.LayoutParams) {
AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams;
if (params.x == x && params.y == y &&
params.width == width && params.height == height) {
return;
}
params.width = width;
params.height = height;
params.x = x;
params.y = y;
pluginMap.mapView.setLayoutParams(params);
} else if (lParams instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams;
if (params.leftMargin == x && params.topMargin == y &&
params.width == width && params.height == height) {
return;
}
params.width = width;
params.height = height;
params.leftMargin = x;
params.topMargin = y;
pluginMap.mapView.setLayoutParams(params);
} else if (lParams instanceof FrameLayout.LayoutParams) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams;
if (params.leftMargin == x && params.topMargin == y &&
params.width == width && params.height == height) {
return;
}
params.width = width;
params.height = height;
params.leftMargin = x;
params.topMargin = y;
//Log.d("MyPluginLayout", "-->FrameLayout y = " + y + ", topMargin = " + params.topMargin + ", drawRect.top = " + drawRect.top);
pluginMap.mapView.setLayoutParams(params);
}
}
mapIds = null;
pluginMap = null;
mapId = null;
pluginMap = null;
drawRect = null;
}
});
}
};
@SuppressLint("NewApi")
public MyPluginLayout(CordovaWebView webView, Activity activity) {
super(webView.getView().getContext());
this.browserView = webView.getView();
browserView.getViewTreeObserver().addOnGlobalLayoutListener(this);
mActivity = activity;
this.webView = webView;
this.root = (ViewGroup) browserView.getParent();
this.context = browserView.getContext();
//if (Build.VERSION.SDK_INT >= 21 || "org.xwalk.core.XWalkView".equals(browserView.getClass().getName())) {
// browserView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
zoomScale = Resources.getSystem().getDisplayMetrics().density;
frontLayer = new FrontLayerLayout(this.context);
scrollView = new ScrollView(this.context);
scrollView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
root.removeView(browserView);
frontLayer.addView(browserView);
scrollFrameLayout = new FrameLayout(this.context);
scrollFrameLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
View dummyView = new View(this.context);
dummyView.setLayoutParams(new LayoutParams(1, 99999));
scrollFrameLayout.addView(dummyView);
scrollView.setHorizontalScrollBarEnabled(true);
scrollView.setVerticalScrollBarEnabled(true);
scrollView.addView(scrollFrameLayout);
browserView.setDrawingCacheEnabled(false);
this.addView(scrollView);
this.addView(frontLayer);
root.addView(this);
browserView.setBackgroundColor(Color.TRANSPARENT);
/*
if("org.xwalk.core.XWalkView".equals(browserView.getClass().getName())
|| "org.crosswalk.engine.XWalkCordovaView".equals(browserView.getClass().getName())) {
try {
// view.setZOrderOnTop(true)
// Called just in time as with root.setBackground(...) the color
// come in front and take the whole screen
browserView.getClass().getMethod("setZOrderOnTop", boolean.class)
.invoke(browserView, true);
}
catch(Exception e) {
e.printStackTrace();
}
}
*/
scrollView.setHorizontalScrollBarEnabled(false);
scrollView.setVerticalScrollBarEnabled(false);
redrawTimer = new Timer();
redrawTimer.scheduleAtFixedRate(new ResizeTask(), 100, 25);
mActivity.getWindow().getDecorView().requestFocus();
}
public void putHTMLElements(JSONObject elements) {
HashMap<String, Bundle> newBuffer = new HashMap<String, Bundle>();
HashMap<String, RectF> newBufferRectFs = new HashMap<String, RectF>();
Bundle elementsBundle = PluginUtil.Json2Bundle(elements);
Iterator<String> domIDs = elementsBundle.keySet().iterator();
String domId;
Bundle domInfo, size;
while (domIDs.hasNext()) {
domId = domIDs.next();
domInfo = elementsBundle.getBundle(domId);
size = domInfo.getBundle("size");
RectF rectF = new RectF();
rectF.left = (float)(Double.parseDouble(size.get("left") + "") * zoomScale);
rectF.top = (float)(Double.parseDouble(size.get("top") + "") * zoomScale);
rectF.right = rectF.left + (float)(Double.parseDouble(size.get("width") + "") * zoomScale);
rectF.bottom = rectF.top + (float)(Double.parseDouble(size.get("height") + "") * zoomScale);
newBufferRectFs.put(domId, rectF);
domInfo.remove("size");
newBuffer.put(domId, domInfo);
}
Bundle bundle;
RectF rectF;
HashMap<String, Bundle> oldBuffer = HTMLNodes;
HashMap<String, RectF> oldBufferRectFs = HTMLNodeRectFs;
HTMLNodes = newBuffer;
HTMLNodeRectFs = newBufferRectFs;
String[] keys = oldBuffer.keySet().toArray(new String[oldBuffer.size()]);
for (int i = 0; i < oldBuffer.size(); i++) {
bundle = oldBuffer.remove(keys[i]);
bundle = null;
rectF = oldBufferRectFs.remove(keys[i]);
rectF = null;
}
oldBuffer = null;
oldBufferRectFs = null;
keys = null;
elementsBundle = null;
}
public void setDebug(final boolean debug) {
this.isDebug = debug;
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (debug) {
inValidate();
}
}
});
}
public PluginMap removePluginMap(final String mapId) {
if (!pluginMaps.containsKey(mapId)) {
return null;
}
final PluginMap pluginMap = pluginMaps.remove(mapId);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
scrollFrameLayout.removeView(pluginMap.mapView);
pluginMap.mapView.removeView(touchableWrappers.remove(mapId));
//Log.d("MyPluginLayout", "--> removePluginMap / mapId = " + mapId);
mActivity.getWindow().getDecorView().requestFocus();
} catch (Exception e) {
// ignore
//e.printStackTrace();
}
}
});
return pluginMap;
}
public void addPluginMap(final PluginMap pluginMap) {
if (pluginMap.mapDivId == null) {
return;
}
if (!HTMLNodes.containsKey(pluginMap.mapDivId)) {
Bundle dummyInfo = new Bundle();
dummyInfo.putDouble("offsetX", 0);
dummyInfo.putDouble("offsetY", 3000);
dummyInfo.putBoolean("isDummy", true);
HTMLNodes.put(pluginMap.mapDivId, dummyInfo);
HTMLNodeRectFs.put(pluginMap.mapDivId, new RectF(0, 3000, 100, 100));
}
pluginMaps.put(pluginMap.mapId, pluginMap);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
TouchableWrapper wrapper = new TouchableWrapper(context);
touchableWrappers.put(pluginMap.mapId, wrapper);
pluginMap.mapView.addView(wrapper);
scrollFrameLayout.addView(pluginMap.mapView);
mActivity.getWindow().getDecorView().requestFocus();
//updateViewPosition(pluginMap.mapId);
}
});
}
public void scrollTo(int x, int y) {
this.scrollView.scrollTo(x, y);
}
public void inValidate() {
this.frontLayer.invalidate();
}
@Override
public void onScrollChanged() {
scrollView.scrollTo(browserView.getScrollX(), browserView.getScrollY());
}
private class FrontLayerLayout extends FrameLayout {
public FrontLayerLayout(Context context) {
super(context);
this.setWillNotDraw(false);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (pluginMaps == null || pluginMaps.size() == 0) {
return false;
}
MyPluginLayout.this.stopFlag = true;
int action = event.getAction();
// The scroll action that started in the browser region is end.
isScrolling = action != MotionEvent.ACTION_UP && isScrolling;
if (isScrolling) {
MyPluginLayout.this.stopFlag = false;
return false;
}
PluginMap pluginMap;
Iterator<Map.Entry<String, PluginMap>> iterator = pluginMaps.entrySet().iterator();
Entry<String, PluginMap> entry;
String mapId;
PointF clickPoint = new PointF(event.getX(), event.getY());
int scrollY = browserView.getScrollY();
RectF drawRect;
boolean isMapAction = false;
while(iterator.hasNext()) {
entry = iterator.next();
mapId = entry.getKey();
pluginMap = entry.getValue();
// Is the map clickable?
if (!pluginMap.isVisible || !pluginMap.isClickable) {
continue;
}
if (pluginMap.mapDivId == null) {
continue;
}
// Is the clicked point is in the map rectangle?
drawRect = HTMLNodeRectFs.get(pluginMap.mapDivId);
if (!drawRect.contains(clickPoint.x, clickPoint.y)) {
continue;
}
isMapAction = true;
// Is the clicked point is on the html elements in the map?
String domIDs[] = HTMLNodes.keySet().toArray(new String[HTMLNodes.size()]);
Bundle domInfo = HTMLNodes.get(pluginMap.mapDivId);
RectF htmlElementRect;
int mapDivDepth = domInfo.getInt("depth");
for (String domId : domIDs) {
if (pluginMap.mapDivId.equals(domId)) {
continue;
}
if (!HTMLNodes.containsKey(domId)) {
continue;
}
domInfo = HTMLNodes.get(domId);
if (domInfo == null) {
continue;
}
if (domInfo.getInt("depth") <= mapDivDepth) {
continue;
}
htmlElementRect = HTMLNodeRectFs.get(domId);
if (htmlElementRect.width() == 0 || htmlElementRect.height() == 0) {
continue;
}
if (clickPoint.x >= htmlElementRect.left &&
clickPoint.x <= (htmlElementRect.right) &&
clickPoint.y >= htmlElementRect.top &&
clickPoint.y <= htmlElementRect.bottom) {
isMapAction = false;
break;
}
}
if (isMapAction) {
break;
}
}
isScrolling = (!isMapAction && action == MotionEvent.ACTION_DOWN) || isScrolling;
isMapAction = !isScrolling && isMapAction;
if (!isMapAction) {
browserView.requestFocus(View.FOCUS_DOWN);
}
webView.loadUrl("javascript:cordova.fireDocumentEvent('plugin_touch', {});");
MyPluginLayout.this.stopFlag = false;
return isMapAction;
}
@Override
protected void onDraw(Canvas canvas) {
if (HTMLNodes.isEmpty() || !isDebug) {
return;
}
PluginMap pluginMap;
Iterator<Map.Entry<String, PluginMap>> iterator = pluginMaps.entrySet().iterator();
Entry<String, PluginMap> entry;
RectF mapRect;
while(iterator.hasNext()) {
entry = iterator.next();
pluginMap = entry.getValue();
if (pluginMap.mapDivId == null) {
continue;
}
mapRect = HTMLNodeRectFs.get(pluginMap.mapDivId);
debugPaint.setColor(Color.argb(100, 0, 255, 0));
canvas.drawRect(mapRect, debugPaint);
}
}
}
private class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
scrollView.requestDisallowInterceptTouchEvent(true);
}
return super.dispatchTouchEvent(event);
}
}
}
|
package go.graphics.android;
import go.graphics.GLDrawContext;
import go.graphics.text.EFontSize;
import go.graphics.text.TextDrawer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import android.content.Context;
import android.opengl.GLES10;
import android.opengl.GLES11;
public class AndroidContext implements GLDrawContext {
private final Context context;
public AndroidContext(Context context) {
this.context = context;
}
@Override
public void fillQuad(float x1, float y1, float x2, float y2) {
quadDatas = new float[3 * 6];
quadDatas[0] = x1;
quadDatas[1] = y1;
quadDatas[2] = 0;
quadDatas[3] = x2;
quadDatas[4] = y1;
quadDatas[5] = 0;
quadDatas[6] = x1;
quadDatas[7] = y2;
quadDatas[8] = 0;
quadDatas[9] = x1;
quadDatas[10] = y2;
quadDatas[11] = 0;
quadDatas[12] = x2;
quadDatas[13] = y1;
quadDatas[14] = 0;
quadDatas[15] = x2;
quadDatas[16] = y2;
quadDatas[17] = 0;
glBindTexture(0);
FloatBuffer floatBuff = generateTemporaryFloatBuffer(quadDatas);
GLES10.glDisableClientState(GLES10.GL_TEXTURE_COORD_ARRAY);
GLES10.glVertexPointer(3, GLES10.GL_FLOAT, 3 * 4, floatBuff);
GLES10.glDrawArrays(GLES10.GL_TRIANGLES, 0, quadDatas.length / 3);
GLES10.glEnableClientState(GLES10.GL_TEXTURE_COORD_ARRAY);
}
@Override
public void glPushMatrix() {
GLES10.glPushMatrix();
}
@Override
public void glTranslatef(float x, float y, float z) {
GLES10.glTranslatef(x, y, z);
}
@Override
public void glScalef(float x, float y, float z) {
GLES10.glScalef(x, y, z);
}
@Override
public void glPopMatrix() {
GLES10.glPopMatrix();
}
@Override
public void color(float red, float green, float blue, float alpha) {
GLES10.glColor4f(red, green, blue, alpha);
}
private FloatBuffer reuseableBuffer = null;
private ByteBuffer quadEleementBuffer;
private FloatBuffer reuseableBufferDuplicate;
private FloatBuffer generateTemporaryFloatBuffer(float[] points) {
int floatCount = points.length;
FloatBuffer b = createReusedBuffer(floatCount);
b.put(points);
b.position(0);
return b;
}
private FloatBuffer createReusedBuffer(int floatCount) {
if (reuseableBuffer == null || reuseableBuffer.position(0).capacity() < floatCount) {
ByteBuffer quadPoints = ByteBuffer.allocateDirect(floatCount * 4);
quadPoints.order(ByteOrder.nativeOrder());
reuseableBuffer = quadPoints.asFloatBuffer();
reuseableBufferDuplicate = reuseableBuffer.duplicate();
} else {
reuseableBuffer.position(0);
}
return reuseableBuffer;
}
@Override
public void drawLine(float[] points, boolean loop) {
if (points.length % 3 != 0) {
throw new IllegalArgumentException("Point array length needs to be multiple of 3.");
}
glBindTexture(0);
FloatBuffer floatBuff = generateTemporaryFloatBuffer(points);
GLES10.glDisableClientState(GLES10.GL_TEXTURE_COORD_ARRAY);
GLES10.glVertexPointer(3, GLES10.GL_FLOAT, 0, floatBuff);
GLES10.glDrawArrays(loop ? GLES10.GL_LINE_LOOP : GLES10.GL_LINE_STRIP, 0, points.length / 3);
GLES10.glEnableClientState(GLES10.GL_TEXTURE_COORD_ARRAY);
}
private int lastTexture = 0;
private void glBindTexture(int texture) {
if (texture != lastTexture) {
GLES10.glBindTexture(GLES10.GL_TEXTURE_2D, texture);
// System.out.println("Setting opengl texture: " + texture);
lastTexture = texture;
}
}
@Override
public void drawQuadWithTexture(int textureid, float[] geometry) {
if (quadEleementBuffer == null) {
generateQuadElementBuffer();
}
quadEleementBuffer.position(0);
glBindTexture(textureid);
FloatBuffer buffer = generateTemporaryFloatBuffer(geometry);
GLES10.glVertexPointer(3, GLES10.GL_FLOAT, 5 * 4, buffer);
FloatBuffer texbuffer = reuseableBufferDuplicate;
texbuffer.position(3);
GLES10.glTexCoordPointer(2, GLES10.GL_FLOAT, 5 * 4, texbuffer);
GLES10.glDrawElements(GLES10.GL_TRIANGLES, 6, GLES10.GL_UNSIGNED_BYTE, quadEleementBuffer);
}
private void generateQuadElementBuffer() {
quadEleementBuffer = ByteBuffer.allocateDirect(6);
quadEleementBuffer.put((byte) 0);
quadEleementBuffer.put((byte) 1);
quadEleementBuffer.put((byte) 3);
quadEleementBuffer.put((byte) 3);
quadEleementBuffer.put((byte) 1);
quadEleementBuffer.put((byte) 2);
}
@Override
public void drawTrianglesWithTexture(int textureid, float[] geometry) {
glBindTexture(textureid);
FloatBuffer buffer = generateTemporaryFloatBuffer(geometry);
GLES10.glVertexPointer(3, GLES10.GL_FLOAT, 5 * 4, buffer);
FloatBuffer texbuffer = reuseableBufferDuplicate;
texbuffer.position(3);
GLES10.glTexCoordPointer(2, GLES10.GL_FLOAT, 5 * 4, texbuffer);
GLES10.glDrawArrays(GLES10.GL_TRIANGLES, 0, geometry.length / 5);
}
@Override
public void drawTrianglesWithTextureColored(int textureid, float[] geometry) {
glBindTexture(textureid);
GLES10.glEnableClientState(GLES10.GL_COLOR_ARRAY);
FloatBuffer buffer = generateTemporaryFloatBuffer(geometry);
GLES10.glVertexPointer(3, GLES10.GL_FLOAT, 9 * 4, buffer);
FloatBuffer texbuffer = reuseableBufferDuplicate;
texbuffer.position(3);
GLES10.glTexCoordPointer(2, GLES10.GL_FLOAT, 9 * 4, texbuffer);
FloatBuffer colorbuffer = buffer.duplicate(); // we need it selden enogh
// to allocate a new one.
colorbuffer.position(5);
GLES10.glColorPointer(4, GLES10.GL_FLOAT, 9 * 4, colorbuffer);
GLES10.glDrawArrays(GLES10.GL_TRIANGLES, 0, geometry.length / 9);
GLES10.glDisableClientState(GLES10.GL_COLOR_ARRAY);
}
private static int getPowerOfTwo(int value) {
int guess = 1;
while (guess < value) {
guess *= 2;
}
return guess;
}
@Override
public int makeWidthValid(int width) {
return getPowerOfTwo(width);
}
@Override
public int makeHeightValid(int height) {
return getPowerOfTwo(height);
}
@Override
public int generateTexture(int width, int height, ShortBuffer data) {
// 1 byte aligned.
GLES10.glPixelStorei(GLES10.GL_UNPACK_ALIGNMENT, 1);
int texture = genTextureIndex();
if (texture == 0) {
return -1;
}
glBindTexture(texture);
GLES10.glTexImage2D(GLES10.GL_TEXTURE_2D, 0, GLES10.GL_RGBA, width, height, 0, GLES10.GL_RGBA, GLES10.GL_UNSIGNED_SHORT_5_5_5_1, data);
setTextureParameters();
return texture;
}
private static int genTextureIndex() {
int[] textureIndexes = new int[1];
GLES10.glGenTextures(1, textureIndexes, 0);
int texture = textureIndexes[0];
return texture;
}
/**
* Sets the texture parameters, assuming that the texture was just created and is bound.
*/
private static void setTextureParameters() {
GLES10.glTexParameterf(GLES10.GL_TEXTURE_2D, GLES10.GL_TEXTURE_MAG_FILTER, GLES10.GL_LINEAR);
GLES10.glTexParameterf(GLES10.GL_TEXTURE_2D, GLES10.GL_TEXTURE_MIN_FILTER, GLES10.GL_LINEAR);
GLES10.glTexParameterf(GLES10.GL_TEXTURE_2D, GLES10.GL_TEXTURE_WRAP_S, GLES10.GL_REPEAT);
GLES10.glTexParameterf(GLES10.GL_TEXTURE_2D, GLES10.GL_TEXTURE_WRAP_T, GLES10.GL_REPEAT);
}
@Override
public void updateTexture(int textureIndex, int left, int bottom, int width, int height, ShortBuffer data) {
glBindTexture(textureIndex);
GLES10.glTexSubImage2D(GLES10.GL_TEXTURE_2D, 0, left, bottom, width, height, GLES10.GL_RGBA, GLES10.GL_UNSIGNED_SHORT_5_5_5_1, data);
}
public int generateTextureAlpha(int width, int height) {
// 1 byte aligned.
GLES10.glPixelStorei(GLES10.GL_UNPACK_ALIGNMENT, 1);
int texture = genTextureIndex();
if (texture == 0) {
return -1;
}
ByteBuffer data = ByteBuffer.allocateDirect(width * height);
while (data.hasRemaining()) {
data.put((byte) 0);
}
data.rewind();
glBindTexture(texture);
GLES10.glTexImage2D(GLES10.GL_TEXTURE_2D, 0, GLES10.GL_ALPHA, width, height, 0, GLES10.GL_ALPHA, GLES10.GL_UNSIGNED_BYTE, data);
setTextureParameters();
return texture;
}
public void updateTextureAlpha(int textureIndex, int left, int bottom, int width, int height, ByteBuffer data) {
glBindTexture(textureIndex);
GLES10.glTexSubImage2D(GLES10.GL_TEXTURE_2D, 0, left, bottom, width, height, GLES10.GL_ALPHA, GLES10.GL_UNSIGNED_BYTE, data);
}
@Override
public void deleteTexture(int textureid) {
GLES10.glDeleteTextures(1, new int[] { textureid }, 0);
}
@Override
public void glMultMatrixf(float[] matrix, int offset) {
GLES10.glMultMatrixf(matrix, offset);
}
@Override
public TextDrawer getTextDrawer(EFontSize size) {
return AndroidTextDrawer.getInstance(size, this);
}
@Override
public void drawQuadWithTexture(int textureid, int geometryindex) {
if (quadEleementBuffer == null) {
generateQuadElementBuffer();
}
quadEleementBuffer.position(0);
glBindTexture(textureid);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryindex);
GLES11.glVertexPointer(3, GLES10.GL_FLOAT, 5 * 4, 0);
GLES11.glTexCoordPointer(2, GLES10.GL_FLOAT, 5 * 4, 3 * 4);
GLES11.glDrawElements(GLES10.GL_TRIANGLES, 6, GLES10.GL_UNSIGNED_BYTE, quadEleementBuffer);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
}
@Override
public boolean isGeometryValid(int geometryindex) {
return geometryindex > 0 && GLES11.glIsBuffer(geometryindex);
}
@Override
public void removeGeometry(int geometryindex) {
GLES11.glDeleteBuffers(1, new int[] { geometryindex }, 0);
}
public void reinit(int width, int height) {
GLES10.glMatrixMode(GLES10.GL_PROJECTION);
GLES10.glLoadIdentity();
GLES10.glMatrixMode(GLES10.GL_MODELVIEW);
GLES10.glLoadIdentity();
GLES10.glScalef(2f / width, 2f / height, -1);
// TODO: do not scale depth by 0.
GLES10.glTranslatef(-width / 2, -height / 2, .5f);
GLES10.glEnableClientState(GLES10.GL_VERTEX_ARRAY);
GLES10.glEnableClientState(GLES10.GL_TEXTURE_COORD_ARRAY);
GLES10.glAlphaFunc(GLES10.GL_GREATER, 0.1f);
GLES10.glEnable(GLES10.GL_ALPHA_TEST);
GLES10.glEnable(GLES10.GL_BLEND);
GLES10.glBlendFunc(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE_MINUS_SRC_ALPHA);
GLES10.glDepthFunc(GLES10.GL_LEQUAL);
GLES10.glEnable(GLES10.GL_DEPTH_TEST);
GLES10.glEnable(GLES10.GL_TEXTURE_2D);
}
@Override
public void drawTrianglesWithTexture(int textureid, int geometryindex, int triangleCount) {
glBindTexture(textureid);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryindex);
GLES11.glVertexPointer(3, GLES11.GL_FLOAT, 5 * 4, 0);
GLES11.glTexCoordPointer(2, GLES11.GL_FLOAT, 5 * 4, 3 * 4);
GLES11.glDrawArrays(GLES11.GL_TRIANGLES, 0, triangleCount * 3);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
}
@Override
public int generateGeometry(int bytes) {
int[] vertexBuffIds = new int[] { 0 };
GLES11.glGenBuffers(1, vertexBuffIds, 0);
int vertexBufferId = vertexBuffIds[0];
if (vertexBufferId == 0) {
return -1;
}
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, vertexBufferId);
GLES11.glBufferData(GLES11.GL_ARRAY_BUFFER, bytes, null, GLES11.GL_DYNAMIC_DRAW);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
return vertexBufferId;
}
@Override
public void drawTrianglesWithTextureColored(int textureid, int geometryindex, int triangleCount) {
glBindTexture(textureid);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryindex);
GLES11.glVertexPointer(3, GLES11.GL_FLOAT, 6 * 4, 0);
GLES11.glTexCoordPointer(2, GLES11.GL_FLOAT, 6 * 4, 3 * 4);
GLES11.glColorPointer(4, GLES11.GL_UNSIGNED_BYTE, 6 * 4, 5 * 4);
GLES11.glEnableClientState(GLES11.GL_COLOR_ARRAY);
GLES11.glDrawArrays(GLES11.GL_TRIANGLES, 0, triangleCount * 3);
GLES11.glDisableClientState(GLES11.GL_COLOR_ARRAY);
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
}
@Override
public int storeGeometry(float[] geometry) {
int bytes = 4 * geometry.length;
// ByteBuffer buffer = ByteBuffer.allocateDirect(bytes);
// for (int i = 0; i < geometry.length; i++) {
// buffer.putFloat(geometry[i]);
// buffer.rewind();
// int[] vertexBuffIds = new int[] {
// GLES11.glGenBuffers(1, vertexBuffIds, 0);
// int vertexBufferId = vertexBuffIds[0];
// if (vertexBufferId == 0) {
// return -1;
// GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, vertexBufferId);
// GLES11.glBufferData(GLES11.GL_ARRAY_BUFFER, bytes, null,
// GLES11.GL_DYNAMIC_DRAW);
// GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
int vertexBufferId = generateGeometry(bytes);
GLBuffer buffer = startWriteGeometry(vertexBufferId);
for (int i = 0; i < geometry.length; i++) {
buffer.putFloat(geometry[i]);
}
endWriteGeometry(vertexBufferId);
return vertexBufferId;
}
private GraphicsByteBuffer currentBuffer = null;
private float[] quadDatas;
@Override
public GLBuffer startWriteGeometry(int geometryindex) {
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryindex);
currentBuffer = new GraphicsByteBuffer();
return currentBuffer;
}
@Override
public void endWriteGeometry(int geometryindex) {
if (currentBuffer != null) {
currentBuffer.writeBuffer();
currentBuffer.position(0);
}
GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0);
}
public static final class GraphicsByteBuffer implements GLDrawContext.GLBuffer {
private static int BUFFER_LENGTH = 1024;
private static ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_LENGTH).order(ByteOrder.nativeOrder());
private static int bufferstart = 0;
private static int bufferlength = 0;
private void assertBufferHas(int remaining) {
if (bufferlength + remaining > BUFFER_LENGTH) {
writeBuffer();
bufferstart += bufferlength;
bufferlength = 0;
buffer.position(0);
}
}
@Override
public void putFloat(float f) {
assertBufferHas(4);
buffer.putFloat(f);
bufferlength += 4;
}
@Override
public void putByte(byte b) {
assertBufferHas(1);
buffer.put(b);
bufferlength++;
}
@Override
public void position(int position) {
if (bufferstart + bufferlength != position) {
if (bufferlength > 0) {
writeBuffer();
}
bufferstart = position;
bufferlength = 0;
buffer.position(0);
}
}
private void writeBuffer() {
buffer.position(0);
GLES11.glBufferSubData(GLES11.GL_ARRAY_BUFFER, bufferstart, bufferlength, buffer);
}
}
public Context getAndroidContext() {
return context;
}
}
|
/*
* $Id: Treatment.java,v 1.11 2008-07-11 17:27:39 schroedn Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.10 2007/10/31 15:55:38 pandyas
* Fixed #8188 Rename UnctrlVocab items to AlternEntry
*
* Revision 1.9 2006/04/17 19:13:46 pandyas
* caMod 2.1 OM changes and added log/id header
*
*/
package gov.nih.nci.camod.domain;
import gov.nih.nci.camod.util.Duplicatable;
import java.io.Serializable;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author rajputs
*/
public class Treatment extends BaseObject implements Serializable, Duplicatable
{
private static final long serialVersionUID = 3258485453799404851L;
private String regimen;
private String dosage;
private String dosageUnit;
private String administrativeRoute;
private String adminRouteAlternEntry;
private String ageAtTreatment;
private String ageAtTreatmentUnit;
private SexDistribution sexDistribution;
private String route;
/**
* @return Returns the sexDistribution.
*/
public SexDistribution getSexDistribution()
{
return sexDistribution;
}
/**
* @param sexDistribution
* The sexDistribution to set.
*/
public void setSexDistribution(SexDistribution sexDistribution)
{
this.sexDistribution = sexDistribution;
}
/**
* @return Returns the administrativeRoute.
*/
public String getAdministrativeRoute()
{
return administrativeRoute;
}
/**
* @param administrativeRoute
* The administrativeRoute to set.
*/
public void setAdministrativeRoute(String administrativeRoute)
{
this.administrativeRoute = administrativeRoute;
}
/**
* @return Returns the ageAtTreatment.
*/
public String getAgeAtTreatment()
{
return ageAtTreatment;
}
/**
* @param ageAtTreatment
* The ageAtTreatment to set.
*/
public void setAgeAtTreatment(String ageAtTreatment)
{
this.ageAtTreatment = ageAtTreatment;
}
/**
* @return Returns the ageAtTreatmentUnit.
*/
public String getAgeAtTreatmentUnit()
{
return ageAtTreatmentUnit;
}
/**
* @param ageAtTreatmentUnit
* The ageAtTreatmentUnit to set.
*/
public void setAgeAtTreatmentUnit(String ageAtTreatmentUnit)
{
this.ageAtTreatmentUnit = ageAtTreatmentUnit;
}
/**
* @return Returns the dosage.
*/
public String getDosage()
{
return dosage;
}
/**
* @return Returns the dosageUnit.
*/
public String getDosageUnit()
{
return dosageUnit;
// String tmpDosage = dosageUnit;
// //Trim leading Zeros
// if (tmpDosage == null)
// return null;
// char[] chars = tmpDosage.toCharArray();
// int index = 0;
// for (; index < tmpDosage.length(); index++)
// if (chars[index] != '0')
// break;
// tmpDosage = (index == 0) ? tmpDosage : tmpDosage.substring(index);
// //if mg/kg is contained in string, replace it with mg/kg/injections
// // Compile regular expression
// Pattern pattern = Pattern.compile("mg/kg");
// // Replace all occurrences of pattern in input
// Matcher matcher = pattern.matcher(tmpDosage);
// tmpDosage = matcher.replaceAll("mg/kg/injections");
// return tmpDosage;
}
/**
* @param dosage
* The dosage to set.
*/
public void setDosage(String dosage)
{
this.dosage = dosage;
}
/**
* @param dosageUnit
* The dosageUnit to set.
*/
public void setDosageUnit(String dosageUnit)
{
this.dosageUnit = dosageUnit;
}
/**
* @return Returns the regimen.
*/
public String getRegimen()
{
return regimen;
}
/**
* @param regimen
* The regimen to set.
*/
public void setRegimen(String regimen)
{
this.regimen = regimen;
}
public String getRoute()
{
StringTokenizer parser = new StringTokenizer(this.regimen, ",");
route = parser.nextToken();
while (parser.hasMoreTokens() && !route.startsWith("Drug given-"))
{
route = parser.nextToken();
}
// Compile regular expression
Pattern pattern = Pattern.compile("Drug given-");
// Replace all occurrences of pattern in input
Matcher matcher = pattern.matcher(route);
route = matcher.replaceAll("");
return route;
}
public void setRoute(String route)
{
this.route = route;
}
public String getSchedule()
{
StringTokenizer parser = new StringTokenizer(this.regimen, ",");
route = parser.nextToken();
while (parser.hasMoreTokens() && !route.startsWith("Schedule-"))
{
route = parser.nextToken();
}
// Compile regular expression
Pattern pattern = Pattern.compile("Schedule-");
// Replace all occurrences of pattern in input
Matcher matcher = pattern.matcher(route);
route = matcher.replaceAll("");
return route;
}
public String getVehicle()
{
StringTokenizer parser = new StringTokenizer(this.regimen, ",");
route = "";
while (parser.hasMoreTokens() && !route.startsWith(" Vehicle-"))
{
route = parser.nextToken();
}
// Compile regular expression
Pattern pattern = Pattern.compile(" Vehicle-");
// Replace all occurrences of pattern in input
Matcher matcher = pattern.matcher(route);
route = matcher.replaceAll("");
return route;
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
String result = super.toString() + " - ";
result += this.getRegimen() + " - " + this.getDosage();
return result;
}
public boolean equals(Object o)
{
if (!super.equals(o))
return false;
if (!(this.getClass().isInstance(o)))
return false;
return true;
}
/**
* @return the adminRouteAlternEntry
*/
public String getAdminRouteAlternEntry() {
return adminRouteAlternEntry;
}
/**
* @param adminRouteAlternEntry the adminRouteAlternEntry to set
*/
public void setAdminRouteAlternEntry(String adminRouteAlternEntry) {
this.adminRouteAlternEntry = adminRouteAlternEntry;
}
}
|
package com.antipodalwall;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class AntipodalWall extends ViewGroup {
private int columns;
private float columnWidth = 0;
public AntipodalWall(Context context, AttributeSet attrs) {
super(context, attrs);
//Load the attrs from the XML
//- number of columns
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AntipodalWallAttrs);
columns = a.getInt(R.styleable.AntipodalWallAttrs_columns, 1);
if(columns < 1)
columns = 1;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
columnWidth = parentWidth / columns;
for(int i=0;i<getChildCount();i++) {
View child = getChildAt(i);
//force the width of the children to be that of the columns...
int childWidthSpec = MeasureSpec.makeMeasureSpec((int)columnWidth, MeasureSpec.EXACTLY);
//... but let them grow vertically
int childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
child.measure(childWidthSpec, childHeightSpec);
}
setMeasuredDimension(parentWidth, parentHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int[] columns_t = new int[columns];
for(int i=0;i<getChildCount();i++) {
View view = getChildAt(i);
//We place each child in the column that has the less height to the moment
int column = findLowerColumn(columns_t);
int left = l + (int)(columnWidth * column);
view.layout(left, columns_t[column], left + view.getMeasuredWidth(), columns_t[column] + view.getMeasuredHeight());
columns_t[column] = columns_t[column] + view.getMeasuredHeight();
}
}
private int findLowerColumn(int[] columns) {
int minValue = columns[0];
int column = 0;
for(int i=1;i<columns.length;i++){
if(columns[i] < minValue){
minValue = columns[i];
column = i;
}
}
return column;
}
}
|
package com.levelup.logutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
public class FileLogger {
private static final String LOG_NAME = "log.csv";
private static final String LOG_NAME_ALTERNATIVE = "log_a.csv";
private static final String LOG_HEAD = "Time,Level,PID,TID,App,Tag,Message";
private static final String TAG = "FileLogger";
private static final int MSG_WRITE = 0; // paired with a LogMessage
private static final int MSG_COLLECT = 1;
private static final int MSG_CLEAR = 2;
private static final int MSG_OPEN = 3;
private final File file1;
private final File file2;
private long maxFileSize = 102400;
private File mCurrentLogFile;
private Writer writer;
private String mTag;
private String applicationTag;
private Handler mSaveStoreHandler;
/**
* Path where the log must be collected
*/
private File finalPath;
private FLogLevel logLevel = FLogLevel.I;
/**
* Create a file for writing logs.
*
* @param logFolder
* the folder path where the logs are stored
* @param tag
* tag used for message without tag
* @throws IOException
*/
public FileLogger(File logFolder, String tag) throws IOException {
this(logFolder);
this.mTag = tag;
}
/**
* Create a file for writing logs.
*
* @param logFolder
* the folder path where the logs are stored
* @throws IOException
*/
@SuppressLint("HandlerLeak")
public FileLogger(File logFolder) throws IOException {
this.file1 = new File(logFolder, LOG_NAME);
this.file2 = new File(logFolder, LOG_NAME_ALTERNATIVE);
if (!logFolder.exists()) logFolder.mkdirs();
if (!logFolder.isDirectory()) {
Log.e(TAG, logFolder + " is not a folder");
throw new IOException("Path is not a directory");
}
if (!logFolder.canWrite()) {
Log.e(TAG, logFolder + " is not a writable");
throw new IOException("Folder is not writable");
}
mCurrentLogFile = chooseFileToWrite();
// Initializing the HandlerThread
HandlerThread handlerThread = new HandlerThread("FileLogger", android.os.Process.THREAD_PRIORITY_BACKGROUND);
if (!handlerThread.isAlive()) {
handlerThread.start();
mSaveStoreHandler = new Handler(handlerThread.getLooper()) {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_OPEN:
try {
closeWriter();
} catch (IOException e) {
}
openWriter();
break;
case MSG_WRITE:
try {
LogMessage logmsg = (LogMessage) msg.obj;
if (writer==null)
Log.e(TAG, "no writer");
else {
writer.append(logmsg.formatCsv());
writer.flush();
}
} catch (OutOfMemoryError e) {
Log.e(TAG, e.getClass().getSimpleName() + " : " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getClass().getSimpleName() + " : " + e.getMessage());
}
verifyFileSize();
break;
case MSG_COLLECT:
if (!mCurrentLogFile.exists() || mCurrentLogFile.length() == 0) {
((LogCollecting) msg.obj).onEmptyLogCollected();
break;
}
// Get the phone information
if (finalPath.getParentFile()!=null)
finalPath.getParentFile().mkdirs();
try {
finalPath.createNewFile();
if (!finalPath.canWrite())
((LogCollecting) msg.obj).onLogCollectingError("Can't write on "+finalPath);
else {
finalPath.delete();
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(finalPath, true), "UTF-8");
out.append(LOG_HEAD);
out.append('\n');
out.flush();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage(), e);
} catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException: " + e.getMessage(), e);
}
// Merge the files
final File olderLogFile;
if (mCurrentLogFile==file2)
olderLogFile = file1;
else
olderLogFile = file2;
if (olderLogFile.exists())
mergeFile(olderLogFile, finalPath);
mergeFile(mCurrentLogFile, finalPath);
((LogCollecting) msg.obj).onLogCollected(finalPath, "text/csv");
}
} catch (IOException e) {
((LogCollecting) msg.obj).onLogCollectingError(e.getMessage()+" - file:"+finalPath);
}
break;
case MSG_CLEAR:
try {
closeWriter();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
} finally {
file1.delete();
file2.delete();
mCurrentLogFile = file1;
openWriter();
}
break;
}
}
};
if (mSaveStoreHandler == null) throw new NullPointerException("Handler is null");
mSaveStoreHandler.sendEmptyMessage(MSG_OPEN);
}
}
public void setLogLevel(FLogLevel level) {
logLevel = level;
}
public void setMaxFileSize(long maxFileSize) {
this.maxFileSize = maxFileSize;
}
private File chooseFileToWrite() {
if (!file1.exists() && !file2.exists())
return file1;
if (file1.exists() && file1.length() < maxFileSize)
return file1;
return file2;
}
public void d(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.D))
write('d', tag, msg, tr);
}
public void d(String tag, String msg) {
if (logLevel.allows(FLogLevel.D))
write('d', tag, msg);
}
public void d(String msg) {
if (logLevel.allows(FLogLevel.D))
write('d', msg);
}
public void e(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.E))
write('e', tag, msg, tr);
}
public void e(String tag, String msg) {
if (logLevel.allows(FLogLevel.E))
write('e', tag, msg);
}
public void e(String msg) {
if (logLevel.allows(FLogLevel.E))
write('e', msg);
}
public void wtf(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.WTF))
write('f', tag, msg, tr);
}
public void wtf(String tag, String msg) {
if (logLevel.allows(FLogLevel.WTF))
write('f', tag, msg);
}
public void wtf(String msg) {
if (logLevel.allows(FLogLevel.WTF))
write('f', msg);
}
public void i(String msg, String tag, Throwable tr) {
if (logLevel.allows(FLogLevel.I))
write('i', tag, msg, tr);
}
public void i(String msg, String tag) {
if (logLevel.allows(FLogLevel.I))
write('i', tag, msg);
}
public void i(String msg) {
if (logLevel.allows(FLogLevel.I))
write('i', msg);
}
public void v(String msg, String tag, Throwable tr) {
if (logLevel.allows(FLogLevel.V))
write('v', tag, msg, tr);
}
public void v(String msg, String tag) {
if (logLevel.allows(FLogLevel.V))
write('v', tag, msg);
}
public void v(String msg) {
if (logLevel.allows(FLogLevel.V))
write('v', msg);
}
public void w(String tag, String msg, Throwable tr) {
if (logLevel.allows(FLogLevel.W))
write('w', tag, msg, tr);
}
public void w(String tag, String msg) {
if (logLevel.allows(FLogLevel.W))
write('w', tag, msg);
}
public void w(String msg) {
if (logLevel.allows(FLogLevel.W))
write('w', msg);
}
private void write(char lvl, String message) {
String tag;
if (mTag == null)
tag = TAG;
else
tag = mTag;
write(lvl, tag, message);
}
private void write(char lvl, String tag, String message) {
write(lvl, tag, message, null);
}
protected void write(char lvl, String tag, String message, Throwable tr) {
if (tag == null) {
write(lvl, message);
return;
}
Message htmsg = Message.obtain(mSaveStoreHandler, MSG_WRITE, new LogMessage(lvl, tag, getApplicationLocalTag(), Thread.currentThread().getName(), message, tr));
mSaveStoreHandler.sendMessage(htmsg);
}
private static class LogMessage {
private static SimpleDateFormat dateFormat; // must always be used in the same thread
private static Date mDate;
private final long now;
private final char level;
private final String tag;
private final String appTag;
private final String threadName;
private final String msg;
private final Throwable cause;
private String date;
LogMessage(char lvl, String tag, String appTag, String threadName, String msg, Throwable tr) {
this.now = System.currentTimeMillis();
this.level = lvl;
this.tag = tag;
this.appTag = appTag;
this.threadName = threadName;
this.msg = msg;
this.cause = tr;
if (msg == null) {
Log.e(TAG, "No message");
}
}
private void addCsvHeader(final StringBuilder csv) {
if (dateFormat==null)
dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.getDefault());
if (date==null && null!=dateFormat) {
if (null==mDate)
mDate = new Date();
mDate.setTime(now);
date = dateFormat.format(mDate);
}
csv.append(date.toString());
csv.append(',');
csv.append(level);
csv.append(',');
csv.append(android.os.Process.myPid());
csv.append(',');
if (threadName!=null)
csv.append(threadName);
csv.append(',');
if (appTag!=null)
csv.append(appTag);
csv.append(',');
if (tag!=null)
csv.append(tag);
csv.append(',');
}
private void addException(final StringBuilder csv, Throwable tr) {
if (tr==null)
return;
final StringBuilder sb = new StringBuilder(256);
sb.append(tr.getClass());
sb.append(": ");
sb.append(tr.getMessage());
sb.append('\n');
for (StackTraceElement trace : tr.getStackTrace()) {
//addCsvHeader(csv);
sb.append(" at ");
sb.append(trace.getClassName());
sb.append('.');
sb.append(trace.getMethodName());
sb.append('(');
sb.append(trace.getFileName());
sb.append(':');
sb.append(trace.getLineNumber());
sb.append(')');
sb.append('\n');
}
addException(sb, tr.getCause());
csv.append(sb.toString().replace(';', '-').replace(',', '-').replace('"', '\''));
}
public CharSequence formatCsv() {
final StringBuilder csv = new StringBuilder(256);
addCsvHeader(csv);
csv.append('"');
if (msg != null) csv.append(msg.replace(';', '-').replace(',', '-').replace('"', '\''));
csv.append('"');
csv.append('\n');
if (cause!=null) {
addCsvHeader(csv);
csv.append('"');
addException(csv, cause);
csv.append('"');
csv.append('\n');
}
return csv;
}
}
private String getApplicationLocalTag() {
if (applicationTag == null) applicationTag = getApplicationTag();
return applicationTag;
}
/**
* remove all the current log entries and start from scratch
*/
public void clear() {
mSaveStoreHandler.sendEmptyMessage(MSG_CLEAR);
}
/**
* Collects the logs. Make sure finalPath have been set before.
*
* @param context
* @param listener
*/
public void collectlogs(Context context, LogCollecting listener) {
if (mCurrentLogFile == null) {
listener.onLogCollectingError("Log file is invalid.");
} else if (finalPath==null) {
listener.onLogCollectingError("Final path have not been set");
} else {
Message msg = Message.obtain(mSaveStoreHandler, MSG_COLLECT, listener);
mSaveStoreHandler.sendMessage(msg);
}
}
private void mergeFile(File otherFile, File finalFile) {
try {
InputStream instream = new FileInputStream(otherFile);
BufferedReader in = new BufferedReader(new InputStreamReader(instream));
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(finalFile, true), "UTF-8");
String line;
while ((line = in.readLine()) != null) {
out.append(line);
out.append('\n');
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
FLog.e(TAG, "FileNotFoundException: " + e.getMessage(), e);
} catch (IOException e) {
FLog.e(TAG, "IOException: " + e.getMessage(), e);
}
}
/**
* a special tag to be added to the logs
* @return
*/
public String getApplicationTag() {
return "";
}
private void verifyFileSize() {
if (mCurrentLogFile != null) {
long size = mCurrentLogFile.length();
if (size > maxFileSize) {
try {
closeWriter();
} catch (IOException e) {
FLog.e(TAG, "Can't use file : "+ mCurrentLogFile, e);
} finally {
if (mCurrentLogFile==file2)
mCurrentLogFile = file1;
else
mCurrentLogFile = file2;
mCurrentLogFile.delete();
openWriter();
}
}
}
}
private void openWriter() {
if (writer==null)
try {
writer = new OutputStreamWriter(new FileOutputStream(mCurrentLogFile, true), "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "can't get a writer for " +mCurrentLogFile+" : "+e.getMessage());
} catch (FileNotFoundException e) {
Log.e(TAG, "can't get a writer for " +mCurrentLogFile+" : "+e.getMessage());
}
}
private void closeWriter() throws IOException {
if (writer!=null) {
writer.close();
writer = null;
}
}
void setFinalPath(File finalPath) {
this.finalPath = finalPath;
}
}
|
package io.github.panpog1.potions;
import java.util.HashSet;
import java.util.Set;
public class Cauldron {
private static String[] constIdgNames = { "Ae", "T", "H", "Ah", "S" };
private static final String packageName = Cauldron.class.getPackage().getName();
public Set<Compound> idgs = new HashSet<Compound>();
public boolean h;
public String toString() {
if (idgs.isEmpty()) {
return "Cauldron is empty";
}
String r = "Cauldron contains: ";
for (Compound idg : idgs) {
String prefix = (h ? Integer.toHexString(idg.hashCode()) + ":" : "");
r += prefix + idg + " ";
}
return r;
}
void add(String next) throws CompoundParseException {
add(parse(next));
}
void add(Compound next) {
idgs.add(next);
boolean done = false;
while (!done) {
done = true;
for (Compound idg : idgs) {
if (idg.react(this)) {
done = false;
break;
}
}
}
}
static Compound parse(String s) throws CompoundParseException {
return parse(s, s, 0);
}
private static Compound parse(String all, String s, int offset) throws CompoundParseException {
// T S and H are in Add
if (s.isEmpty())
throw new CompoundParseException(all, offset);
s = numbersToLetters(s.trim());
if (s == null)
throw new CompoundParseException(all, offset);
if (s.startsWith("U")) {
Compound inner = parse(all, s.substring(1), offset + 1);
inner.applyU();
return inner;
}
if (s.startsWith("E")) {
Compound inner = parse(all, s.substring(1), offset + 1);
return new E(inner);
}
if (s.startsWith("\"") && s.endsWith("\"")) {
s = s.substring(1, s.length() - 1);
offset++;
if (s.contains("\""))
throw new CompoundParseException(all, s.indexOf("\""));
if (s.contains(" "))
throw new CompoundParseException(all, s.indexOf(" "));
return new Base(s);
}
if (s.startsWith("R")) {
Compound inner = parse(all, s.substring(1), offset + 1);
return new R(inner);
}
if (s.startsWith("If(")) {
return parseIf(all, s, offset);
}
return checkConstIdgNames(all, s, offset);
}
static Compound parseIf(String all, String s, int offset) throws CompoundParseException {
if (!s.endsWith(")"))
throw new CompoundParseException(all, offset + s.length());
offset += 3;
s = s.substring(3, s.length() - 1);
int i = 0;
int parens = 0;
boolean fail = true;
while (i < s.length()) {
if (s.charAt(i) == ',' && parens == 0) {
fail = false;
break;
} else if (s.charAt(i) == '(') {
parens++;
} else if (s.charAt(i) == ')') {
parens
if (parens > 0) {
throw new CompoundParseException(all, offset + i);
}
}
i++;
}
if (fail)
throw new CompoundParseException(all, offset);
Compound condition = Cauldron.parse(all, s.substring(0, i), offset);
Compound body = Cauldron.parse(all, s.substring(i + 1), offset + i + 1);
return new If(condition, body);
}
private static Compound checkConstIdgNames(String all, String s, int offset)
throws CompoundParseException {
for (String constIdgName : constIdgNames) {
if (s.startsWith(constIdgName)) {
if (!s.equals(constIdgName)) {
throw new CompoundParseException(all, offset + constIdgName.length());
}
try {
Class<?> obj;
obj = Class.forName(packageName + "." + constIdgName);
@SuppressWarnings("unchecked")
Class<Compound> clazz = (Class<Compound>) obj;
return clazz.getConstructor().newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
throw new CompoundParseException(all, offset);
}
static String numbersToLetters(String s) {
if (Character.isDigit(s.charAt(0))) {
boolean failure = true;
for (int i = 1; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
String prefix = "";
int times = Integer.parseInt(s.substring(0, i)) - 1;
s = s.substring(i);
String first = s.substring(0, 1);
for (int j = 0; j < times; j++) {
prefix += first;
}
failure = false;
s = prefix + s;
break;
}
}
if (failure)
return null;
}
return s;
}
}
|
package top.zibin.luban;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.annotation.WorkerThread;
import android.util.Log;
import java.io.File;
import java.io.IOException;
public class Luban implements Handler.Callback {
private static final String TAG = "Luban";
private static final String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache";
private static final int MSG_COMPRESS_SUCCESS = 0;
private static final int MSG_COMPRESS_START = 1;
private static final int MSG_COMPRESS_ERROR = 2;
private File file;
private OnCompressListener onCompressListener;
private Handler mHandler;
private Luban(Builder builder) {
this.file = builder.file;
this.onCompressListener = builder.onCompressListener;
mHandler = new Handler(Looper.getMainLooper(), this);
}
public static Builder with(Context context) {
return new Builder(context);
}
/**
* Returns a file with a cache audio name in the private cache directory.
*
* @param context
* A context.
*/
private File getImageCacheFile(Context context) {
if (getImageCacheDir(context) != null) {
return new File(getImageCacheDir(context) + "/" + System.currentTimeMillis() + (int) (Math.random() * 1000) + ".jpg");
}
return null;
}
/**
* Returns a directory with a default name in the private cache directory of the application to
* use to store retrieved audio.
*
* @param context
* A context.
*
* @see #getImageCacheDir(Context, String)
*/
@Nullable
private File getImageCacheDir(Context context) {
return getImageCacheDir(context, DEFAULT_DISK_CACHE_DIR);
}
/**
* Returns a directory with the given name in the private cache directory of the application to
* use to store retrieved media and thumbnails.
*
* @param context
* A context.
* @param cacheName
* The name of the subdirectory in which to store the cache.
*
* @see #getImageCacheDir(Context)
*/
@Nullable
private File getImageCacheDir(Context context, String cacheName) {
File cacheDir = context.getExternalCacheDir();
if (cacheDir != null) {
File result = new File(cacheDir, cacheName);
if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {
// File wasn't able to create a directory, or the result exists but not a directory
return null;
}
return result;
}
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "default disk cache dir is null");
}
return null;
}
/**
* start asynchronous compress thread
*/
@UiThread private void launch(final Context context) {
if (file == null && onCompressListener != null) {
onCompressListener.onError(new NullPointerException("image file cannot be null"));
}
new Thread(new Runnable() {
@Override public void run() {
try {
mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_START));
File result = new Engine(file, getImageCacheFile(context)).compress();
mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_SUCCESS, result));
} catch (IOException e) {
mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_ERROR, e));
}
}
}).start();
}
/**
* start compress and return the file
*/
@WorkerThread private File get(final Context context) throws IOException {
return new Engine(file, getImageCacheFile(context)).compress();
}
@Override public boolean handleMessage(Message msg) {
if (onCompressListener == null) return false;
switch (msg.what) {
case MSG_COMPRESS_START:
onCompressListener.onStart();
break;
case MSG_COMPRESS_SUCCESS:
onCompressListener.onSuccess((File) msg.obj);
break;
case MSG_COMPRESS_ERROR:
onCompressListener.onError((Throwable) msg.obj);
break;
}
return false;
}
public static class Builder {
private Context context;
private File file;
private OnCompressListener onCompressListener;
Builder(Context context) {
this.context = context;
}
private Luban build() {
return new Luban(this);
}
public Builder load(File file) {
this.file = file;
return this;
}
public Builder putGear(int gear) {
return this;
}
public Builder setCompressListener(OnCompressListener listener) {
this.onCompressListener = listener;
return this;
}
public void launch() {
build().launch(context);
}
public File get() throws IOException {
return build().get(context);
}
}
}
|
package ControladoresDAO;
import java.util.ArrayList;
import Entities.ChartData;
import Utils.ConfigManager;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetChartData implements Serializable{
private String driver="";
private String protocol="";
private String usrname="";
private String password="";
public String GenerateJSonChartData(String jsonp, String kind) throws JSONException, SQLException
{
String chartType=jsonp;
List<String> result = new ArrayList();
String kindOfReport="Barios";
if (kind.equals("1")){
kindOfReport="Categorias";
result=top10CatRanking();
} else {
result=top10BarrioRanking();
}
JSONObject finalJSonObj=new JSONObject();
ChartData cd;
ArrayList <ChartData> chartDataArray=new ArrayList<ChartData>();
if (!result.isEmpty()){
for (int i=0; i<result.size(); i++){
String[] l = result.get(i).split(";");
cd=new ChartData();
cd.setParametro(l[0]);
cd.setCantidad(Integer.parseInt(l[1]));
chartDataArray.add(cd);
}
}
JSONArray chartData=new JSONArray();
JSONArray xaxisArr =new JSONArray();
JSONObject xaxisObj = new JSONObject();
JSONObject dataObj = new JSONObject();
JSONArray cantidad =new JSONArray();
for (int i=0; i<chartDataArray.size();i++)
{
System.out.println("Json data "+i);
xaxisArr.put(chartDataArray.get(i).getParametro());
cantidad.put(chartDataArray.get(i).getCantidad());
}
xaxisObj.put("category", xaxisArr);
chartData.put(xaxisObj);
dataObj = new JSONObject();
dataObj.put("name",kindOfReport);
dataObj.put("color","##5cb85c");
dataObj.put("data",cantidad);
chartData.put(dataObj);
System.out.println("Json data "+ chartData);
finalJSonObj.put(chartType, chartData);
String tempStr=jsonp+"("+finalJSonObj.toString()+")";
return tempStr;
}
List top10CatRanking() throws SQLException{
List result = new ArrayList();
Connection con=null;
Statement s = null;
ResultSet rs = null;
try{
ConfigManager configuracion = new ConfigManager();
Properties propiedades = configuracion.getConfigFile("Config.properties");
driver=propiedades.getProperty("postgress-driver");
protocol=propiedades.getProperty("jdbc-url");
usrname=propiedades.getProperty("tsig-usr");
password=propiedades.getProperty("tsig-pwd");
String cc=protocol+"?" +
"user="+usrname+"&password="+password;
Class.forName(driver).newInstance();
con = DriverManager.getConnection(cc);
s = con.createStatement();
String query="select u.nombre , count(u.id) as cantidad from ( " +
"SELECT c.nombre as nombre, po.id as id " +
" FROM categoria c ,punto_ombu po " +
" WHERE c.id=po.id_categoria " +
"UNION " +
"SELECT c2.nombre as nombre, ro.id as id " +
" FROM categoria c2 ,referencia_ombu ro " +
" WHERE c2.id=ro.categoria_id " +
") as u " +
"GROUP BY u.nombre ORDER BY cantidad desc LIMIT 10";
rs = s.executeQuery(query);
while (rs.next()){
String category=rs.getString(1);
String count=rs.getString(2);
String toAdd=category+";"+count;
result.add(toAdd);
}
}catch (Exception e){
System.out.println("Error en ReportsSQLController;top10CatRanking "+e.toString());
}finally {
try{
if(rs!=null)
rs.close();
if(s!=null)
s.close();
if(con!=null)
con.close();
}catch (Exception e2){
System.out.println("Error en ReportsSQLController;top10CatRanking;closeConnection "+e2.toString());
}
}
return result;
}
List top10BarrioRanking() throws SQLException{
List result = new ArrayList();
Connection con=null;
Statement s = null;
ResultSet rs = null;
try{
ConfigManager configuracion = new ConfigManager();
Properties propiedades = configuracion.getConfigFile("Config.properties");
driver=propiedades.getProperty("postgress-driver");
protocol=propiedades.getProperty("jdbc-url");
usrname=propiedades.getProperty("tsig-usr");
password=propiedades.getProperty("tsig-pwd");
// String cc=protocol+"?" +
// "user="+usrname+"&password="+password;
Class.forName(driver).newInstance();
con = DriverManager.getConnection(protocol,usrname,password);
s = con.createStatement();
String query="SELECT res.barrio, COUNT(res.ombu_id) as cantidad FROM " +
"(SELECT DISTINCT b.barrio as barrio ,po.ombu_id as ombu_id " +
"FROM " +
// "ombues o, categoria c, \n" +
"barrios b, punto_ombu po WHERE st_contains(st_transform(st_setsrid(b.geom,32721),3857), po.geom) ) as res " +
"GROUP BY res.barrio ORDER BY cantidad desc " +
"LIMIT 10";
rs = s.executeQuery(query);
while (rs.next()){
String barrio=rs.getString(1);
String count=rs.getString(2);
String toAdd=barrio+";"+count;
result.add(toAdd);
}
}catch (Exception e){
System.out.println("Error en ReportsSQLController;top10CatRanking "+e.toString());
}finally {
try{
if(rs!=null)
rs.close();
if(s!=null)
s.close();
if(con!=null)
con.close();
}catch (Exception e2){
System.out.println("Error en ReportsSQLController;top10CatRanking;closeConnection "+e2.toString());
}
}
return result;
}
}
|
package org.holoeverywhere.addon;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import org.holoeverywhere.HoloEverywhere;
public abstract class IAddon {
private static final Map<Class<? extends IAddon>, IAddon> sAddonsMap = new HashMap<Class<? extends IAddon>, IAddon>();
@SuppressWarnings("unchecked")
public static <T extends IAddon> T addon(Class<T> clazz) {
try {
T t = (T) sAddonsMap.get(clazz);
if (t == null) {
t = clazz.newInstance();
sAddonsMap.put(clazz, t);
}
return t;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T extends IAddon> T addon(String classname) {
Class<T> clazz = makeAddonClass(classname);
return addon(clazz);
}
@SuppressWarnings("unchecked")
public static <T extends IAddon> Class<T> makeAddonClass(String classname) {
if (classname.contains(".")) {
try {
return (Class<T>) Class.forName(classname);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
return makeAddonClass(HoloEverywhere.PACKAGE + ".addon.Addon" + classname);
}
}
public static <T extends IAddon, Z extends IAddonBase<V>, V> Z obtain(Class<T> clazz, V object) {
return addon(clazz).obtain(object);
}
public static <T extends IAddon, Z extends IAddonBase<V>, V> Z obtain(String classname, V object) {
return addon(classname).obtain(object);
}
private final Map<Object, Object> mStatesMap = new WeakHashMap<Object, Object>();
private final Map<Class<?>, Class<? extends IAddonBase<?>>> mTypesMap = new HashMap<Class<?>, Class<? extends IAddonBase<?>>>();
@SuppressWarnings("unchecked")
public <T, V extends IAddonBase<T>> V obtain(T object) {
try {
WeakReference<V> addonRef = (WeakReference<V>) mStatesMap
.get(object);
V addon = addonRef == null ? null : addonRef.get();
if (addon != null) {
return addon;
}
Class<?> clazz = object.getClass();
while (!mTypesMap.containsKey(clazz)) {
if (clazz == Object.class) {
// Nothing was found
return null;
}
clazz = clazz.getSuperclass();
}
addon = ((Class<V>) mTypesMap.get(clazz)).newInstance();
addon.attach(object);
mStatesMap.put(object, new WeakReference<V>(addon));
return addon;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T> void register(Class<T> clazz, Class<? extends IAddonBase<T>> addonClazz) {
mTypesMap.put(clazz, addonClazz);
}
public void unregister(Class<?> clazz) {
mTypesMap.remove(clazz);
}
}
|
package nxt.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class VersionedEntityDbTable<T> extends EntityDbTable<T> {
protected VersionedEntityDbTable(DbKey.Factory<T> dbKeyFactory) {
super(dbKeyFactory, true);
}
@Override
public final void rollback(int height) {
rollback(table(), height, dbKeyFactory);
}
@Override
public final void delete(T t) {
if (t == null) {
return;
}
insert(t); // make sure current height is saved
DbKey dbKey = dbKeyFactory.newKey(t);
Db.getCache(table()).remove(dbKey);
try (Connection con = Db.getConnection();
PreparedStatement pstmt = con.prepareStatement("UPDATE " + table()
+ " SET latest = FALSE " + dbKeyFactory.getPKClause() + " AND latest = TRUE LIMIT 1")) {
dbKey.setPK(pstmt);
pstmt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
@Override
public final void trim(int height) {
trim(table(), height, dbKeyFactory);
}
static void rollback(String table, int height, DbKey.Factory dbKeyFactory) {
try (Connection con = Db.getConnection();
PreparedStatement pstmtSelectToDelete = con.prepareStatement("SELECT " + dbKeyFactory.getDistinctClause()
+ " FROM " + table + " WHERE height >= ?");
PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table
+ " WHERE height >= ?");
PreparedStatement pstmtSetLatest = con.prepareStatement("UPDATE " + table
+ " SET latest = TRUE " + dbKeyFactory.getPKClause() + " AND height ="
+ " (SELECT MAX(height) FROM " + table + dbKeyFactory.getPKClause() + ")")) {
pstmtSelectToDelete.setInt(1, height);
try (ResultSet rs = pstmtSelectToDelete.executeQuery()) {
while (rs.next()) {
DbKey dbKey = dbKeyFactory.newKey(rs);
pstmtDelete.setInt(1, height);
pstmtDelete.executeUpdate();
int i = 1;
i = dbKey.setPK(pstmtSetLatest, i);
i = dbKey.setPK(pstmtSetLatest, i);
pstmtSetLatest.executeUpdate();
Db.getCache(table).remove(dbKey);
}
}
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
static void trim(String table, int height, DbKey.Factory dbKeyFactory) {
//Logger.logDebugMessage("Trimming table " + table);
try (Connection con = Db.getConnection();
PreparedStatement pstmtSelectToDelete = con.prepareStatement("SELECT " + dbKeyFactory.getDistinctClause()
+ " FROM " + table + " WHERE height >= ?");
PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + dbKeyFactory.getPKClause()
+ " AND height < ?");
PreparedStatement pstmtSelectOlderToDelete = con.prepareStatement("SELECT " + dbKeyFactory.getDistinctClause()
+ " FROM " + table + " WHERE height < ?");
PreparedStatement pstmtDeleteOlder = con.prepareStatement("DELETE FROM " + table + dbKeyFactory.getPKClause()
+ " AND height < (SELECT MAX(height) FROM " + table + dbKeyFactory.getPKClause() + ")")) {
pstmtSelectToDelete.setInt(1, height);
try (ResultSet rs = pstmtSelectToDelete.executeQuery()) {
while (rs.next()) {
DbKey dbKey = dbKeyFactory.newKey(rs);
int i = 1;
i = dbKey.setPK(pstmtDelete, i);
pstmtDelete.setInt(i, height);
pstmtDelete.executeUpdate();
}
}
pstmtSelectOlderToDelete.setInt(1, height);
try (ResultSet rs = pstmtSelectOlderToDelete.executeQuery()) {
while (rs.next()) {
DbKey dbKey = dbKeyFactory.newKey(rs);
int i = 1;
i = dbKey.setPK(pstmtDeleteOlder, i);
i = dbKey.setPK(pstmtDeleteOlder, i);
pstmtDeleteOlder.executeUpdate();
}
}
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
}
|
package astargazer.map.heuristic;
import astargazer.map.WeightedPoint;
/**
* Euclidean distance squared heuristic
*
* @author Matt Yanos, Philip Diffenderfer
*/
public class HeuristicSquared extends HeuristicScheme
{
@Override
public float distance(WeightedPoint one, WeightedPoint two)
{
float dx = one.getCol() - two.getCol();
float dy = one.getRow() - two.getRow();
return dx * dx + dy * dy;
}
@Override
public String getLabel()
{
return "Euclidian Squared";
}
}
|
/* Use of the link grammar parsing system is subject to the terms of the */
/* forms, with or without modification, subject to certain conditions. */
package org.linkgrammar;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.CharacterIterator;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class LGService
{
private static boolean verbose = false;
private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Link Grammar requires each concurrent thread to initialize separately. This entails
// that each thread has a separate copy of the dictionaries which in unfortunate design,
// but nevertheless we want to avoid initializing before every parse activity so we
// maintain a thread local flag and initialize on demand only.
// XXX Except that this is not true (or is only partly true ... )
// The C library itself does not have this restriction; one
// dictionary can be shared by many threads. However, the java
// bindings do have this restriction; the java bindings were
// never designed to be run multi-threaded, and so this would
// need to be fixed.
// The main problem is to detect when a thread completes its work and therefore
// LinkGrammar.close should be called to free allocated memory. We leave that to the
// use of this class.
private static ThreadLocal<Boolean> initialized = new ThreadLocal<Boolean>()
{ protected Boolean initialValue() { return Boolean.FALSE; } };
/**
* <p>Return <code>true</code> if LinkGrammar is initialized for the current thread
* and <code>false</code> otherwise.
*/
public static boolean isInitialized()
{
return initialized.get();
}
/**
* <p>
* Initialize LinkGrammar for the current is this is not already done. Note that
* this method is called by all other methods in this class that invoke LinkGrammar
* so there's no really need to call it yourself. It is safe to call the method repeatedly.
* </p>
*/
public static void init()
{
if (!initialized.get())
{
LinkGrammar.init();
initialized.set(Boolean.TRUE);
}
}
/**
* <p>
* Cleanup allocated memory for use of LinkGrammar in the current thread.
* </p>
*/
public static void close()
{
LinkGrammar.close();
initialized.set(Boolean.FALSE);
}
private static void trace(String s)
{
if (verbose)
System.out.println("LG " + dateFormatter.format(new java.util.Date()) + " " + s);
}
private static boolean getBool(String name, Map<String, String> msg, boolean def)
{
String x = msg.get(name);
return x == null ? def : Boolean.valueOf(x);
}
private static int getInt(String name, Map<String, String> msg, int def)
{
String x = msg.get(name);
return x == null ? def : Integer.parseInt(x);
}
/**
* <p>
* Apply configuration parameters to the parser.
* </p>
*/
public static void configure(LGConfig config)
{
init();
if (config.getMaxCost() > -1)
LinkGrammar.setMaxCost(config.getMaxCost());
if (config.getMaxParseSeconds() > -1)
LinkGrammar.setMaxParseSeconds(config.getMaxParseSeconds());
if (config.getDictionaryLocation() != null)
LinkGrammar.setDictionariesPath(config.getDictionaryLocation());
}
/**
* Assuming <code>LinkGrammar.parse</code> has already been called,
* construct a full <code>ParseResult</code> given the passed in
* configuration. For example, no more that
* <code>config.getMaxLinkages</code> are returned, etc.
*
* @param config
* @return
*/
public static ParseResult getAsParseResult(LGConfig config)
{
LinkGrammar.makeLinkage(0); // need to call at least once, otherwise it crashes
ParseResult parseResult = new ParseResult();
parseResult.numSkippedWords = LinkGrammar.getNumSkippedWords();
parseResult.words = new String[LinkGrammar.getNumWords()];
parseResult.entityFlags = new boolean[LinkGrammar.getNumWords()];
parseResult.pastTenseFlags = new boolean[LinkGrammar.getNumWords()];
for (int i = 0; i < parseResult.words.length; i++)
{
String word = parseResult.words[i] = LinkGrammar.getWord(i);
parseResult.entityFlags[i] = LinkGrammar.isEntity(word);
parseResult.pastTenseFlags[i] = LinkGrammar.isPastTenseForm(word);
}
int maxLinkages = Math.min(config.getMaxLinkages(), LinkGrammar.getNumLinkages());
for (int li = 0; li < maxLinkages; li++)
{
LinkGrammar.makeLinkage(li);
Linkage linkage = new Linkage();
linkage.setAndCost(LinkGrammar.getLinkageAndCost());
linkage.setDisjunctCost(LinkGrammar.getLinkageDisjunctCost());
linkage.setLinkCost(LinkGrammar.getLinkageLinkCost());
linkage.setLinkedWordCount(LinkGrammar.getNumWords());
linkage.setNumViolations(LinkGrammar.getLinkageNumViolations());
String [] words = new String[LinkGrammar.getNumWords()];
for (int i = 0; i < words.length; i++)
words[i] = LinkGrammar.getLinkageWord(i);
linkage.setWords(words);
int numLinks = LinkGrammar.getNumLinks();
for (int i = 0; i < numLinks; i++)
{
Link link = new Link();
link.setLabel(LinkGrammar.getLinkLabel(i));
link.setLeft(LinkGrammar.getLinkLWord(i));
link.setRight(LinkGrammar.getLinkRWord(i));
link.setLeftLabel(LinkGrammar.getLinkLLabel(i));
link.setRightLabel(LinkGrammar.getLinkRLabel(i));
linkage.getLinks().add(link);
}
if (config.isStoreConstituentString())
linkage.setConstituentString(LinkGrammar.getConstituentString());
parseResult.linkages.add(linkage);
}
return parseResult;
}
static char[] hex = "0123456789ABCDEF".toCharArray();
private static String jsonString(String s)
{
StringBuffer b = new StringBuffer();
b.append("\"");
CharacterIterator it = new StringCharacterIterator(s);
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next())
{
if (c == '"') b.append("\\\"");
else if (c == '\\') b.append("\\\\");
else if (c == '/') b.append("\\/");
else if (c == '\b') b.append("\\b");
else if (c == '\f') b.append("\\f");
else if (c == '\n') b.append("\\n");
else if (c == '\r') b.append("\\r");
else if (c == '\t') b.append("\\t");
else if (Character.isISOControl(c))
{
int n = c;
for (int i = 0; i < 4; ++i) {
int digit = (n & 0xf000) >> 12;
b.append(hex[digit]);
n <<= 4;
}
}
else
{
b.append(c);
}
}
b.append("\"");
return b.toString();
}
/**
* Format the current parsing result as a JSON string. This method
* assume that <code>LinkGrammar.parse</code> has been called before.
*/
public static String getAsJSONFormat(LGConfig config)
{
LinkGrammar.makeLinkage(0); // need to call at least once, otherwise it crashes
int numWords = LinkGrammar.getNumWords();
int maxLinkages = Math.min(config.getMaxLinkages(), LinkGrammar.getNumLinkages());
StringBuffer buf = new StringBuffer();
buf.append("{\"tokens\":[");
for (int i = 0; i < numWords; i++)
{
buf.append(jsonString(LinkGrammar.getWord(i)));
if (i + 1 < numWords)
buf.append(",");
}
buf.append("],\"numSkippedWords\":" + LinkGrammar.getNumSkippedWords());
buf.append(",\"entity\":[");
boolean first = true;
for (int i = 0; i < numWords; i++)
if (LinkGrammar.isEntity(LinkGrammar.getWord(i)))
{
if (!first)
buf.append(",");
first = false;
buf.append(Integer.toString(i));
}
buf.append("],\"pastTense\":[");
first = true;
for (int i = 0; i < numWords; i++)
if (LinkGrammar.isPastTenseForm(LinkGrammar.getWord(i).toLowerCase()))
{
if (!first)
buf.append(",");
first = false;
buf.append(Integer.toString(i));
}
buf.append("],\"linkages\":[");
for (int li = 0; li < maxLinkages; li++)
{
LinkGrammar.makeLinkage(li);
buf.append("{\"words\":[");
for (int i = 0; i < numWords; i++)
{
buf.append(jsonString(LinkGrammar.getLinkageWord(i)));
if (i + 1 < numWords)
buf.append(",");
}
buf.append("], \"andCost\":");
buf.append(Integer.toString(LinkGrammar.getLinkageAndCost()));
buf.append(", \"disjunctCost\":");
buf.append(Integer.toString(LinkGrammar.getLinkageDisjunctCost()));
buf.append(", \"linkageCost\":");
buf.append(Integer.toString(LinkGrammar.getLinkageLinkCost()));
buf.append(", \"numViolations\":");
buf.append(Integer.toString(LinkGrammar.getLinkageNumViolations()));
if (config.isStoreConstituentString())
{
buf.append(", \"constituentString\":");
buf.append(jsonString(LinkGrammar.getConstituentString()));
}
buf.append(", \"links\":[");
int numLinks = LinkGrammar.getNumLinks();
for (int i = 0; i < numLinks; i++)
{
buf.append("{\"label\":" + jsonString(LinkGrammar.getLinkLabel(i)) + ",");
buf.append("\"left\":" + LinkGrammar.getLinkLWord(i) + ",");
buf.append("\"right\":" + LinkGrammar.getLinkRWord(i) + ",");
buf.append("\"leftLabel\":" + jsonString(LinkGrammar.getLinkLLabel(i)) + ",");
buf.append("\"rightLabel\":" + jsonString(LinkGrammar.getLinkRLabel(i)) + "}");
if (i + 1 < numLinks)
buf.append(",");
}
buf.append("]");
buf.append("}");
}
buf.append("]"); // close linkage array
buf.append("}");
return buf.toString();
}
/**
* A stub method for now for implementing a compact binary format
* for parse results.
*
* @param config
* @return
*/
public static byte [] getAsBinary(LGConfig config)
{
int size = 0;
byte [] buf = new byte[1024];
// TODO ..... grow buf as needed
byte [] result = new byte[size];
System.arraycopy(buf, 0, result, 0, size);
return result;
}
private static Map<String, String> readMsg(Reader in) throws java.io.IOException
{
int length = 0;
char [] buf = new char[1024];
for (int count = in.read(buf, length, buf.length - length);
count > -1;
count = in.read(buf, length, buf.length - length))
{
length += count;
if (length == buf.length)
{
char [] nbuf = new char[buf.length + 512];
System.arraycopy(buf, 0, nbuf, 0, buf.length);
buf = nbuf;
}
if (buf[length-1] == '\n')
break;
}
Map<String, String> result = new HashMap<String, String>();
int start = -1;
int column = -1;
for (int offset = 0; offset < length - 1; offset++)
{
char c = buf[offset];
if (start == -1)
start = offset;
else if (c == ':')
column = offset;
else if (c == '\0')
{
if (start == -1 || column == -1)
throw new RuntimeException("Malformat message:" + new String(buf, 0, length));
String name = new String(buf, start, column - start);
String value = new String(buf, column + 1, offset - column - 1);
result.put(name, value);
start = column = -1;
}
}
if (start != -1 || column != -1)
throw new RuntimeException("Malformat message:" + new String(buf, 0, length));
return result;
}
private static void handleClient(Socket clientSocket)
{
init();
Reader in = null;
PrintWriter out = null;
try
{
trace("Connection accepted from : " + clientSocket.getInetAddress());
in = new InputStreamReader(clientSocket.getInputStream());
Map<String, String> msg = readMsg(in);
if (verbose)
trace("Received msg '" + msg + "' from " + clientSocket.getInetAddress());
String json = "{}";
LGConfig config = new LGConfig();
config.setStoreConstituentString(getBool("storeConstituentString", msg, config.isStoreConstituentString()));
config.setMaxCost(getInt("maxCost", msg, config.getMaxCost()));
config.setMaxLinkages(getInt("maxLinkages", msg, config.getMaxLinkages()));
config.setMaxParseSeconds(getInt("maxParseSeconds", msg, config.getMaxParseSeconds()));
configure(config);
String text = msg.get("text");
if (text != null)
LinkGrammar.parse(text);
if (LinkGrammar.getNumLinkages() > 0)
json = getAsJSONFormat(config);
out = new PrintWriter(clientSocket.getOutputStream(), true);
out.print(json);
out.print('\n');
trace("Response written to " + clientSocket.getInetAddress() + ", closing client connection...");
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
finally
{
if (out != null) try { out.close(); } catch (Throwable t) { }
if (in != null) try { in.close(); } catch (Throwable t) { }
if (clientSocket != null) try { clientSocket.close(); } catch (Throwable t) { }
}
}
/**
* <p>
* Parse a piece of text with the given configuration and return the <code>ParseResult</code>.
* </p>
*
* @param config The configuration to be used. If this is the first time the <code>parse</code>
* method is called within the current thread, the dictionary location (if not <code>null</code>)
* of this parameter will be used to initialize the parser. Otherwise the dictionary location is
* ignored.
* @param text The text to parse, normally a single sentence.
* @return The <code>ParseResult</code>. Note that <code>null</code> is never returned. If parsing
* failed, there will be 0 linkages in the result.
*/
public static ParseResult parse(LGConfig config, String text)
{
if (!isInitialized() &&
config.getDictionaryLocation() != null &&
config.getDictionaryLocation().trim().length() > 0)
LinkGrammar.setDictionariesPath(config.getDictionaryLocation());
configure(config);
LinkGrammar.parse(text);
return getAsParseResult(config);
}
public static void main(String [] argv)
{
int threads = 1;
int port = 0;
String dictionaryPath = null;
try
{
int argIdx = 0;
if (argv[argIdx].equals("-verbose")) { verbose = true; argIdx++; }
if (argv[argIdx].equals("-threads")) { threads = Integer.parseInt(argv[++argIdx]); argIdx++; }
port = Integer.parseInt(argv[argIdx++]);
if (argv.length > argIdx)
dictionaryPath = argv[argIdx];
}
catch (Throwable ex)
{
if (argv.length > 0)
ex.printStackTrace(System.err);
System.out.println("Syntax: java org.linkgrammar.LGService [-verbose] [-threads n] port [dictionaryPath]");
System.out.println("\t where 'port' is the TCP port the service should listen to and");
System.out.println("\t -verbose forces tracing of every message received and");
System.out.println("\t -threads specifies the number of concurrent threads/clients allowed (default 1) and ");
System.out.println("\t 'dictionaryPath' full path to the Link Grammar dictionaries (optional).");
System.exit(-1);
}
if (dictionaryPath != null)
{
File f = new File(dictionaryPath);
if (!f.exists())
{ System.err.println("Dictionary path " + dictionaryPath + " not found."); System.exit(-1); }
else if (!f.isDirectory())
{ System.err.println("Dictionary path " + dictionaryPath + " not a directory."); System.exit(-1); }
}
System.out.println("Starting Link Grammar Server at port " + port +
", with " + threads + " available processing threads and " +
((dictionaryPath == null) ? " with default dictionary location." :
"with dictionary location '" + dictionaryPath + "'."));
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threads,
threads,
Long.MAX_VALUE,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
try
{
if (dictionaryPath != null)
LinkGrammar.setDictionariesPath(dictionaryPath);
ServerSocket serverSocket = new ServerSocket(port);
while (true)
{
trace("Waiting for client connections...");
final Socket clientSocket = serverSocket.accept();
threadPool.submit(new Runnable() { public void run() { handleClient(clientSocket); } });
}
}
catch (Throwable t)
{
t.printStackTrace(System.err);
System.exit(-1);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.