diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/adrguides/SearchViewGuides.java b/src/main/java/com/adrguides/SearchViewGuides.java
index 859f5da..c73c3f1 100644
--- a/src/main/java/com/adrguides/SearchViewGuides.java
+++ b/src/main/java/com/adrguides/SearchViewGuides.java
@@ -1,116 +1,116 @@
package com.adrguides;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.util.Log;
import android.view.MenuItem;
import android.widget.FilterQueryProvider;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import com.adrguides.model.Place;
import com.adrguides.tts.TextToSpeechSingleton;
import java.util.ArrayList;
/**
* Created by adrian on 29/08/13.
*/
public class SearchViewGuides {
public SearchViewGuides(final Context context, final MenuItem menuitem) {
final SearchView searchView = (SearchView) menuitem.getActionView();
// Configure the search info and add any event listeners
menuitem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
String[] from = {"text"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_activated_1, getSuggestionsCursor(null), from, to, 0);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
- return getSuggestionsCursor(new String(constraint.toString()));
+ return getSuggestionsCursor(constraint.toString());
}
});
searchView.setSuggestionsAdapter(adapter);
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
return true;
}
});
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return false;
}
@Override
public boolean onSuggestionClick(int i) {
Cursor row = (Cursor) searchView.getSuggestionsAdapter().getItem(i);
searchView.setQuery(row.getString(2), true);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
if (s == null) {
return false;
}
Log.d("com.adrguides.SearchViewGuides", "man submitao");
Place[] places = TextToSpeechSingleton.getInstance().getGuide().getPlaces();
for(int i = 0; i < places.length; i++){
Place item = places[i];
if ((item.getId() != null && item.getId().equals(s)) ||
item.getTitle().toLowerCase().equals(s.toLowerCase()) ||
item.getVisibleLabel().toLowerCase().equals(s.toLowerCase())) {
TextToSpeechSingleton.getInstance().gotoChapter(i);
menuitem.collapseActionView();
return true;
}
}
return false ;// true if the query has been handled by the listener, false to let the SearchView perform the default action.
}
@Override
public boolean onQueryTextChange(String s) {
return false; // false if the SearchView should perform the default action of showing any suggestions if available, true if the action was handled by the listener.
}
});
}
private Cursor getSuggestionsCursor(String filter) {
Log.d("com.adrguides.SearchViewGuides", "man filtrao");
String[] columnNames = {"_id", "_title", "text"};
MatrixCursor cursor = new MatrixCursor(columnNames);
String[] temp = new String[3];
int id = 0;
for(Place item : TextToSpeechSingleton.getInstance().getGuide().getPlaces()){
if (filter == null ||
(item.getId() != null && item.getId().contains(filter)) ||
item.getTitle().toLowerCase().contains(filter.toLowerCase())) {
temp[0] = item.getId();
temp[1] = item.getTitle();
temp[2] = item.getVisibleLabel();
cursor.addRow(temp);
}
}
return cursor;
}
}
| true | true | public SearchViewGuides(final Context context, final MenuItem menuitem) {
final SearchView searchView = (SearchView) menuitem.getActionView();
// Configure the search info and add any event listeners
menuitem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
String[] from = {"text"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_activated_1, getSuggestionsCursor(null), from, to, 0);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return getSuggestionsCursor(new String(constraint.toString()));
}
});
searchView.setSuggestionsAdapter(adapter);
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
return true;
}
});
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return false;
}
@Override
public boolean onSuggestionClick(int i) {
Cursor row = (Cursor) searchView.getSuggestionsAdapter().getItem(i);
searchView.setQuery(row.getString(2), true);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
if (s == null) {
return false;
}
Log.d("com.adrguides.SearchViewGuides", "man submitao");
Place[] places = TextToSpeechSingleton.getInstance().getGuide().getPlaces();
for(int i = 0; i < places.length; i++){
Place item = places[i];
if ((item.getId() != null && item.getId().equals(s)) ||
item.getTitle().toLowerCase().equals(s.toLowerCase()) ||
item.getVisibleLabel().toLowerCase().equals(s.toLowerCase())) {
TextToSpeechSingleton.getInstance().gotoChapter(i);
menuitem.collapseActionView();
return true;
}
}
return false ;// true if the query has been handled by the listener, false to let the SearchView perform the default action.
}
@Override
public boolean onQueryTextChange(String s) {
return false; // false if the SearchView should perform the default action of showing any suggestions if available, true if the action was handled by the listener.
}
});
}
| public SearchViewGuides(final Context context, final MenuItem menuitem) {
final SearchView searchView = (SearchView) menuitem.getActionView();
// Configure the search info and add any event listeners
menuitem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
String[] from = {"text"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_activated_1, getSuggestionsCursor(null), from, to, 0);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return getSuggestionsCursor(constraint.toString());
}
});
searchView.setSuggestionsAdapter(adapter);
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
return true;
}
});
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return false;
}
@Override
public boolean onSuggestionClick(int i) {
Cursor row = (Cursor) searchView.getSuggestionsAdapter().getItem(i);
searchView.setQuery(row.getString(2), true);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
if (s == null) {
return false;
}
Log.d("com.adrguides.SearchViewGuides", "man submitao");
Place[] places = TextToSpeechSingleton.getInstance().getGuide().getPlaces();
for(int i = 0; i < places.length; i++){
Place item = places[i];
if ((item.getId() != null && item.getId().equals(s)) ||
item.getTitle().toLowerCase().equals(s.toLowerCase()) ||
item.getVisibleLabel().toLowerCase().equals(s.toLowerCase())) {
TextToSpeechSingleton.getInstance().gotoChapter(i);
menuitem.collapseActionView();
return true;
}
}
return false ;// true if the query has been handled by the listener, false to let the SearchView perform the default action.
}
@Override
public boolean onQueryTextChange(String s) {
return false; // false if the SearchView should perform the default action of showing any suggestions if available, true if the action was handled by the listener.
}
});
}
|
diff --git a/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java b/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java
index 2097193..d45cf95 100644
--- a/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java
+++ b/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java
@@ -1,105 +1,107 @@
package kkckkc.jsourcepad.model.bundle;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import kkckkc.jsourcepad.action.ActionContextKeys;
import kkckkc.jsourcepad.model.Doc;
import kkckkc.jsourcepad.model.Window;
import kkckkc.jsourcepad.util.action.ActionManager;
import kkckkc.syntaxpane.model.Interval;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class EnvironmentProvider {
public static Map<String, String> getEnvironment(Window window, BundleItemSupplier bundleItemSupplier) {
Map<String, String> environment = Maps.newHashMap();
Doc activeDoc = window.getDocList().getActiveDoc();
if (activeDoc != null) {
environment.put("TM_SCOPE", activeDoc.getActiveBuffer().getInsertionPoint().getScope().getPath());
environment.put("TM_LINE_INDEX", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineIndex()));
environment.put("TM_LINE_NUMBER", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineNumber() + 1));
environment.put("TM_CURRENT_LINE", activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentLine()));
String s = activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentWord());
if (s != null) {
environment.put("TM_CURRENT_WORD", s);
}
if (activeDoc.getFile() != null) {
environment.put("TM_FILENAME", activeDoc.getFile().getName());
environment.put("TM_DIRECTORY", activeDoc.getFile().getParentFile().getPath());
environment.put("TM_FILEPATH", activeDoc.getFile().getPath());
Interval selection = activeDoc.getActiveBuffer().getSelection();
if (selection != null && ! selection.isEmpty()) {
String text = activeDoc.getActiveBuffer().getText(selection);
if (text.length() > 60000) text = text.substring(0, 60000);
environment.put("TM_SELECTED_TEXT", text);
}
}
}
if (window.getProject() != null) {
environment.put("TM_PROJECT_DIRECTORY", window.getProject().getProjectDir().getPath());
}
List<File> paths = Lists.newArrayList();
if (bundleItemSupplier != null) {
environment.put("TM_BUNDLE_SUPPORT",
new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support").getPath());
paths.add(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support/bin"));
}
if (System.getProperty("supportPath") != null) {
environment.put("TM_SUPPORT_PATH", System.getProperty("supportPath"));
paths.add(new File(System.getProperty("supportPath") + "/bin"));
paths.add(new File(System.getProperty("supportPath") + "/" + System.getProperty("os.name") + "/bin"));
// TODO: This is a hack. Add binary with proper error message
environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2");
}
List<File> files = Lists.newArrayList();
ActionManager actionManager = window.getActionManager();
- if (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc) {
- files = window.getProject().getSelectedFiles();
+ if (! (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc)) {
+ if (window.getProject() != null) {
+ files = window.getProject().getSelectedFiles();
+ }
} else {
if (activeDoc != null && activeDoc.getFile() != null) {
files = Collections.singletonList(activeDoc.getFile());
}
}
if (files.isEmpty()) {
environment.put("TM_SELECTED_FILE", "");
environment.put("TM_SELECTED_FILES", "");
} else {
List<String> s = Lists.newArrayList();
for (File f : files) {
s.add("\"" + f.toString() + "\"");
}
environment.put("TM_SELECTED_FILE", "\"" + s.get(0));
environment.put("TM_SELECTED_FILES", Joiner.on("\"").join(s));
}
if (activeDoc != null) {
environment.put("TM_SOFT_TABS", activeDoc.getTabManager().isSoftTabs() ? "true" : "false");
environment.put("TM_TAB_SIZE", Integer.toString(activeDoc.getTabManager().getTabSize()));
}
// Build path
environment.put("PATH",
System.getenv("PATH") + File.pathSeparator +
Joiner.on(File.pathSeparator).join(paths));
return environment;
}
}
| true | true | public static Map<String, String> getEnvironment(Window window, BundleItemSupplier bundleItemSupplier) {
Map<String, String> environment = Maps.newHashMap();
Doc activeDoc = window.getDocList().getActiveDoc();
if (activeDoc != null) {
environment.put("TM_SCOPE", activeDoc.getActiveBuffer().getInsertionPoint().getScope().getPath());
environment.put("TM_LINE_INDEX", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineIndex()));
environment.put("TM_LINE_NUMBER", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineNumber() + 1));
environment.put("TM_CURRENT_LINE", activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentLine()));
String s = activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentWord());
if (s != null) {
environment.put("TM_CURRENT_WORD", s);
}
if (activeDoc.getFile() != null) {
environment.put("TM_FILENAME", activeDoc.getFile().getName());
environment.put("TM_DIRECTORY", activeDoc.getFile().getParentFile().getPath());
environment.put("TM_FILEPATH", activeDoc.getFile().getPath());
Interval selection = activeDoc.getActiveBuffer().getSelection();
if (selection != null && ! selection.isEmpty()) {
String text = activeDoc.getActiveBuffer().getText(selection);
if (text.length() > 60000) text = text.substring(0, 60000);
environment.put("TM_SELECTED_TEXT", text);
}
}
}
if (window.getProject() != null) {
environment.put("TM_PROJECT_DIRECTORY", window.getProject().getProjectDir().getPath());
}
List<File> paths = Lists.newArrayList();
if (bundleItemSupplier != null) {
environment.put("TM_BUNDLE_SUPPORT",
new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support").getPath());
paths.add(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support/bin"));
}
if (System.getProperty("supportPath") != null) {
environment.put("TM_SUPPORT_PATH", System.getProperty("supportPath"));
paths.add(new File(System.getProperty("supportPath") + "/bin"));
paths.add(new File(System.getProperty("supportPath") + "/" + System.getProperty("os.name") + "/bin"));
// TODO: This is a hack. Add binary with proper error message
environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2");
}
List<File> files = Lists.newArrayList();
ActionManager actionManager = window.getActionManager();
if (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc) {
files = window.getProject().getSelectedFiles();
} else {
if (activeDoc != null && activeDoc.getFile() != null) {
files = Collections.singletonList(activeDoc.getFile());
}
}
if (files.isEmpty()) {
environment.put("TM_SELECTED_FILE", "");
environment.put("TM_SELECTED_FILES", "");
} else {
List<String> s = Lists.newArrayList();
for (File f : files) {
s.add("\"" + f.toString() + "\"");
}
environment.put("TM_SELECTED_FILE", "\"" + s.get(0));
environment.put("TM_SELECTED_FILES", Joiner.on("\"").join(s));
}
if (activeDoc != null) {
environment.put("TM_SOFT_TABS", activeDoc.getTabManager().isSoftTabs() ? "true" : "false");
environment.put("TM_TAB_SIZE", Integer.toString(activeDoc.getTabManager().getTabSize()));
}
// Build path
environment.put("PATH",
System.getenv("PATH") + File.pathSeparator +
Joiner.on(File.pathSeparator).join(paths));
return environment;
}
| public static Map<String, String> getEnvironment(Window window, BundleItemSupplier bundleItemSupplier) {
Map<String, String> environment = Maps.newHashMap();
Doc activeDoc = window.getDocList().getActiveDoc();
if (activeDoc != null) {
environment.put("TM_SCOPE", activeDoc.getActiveBuffer().getInsertionPoint().getScope().getPath());
environment.put("TM_LINE_INDEX", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineIndex()));
environment.put("TM_LINE_NUMBER", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineNumber() + 1));
environment.put("TM_CURRENT_LINE", activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentLine()));
String s = activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentWord());
if (s != null) {
environment.put("TM_CURRENT_WORD", s);
}
if (activeDoc.getFile() != null) {
environment.put("TM_FILENAME", activeDoc.getFile().getName());
environment.put("TM_DIRECTORY", activeDoc.getFile().getParentFile().getPath());
environment.put("TM_FILEPATH", activeDoc.getFile().getPath());
Interval selection = activeDoc.getActiveBuffer().getSelection();
if (selection != null && ! selection.isEmpty()) {
String text = activeDoc.getActiveBuffer().getText(selection);
if (text.length() > 60000) text = text.substring(0, 60000);
environment.put("TM_SELECTED_TEXT", text);
}
}
}
if (window.getProject() != null) {
environment.put("TM_PROJECT_DIRECTORY", window.getProject().getProjectDir().getPath());
}
List<File> paths = Lists.newArrayList();
if (bundleItemSupplier != null) {
environment.put("TM_BUNDLE_SUPPORT",
new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support").getPath());
paths.add(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support/bin"));
}
if (System.getProperty("supportPath") != null) {
environment.put("TM_SUPPORT_PATH", System.getProperty("supportPath"));
paths.add(new File(System.getProperty("supportPath") + "/bin"));
paths.add(new File(System.getProperty("supportPath") + "/" + System.getProperty("os.name") + "/bin"));
// TODO: This is a hack. Add binary with proper error message
environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2");
}
List<File> files = Lists.newArrayList();
ActionManager actionManager = window.getActionManager();
if (! (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc)) {
if (window.getProject() != null) {
files = window.getProject().getSelectedFiles();
}
} else {
if (activeDoc != null && activeDoc.getFile() != null) {
files = Collections.singletonList(activeDoc.getFile());
}
}
if (files.isEmpty()) {
environment.put("TM_SELECTED_FILE", "");
environment.put("TM_SELECTED_FILES", "");
} else {
List<String> s = Lists.newArrayList();
for (File f : files) {
s.add("\"" + f.toString() + "\"");
}
environment.put("TM_SELECTED_FILE", "\"" + s.get(0));
environment.put("TM_SELECTED_FILES", Joiner.on("\"").join(s));
}
if (activeDoc != null) {
environment.put("TM_SOFT_TABS", activeDoc.getTabManager().isSoftTabs() ? "true" : "false");
environment.put("TM_TAB_SIZE", Integer.toString(activeDoc.getTabManager().getTabSize()));
}
// Build path
environment.put("PATH",
System.getenv("PATH") + File.pathSeparator +
Joiner.on(File.pathSeparator).join(paths));
return environment;
}
|
diff --git a/frost-wot/source/frost/gui/TofTreeCellRenderer.java b/frost-wot/source/frost/gui/TofTreeCellRenderer.java
index b90b84d6..f79048d6 100644
--- a/frost-wot/source/frost/gui/TofTreeCellRenderer.java
+++ b/frost-wot/source/frost/gui/TofTreeCellRenderer.java
@@ -1,183 +1,181 @@
/*
TofTreeCellRenderer.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.gui;
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import frost.frame1;
import frost.gui.objects.FrostBoardObject;
public class TofTreeCellRenderer extends DefaultTreeCellRenderer
{
ImageIcon writeAccessIcon;
ImageIcon writeAccessNewIcon;
ImageIcon readAccessIcon;
ImageIcon readAccessNewIcon;
ImageIcon boardIcon;
ImageIcon boardNewIcon;
ImageIcon boardSpammedIcon;
String fileSeparator;
Font boldFont = null;
Font normalFont = null;
public TofTreeCellRenderer()
{
fileSeparator = System.getProperty("file.separator");
boardIcon = new ImageIcon(frame1.class.getResource("/data/board.gif"));
boardNewIcon = new ImageIcon(frame1.class.getResource("/data/boardnew.gif"));
boardSpammedIcon = new ImageIcon(frame1.class.getResource("/data/boardspam.gif"));
writeAccessIcon = new ImageIcon(frame1.class.getResource("/data/waboard.jpg"));
writeAccessNewIcon = new ImageIcon(frame1.class.getResource("/data/waboardnew.jpg"));
readAccessIcon = new ImageIcon(frame1.class.getResource("/data/raboard.jpg"));
readAccessNewIcon = new ImageIcon(frame1.class.getResource("/data/raboardnew.jpg"));
this.setLeafIcon(new ImageIcon(frame1.class.getResource("/data/board.gif")));
this.setClosedIcon(new ImageIcon(frame1.class.getResource("/data/closed.gif")));
this.setOpenIcon(new ImageIcon(frame1.class.getResource("/data/open.gif")));
JTable dummyTable = new JTable();
normalFont = dummyTable.getFont();
boldFont = normalFont.deriveFont( Font.BOLD );
}
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
{
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
FrostBoardObject board = null;
if( value instanceof FrostBoardObject )
{
board = (FrostBoardObject)value;
}
else
{
System.out.println("Error - TofTreeCellRenderer: got a tree value wich is no FrostBoardObject:");
System.out.println(" node value='"+value+"' ; node class='"+value.getClass()+"'");
System.out.println("This should never happen, please report the error.");
return this;
}
boolean containsNewMessage = board.containsNewMessage();
if( board.isFolder() )
{
// if this is a folder, check board for new messages
if( board.containsFolderNewMessages() )
{
setFont( boldFont );
}
else
{
setFont( normalFont );
}
}
else
{
// set the sdpecial text (board name + if new msg. a ' (2)' is appended and bold)
setText( board.getVisibleText() );
if( containsNewMessage )
{
setFont( boldFont );
}
else
{
setFont( normalFont );
}
}
// maybe update visualization
if( frame1.frostSettings.getBoolValue("boardUpdateVisualization") &&
board.isUpdating() == true )
{
// set special updating colors
Color c;
c = (Color)frame1.frostSettings.getObjectValue("boardUpdatingNonSelectedBackgroundColor");
setBackgroundNonSelectionColor( c );
c = (Color)frame1.frostSettings.getObjectValue("boardUpdatingSelectedBackgroundColor");
setBackgroundSelectionColor( c );
- setTextSelectionColor(Color.white);
- setTextNonSelectionColor(Color.white);
}
else
{
// refresh colours from the L&F
setTextSelectionColor(UIManager.getColor("Tree.selectionForeground"));
setTextNonSelectionColor(UIManager.getColor("Tree.textForeground"));
setBackgroundNonSelectionColor( UIManager.getColor("Tree.textBackground") );
setBackgroundSelectionColor( UIManager.getColor("Tree.selectionBackground") );
}
// set the icon
if( leaf == true )
{
if( board.isPublicBoard() )
{
if( containsNewMessage )
{
setIcon(boardNewIcon);
}
else
{
setIcon(boardIcon);
}
}
else if( board.isSpammed() )
{
setIcon(boardSpammedIcon);
}
else if( board.isWriteAccessBoard() )
{
if( containsNewMessage )
{
setIcon(writeAccessNewIcon);
}
else
{
setIcon(writeAccessIcon);
}
}
else if( board.isReadAccessBoard() )
{
if( containsNewMessage )
{
setIcon(readAccessNewIcon);
}
else
{
setIcon(readAccessIcon);
}
}
}
return this;
}
}
| true | true | public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
{
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
FrostBoardObject board = null;
if( value instanceof FrostBoardObject )
{
board = (FrostBoardObject)value;
}
else
{
System.out.println("Error - TofTreeCellRenderer: got a tree value wich is no FrostBoardObject:");
System.out.println(" node value='"+value+"' ; node class='"+value.getClass()+"'");
System.out.println("This should never happen, please report the error.");
return this;
}
boolean containsNewMessage = board.containsNewMessage();
if( board.isFolder() )
{
// if this is a folder, check board for new messages
if( board.containsFolderNewMessages() )
{
setFont( boldFont );
}
else
{
setFont( normalFont );
}
}
else
{
// set the sdpecial text (board name + if new msg. a ' (2)' is appended and bold)
setText( board.getVisibleText() );
if( containsNewMessage )
{
setFont( boldFont );
}
else
{
setFont( normalFont );
}
}
// maybe update visualization
if( frame1.frostSettings.getBoolValue("boardUpdateVisualization") &&
board.isUpdating() == true )
{
// set special updating colors
Color c;
c = (Color)frame1.frostSettings.getObjectValue("boardUpdatingNonSelectedBackgroundColor");
setBackgroundNonSelectionColor( c );
c = (Color)frame1.frostSettings.getObjectValue("boardUpdatingSelectedBackgroundColor");
setBackgroundSelectionColor( c );
setTextSelectionColor(Color.white);
setTextNonSelectionColor(Color.white);
}
else
{
// refresh colours from the L&F
setTextSelectionColor(UIManager.getColor("Tree.selectionForeground"));
setTextNonSelectionColor(UIManager.getColor("Tree.textForeground"));
setBackgroundNonSelectionColor( UIManager.getColor("Tree.textBackground") );
setBackgroundSelectionColor( UIManager.getColor("Tree.selectionBackground") );
}
// set the icon
if( leaf == true )
{
if( board.isPublicBoard() )
{
if( containsNewMessage )
{
setIcon(boardNewIcon);
}
else
{
setIcon(boardIcon);
}
}
else if( board.isSpammed() )
{
setIcon(boardSpammedIcon);
}
else if( board.isWriteAccessBoard() )
{
if( containsNewMessage )
{
setIcon(writeAccessNewIcon);
}
else
{
setIcon(writeAccessIcon);
}
}
else if( board.isReadAccessBoard() )
{
if( containsNewMessage )
{
setIcon(readAccessNewIcon);
}
else
{
setIcon(readAccessIcon);
}
}
}
return this;
}
| public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
{
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
FrostBoardObject board = null;
if( value instanceof FrostBoardObject )
{
board = (FrostBoardObject)value;
}
else
{
System.out.println("Error - TofTreeCellRenderer: got a tree value wich is no FrostBoardObject:");
System.out.println(" node value='"+value+"' ; node class='"+value.getClass()+"'");
System.out.println("This should never happen, please report the error.");
return this;
}
boolean containsNewMessage = board.containsNewMessage();
if( board.isFolder() )
{
// if this is a folder, check board for new messages
if( board.containsFolderNewMessages() )
{
setFont( boldFont );
}
else
{
setFont( normalFont );
}
}
else
{
// set the sdpecial text (board name + if new msg. a ' (2)' is appended and bold)
setText( board.getVisibleText() );
if( containsNewMessage )
{
setFont( boldFont );
}
else
{
setFont( normalFont );
}
}
// maybe update visualization
if( frame1.frostSettings.getBoolValue("boardUpdateVisualization") &&
board.isUpdating() == true )
{
// set special updating colors
Color c;
c = (Color)frame1.frostSettings.getObjectValue("boardUpdatingNonSelectedBackgroundColor");
setBackgroundNonSelectionColor( c );
c = (Color)frame1.frostSettings.getObjectValue("boardUpdatingSelectedBackgroundColor");
setBackgroundSelectionColor( c );
}
else
{
// refresh colours from the L&F
setTextSelectionColor(UIManager.getColor("Tree.selectionForeground"));
setTextNonSelectionColor(UIManager.getColor("Tree.textForeground"));
setBackgroundNonSelectionColor( UIManager.getColor("Tree.textBackground") );
setBackgroundSelectionColor( UIManager.getColor("Tree.selectionBackground") );
}
// set the icon
if( leaf == true )
{
if( board.isPublicBoard() )
{
if( containsNewMessage )
{
setIcon(boardNewIcon);
}
else
{
setIcon(boardIcon);
}
}
else if( board.isSpammed() )
{
setIcon(boardSpammedIcon);
}
else if( board.isWriteAccessBoard() )
{
if( containsNewMessage )
{
setIcon(writeAccessNewIcon);
}
else
{
setIcon(writeAccessIcon);
}
}
else if( board.isReadAccessBoard() )
{
if( containsNewMessage )
{
setIcon(readAccessNewIcon);
}
else
{
setIcon(readAccessIcon);
}
}
}
return this;
}
|
diff --git a/src/beads_main/net/beadsproject/beads/ugens/Add.java b/src/beads_main/net/beadsproject/beads/ugens/Add.java
index 598bfe4..d6918bf 100644
--- a/src/beads_main/net/beadsproject/beads/ugens/Add.java
+++ b/src/beads_main/net/beadsproject/beads/ugens/Add.java
@@ -1,152 +1,152 @@
/*
* This file is part of Beads. See http://www.beadsproject.net for all information.
*/
package net.beadsproject.beads.ugens;
import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.UGen;
/**
* Takes an incoming signal (or signals in the multi-channel case) and adds
* something (either a float value or another signal) to it (them).
*
* @beads.category utilities
* @author ollie
* @author Benito Crawford
* @version 0.9.5
*/
public class Add extends UGen {
private UGen adderUGen;
private float adder = 0;
/**
* Constructor for an Add object that sets a UGen to control the value to
* add.
*
* @param context
* The audio context.
* @param channels
* The number of channels.
* @param adderUGen
* The adder UGen controller.
*/
public Add(AudioContext context, int channels, UGen adderUGen) {
super(context, channels, channels);
setAdder(adderUGen);
}
/**
* Constructor for an Add object with a given UGen as input and another as adder.
* i.e., use this as quickest way to add two UGens together.
*
* @param context the AudioContext.
* @param input the input UGen.
* @param adderUGen the adder UGen.
*/
public Add(AudioContext context, UGen input, UGen adderUGen) {
super(context, input.getOuts(), input.getOuts());
setAdder(adderUGen);
addInput(input);
}
/**
* Constructor for an Add object that sets a static adder value.
*
* @param context
* The audio context.
* @param channels
* The number of channels.
* @param adder
* The value to add.
*/
public Add(AudioContext context, int channels, float adder) {
super(context, channels, channels);
setAdder(adder);
}
/*
* (non-Javadoc)
*
* @see com.olliebown.beads.core.UGen#calculateBuffer()
*/
@Override
public void calculateBuffer() {
if (adderUGen == null) {
for (int j = 0; j < outs; j++) {
float[] bi = bufIn[j];
float[] bo = bufOut[j];
for (int i = 0; i < bufferSize; i++) {
- bo[i] = bi[j] + adder;
+ bo[i] = bi[i] + adder;
}
}
} else {
adderUGen.update();
if (outs == 1) {
float[] bi = bufIn[0];
float[] bo = bufOut[0];
for (int i = 0; i < bufferSize; i++) {
adder = adderUGen.getValue(0, i);
bo[i] = bi[i] + adder;
}
} else {
for (int i = 0; i < bufferSize; i++) {
for (int j = 0; j < outs; j++) {
adder = adderUGen.getValue(0, i);
bufOut[j][i] = bufIn[j][i] + adder;
}
}
}
}
}
/**
* Gets the current adder value.
*
* @return The adder value.
*/
public float getAdder() {
return adder;
}
/**
* Sets the adder to a static float value.
*
* @param adder
* The new adder value.
* @return This Add instance.
*/
public Add setAdder(float adder) {
this.adder = adder;
adderUGen = null;
return this;
}
/**
* Sets a UGen to control the adder value.
*
* @param adderUGen
* The adder UGen controller.
* @return This Add instance.
*/
public Add setAdder(UGen adderUGen) {
if (adderUGen == null) {
setAdder(adder);
} else {
this.adderUGen = adderUGen;
adderUGen.update();
adder = adderUGen.getValue();
}
return this;
}
/**
* Gets the adder UGen controller.
*
* @return The adder UGen controller.
*/
public UGen getAdderUGen() {
return adderUGen;
}
}
| true | true | public void calculateBuffer() {
if (adderUGen == null) {
for (int j = 0; j < outs; j++) {
float[] bi = bufIn[j];
float[] bo = bufOut[j];
for (int i = 0; i < bufferSize; i++) {
bo[i] = bi[j] + adder;
}
}
} else {
adderUGen.update();
if (outs == 1) {
float[] bi = bufIn[0];
float[] bo = bufOut[0];
for (int i = 0; i < bufferSize; i++) {
adder = adderUGen.getValue(0, i);
bo[i] = bi[i] + adder;
}
} else {
for (int i = 0; i < bufferSize; i++) {
for (int j = 0; j < outs; j++) {
adder = adderUGen.getValue(0, i);
bufOut[j][i] = bufIn[j][i] + adder;
}
}
}
}
}
| public void calculateBuffer() {
if (adderUGen == null) {
for (int j = 0; j < outs; j++) {
float[] bi = bufIn[j];
float[] bo = bufOut[j];
for (int i = 0; i < bufferSize; i++) {
bo[i] = bi[i] + adder;
}
}
} else {
adderUGen.update();
if (outs == 1) {
float[] bi = bufIn[0];
float[] bo = bufOut[0];
for (int i = 0; i < bufferSize; i++) {
adder = adderUGen.getValue(0, i);
bo[i] = bi[i] + adder;
}
} else {
for (int i = 0; i < bufferSize; i++) {
for (int j = 0; j < outs; j++) {
adder = adderUGen.getValue(0, i);
bufOut[j][i] = bufIn[j][i] + adder;
}
}
}
}
}
|
diff --git a/src/main/java/com/edwardhand/mobrider/listeners/RiderDamageListener.java b/src/main/java/com/edwardhand/mobrider/listeners/RiderDamageListener.java
index 0a20352..bc29432 100644
--- a/src/main/java/com/edwardhand/mobrider/listeners/RiderDamageListener.java
+++ b/src/main/java/com/edwardhand/mobrider/listeners/RiderDamageListener.java
@@ -1,114 +1,114 @@
package com.edwardhand.mobrider.listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import com.edwardhand.mobrider.MobRider;
import com.edwardhand.mobrider.managers.GoalManager;
import com.edwardhand.mobrider.managers.RiderManager;
import com.edwardhand.mobrider.models.Rider;
public class RiderDamageListener implements Listener
{
private RiderManager riderManager;
private GoalManager goalManager;
public RiderDamageListener(MobRider plugin)
{
riderManager = plugin.getRiderManager();
goalManager = plugin.getGoalManager();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event)
{
if (event.isCancelled())
return;
Entity entity = event.getEntity();
Entity damager = event.getDamager();
if (damager instanceof Projectile) {
damager = ((Projectile) damager).getShooter();
}
// rider damaged by entity
if (entity instanceof Player) {
Rider rider = riderManager.getRider((Player) entity);
if (rider.isValid()) {
LivingEntity ride = rider.getRide();
if (damager.equals(ride)) {
event.setCancelled(true); // riders get in the way of
// skeleton arrows
}
else if (!damager.equals(ride) && !damager.equals(rider.getTarget())) {
goalManager.setAttackGoal(rider, (LivingEntity) damager);
return;
}
}
}
// entity damaged by rider
if (damager instanceof Player) {
Rider rider = riderManager.getRider((Player) damager);
if (rider.isValid()) {
LivingEntity ride = rider.getRide();
if (!entity.equals(ride) && !entity.equals(rider.getTarget())) {
goalManager.setAttackGoal(rider, (LivingEntity) entity);
return;
}
}
}
// ride damaged by entity
- if (damager instanceof LivingEntity) {
+ if (damager instanceof LivingEntity && entity.getPassenger() instanceof Player) {
Player player = (Player) entity.getPassenger();
- Rider rider = riderManager.getRider(player);
+ Rider rider = riderManager.getRider((Player) entity.getPassenger());
if (rider.isValid()) {
if (!damager.equals(player)) {
goalManager.setAttackGoal(rider, (LivingEntity) damager);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByBlock(EntityDamageByBlockEvent event)
{
Entity entity = event.getEntity();
if (entity instanceof Player) {
// rider damaged by drowning or suffocation
Rider rider = riderManager.getRider((Player) entity);
if (rider.isValid()) {
switch (event.getCause()) {
case SUFFOCATION:
event.setCancelled(true);
break;
case DROWNING:
if (rider.hasWaterCreature()) {
event.setCancelled(true);
}
break;
default:
break;
}
}
}
}
}
| false | true | public void onEntityDamageByEntity(EntityDamageByEntityEvent event)
{
if (event.isCancelled())
return;
Entity entity = event.getEntity();
Entity damager = event.getDamager();
if (damager instanceof Projectile) {
damager = ((Projectile) damager).getShooter();
}
// rider damaged by entity
if (entity instanceof Player) {
Rider rider = riderManager.getRider((Player) entity);
if (rider.isValid()) {
LivingEntity ride = rider.getRide();
if (damager.equals(ride)) {
event.setCancelled(true); // riders get in the way of
// skeleton arrows
}
else if (!damager.equals(ride) && !damager.equals(rider.getTarget())) {
goalManager.setAttackGoal(rider, (LivingEntity) damager);
return;
}
}
}
// entity damaged by rider
if (damager instanceof Player) {
Rider rider = riderManager.getRider((Player) damager);
if (rider.isValid()) {
LivingEntity ride = rider.getRide();
if (!entity.equals(ride) && !entity.equals(rider.getTarget())) {
goalManager.setAttackGoal(rider, (LivingEntity) entity);
return;
}
}
}
// ride damaged by entity
if (damager instanceof LivingEntity) {
Player player = (Player) entity.getPassenger();
Rider rider = riderManager.getRider(player);
if (rider.isValid()) {
if (!damager.equals(player)) {
goalManager.setAttackGoal(rider, (LivingEntity) damager);
}
}
}
}
| public void onEntityDamageByEntity(EntityDamageByEntityEvent event)
{
if (event.isCancelled())
return;
Entity entity = event.getEntity();
Entity damager = event.getDamager();
if (damager instanceof Projectile) {
damager = ((Projectile) damager).getShooter();
}
// rider damaged by entity
if (entity instanceof Player) {
Rider rider = riderManager.getRider((Player) entity);
if (rider.isValid()) {
LivingEntity ride = rider.getRide();
if (damager.equals(ride)) {
event.setCancelled(true); // riders get in the way of
// skeleton arrows
}
else if (!damager.equals(ride) && !damager.equals(rider.getTarget())) {
goalManager.setAttackGoal(rider, (LivingEntity) damager);
return;
}
}
}
// entity damaged by rider
if (damager instanceof Player) {
Rider rider = riderManager.getRider((Player) damager);
if (rider.isValid()) {
LivingEntity ride = rider.getRide();
if (!entity.equals(ride) && !entity.equals(rider.getTarget())) {
goalManager.setAttackGoal(rider, (LivingEntity) entity);
return;
}
}
}
// ride damaged by entity
if (damager instanceof LivingEntity && entity.getPassenger() instanceof Player) {
Player player = (Player) entity.getPassenger();
Rider rider = riderManager.getRider((Player) entity.getPassenger());
if (rider.isValid()) {
if (!damager.equals(player)) {
goalManager.setAttackGoal(rider, (LivingEntity) damager);
}
}
}
}
|
diff --git a/PacketHandler.java b/PacketHandler.java
index 9ffbe33..41753c3 100644
--- a/PacketHandler.java
+++ b/PacketHandler.java
@@ -1,70 +1,70 @@
package assets.pchan3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import assets.pchan3.steamship.EntityAirship;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;
/**
*
* @author pchan3
*/
public class PacketHandler implements IPacketHandler
{
public static String CHANNEL = "Steamship";
@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload payload, Player player)
{
if (payload.channel.equals(CHANNEL)) {
this.handle(payload,player);
}
}
private void handle(Packet250CustomPayload payload, Player player) {
DataInputStream inStream = new DataInputStream(new ByteArrayInputStream(payload.data));
short data;
try {
data = inStream.readShort();
} catch (IOException e) {
e.printStackTrace();
return;
}
Entity ent = ((EntityPlayer)player).ridingEntity;
if (ent!=null && ent instanceof EntityAirship){
switch(data){
- case 0: ((EntityPlayer)player).openGui(PChan3Mods.instance, PChan3Mods.instance.GUI_ID, ent.worldObj, ent.serverPosX, ent.serverPosY, ent.serverPosZ);break;
+ case 0: ((EntityPlayer)player).openGui(PChan3Mods.instance, PChan3Mods.instance.GUI_ID, ent.worldObj, (int)ent.posX, (int)ent.posY, (int)ent.posZ);break;
case 1: ((EntityAirship)ent).isGoingUp=true;break;
case 2: ((EntityAirship)ent).isGoingDown=true;break;
case 3: ((EntityAirship)ent).isFiring=true;break;
case 4: ((EntityAirship)ent).isGoingUp=false;break;
case 5: ((EntityAirship)ent).isGoingDown=false;break;
case 6: ((EntityAirship)ent).isFiring=false;break;
}
}
}
public static Packet getPacket(int i) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(2);
DataOutputStream outputStream = new DataOutputStream(bos);
try {
outputStream.writeShort(i);
} catch (Exception ex) {
ex.printStackTrace();
}
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = CHANNEL;
packet.data = bos.toByteArray();
packet.length = bos.size();
return packet;
}
}
| true | true | private void handle(Packet250CustomPayload payload, Player player) {
DataInputStream inStream = new DataInputStream(new ByteArrayInputStream(payload.data));
short data;
try {
data = inStream.readShort();
} catch (IOException e) {
e.printStackTrace();
return;
}
Entity ent = ((EntityPlayer)player).ridingEntity;
if (ent!=null && ent instanceof EntityAirship){
switch(data){
case 0: ((EntityPlayer)player).openGui(PChan3Mods.instance, PChan3Mods.instance.GUI_ID, ent.worldObj, ent.serverPosX, ent.serverPosY, ent.serverPosZ);break;
case 1: ((EntityAirship)ent).isGoingUp=true;break;
case 2: ((EntityAirship)ent).isGoingDown=true;break;
case 3: ((EntityAirship)ent).isFiring=true;break;
case 4: ((EntityAirship)ent).isGoingUp=false;break;
case 5: ((EntityAirship)ent).isGoingDown=false;break;
case 6: ((EntityAirship)ent).isFiring=false;break;
}
}
}
| private void handle(Packet250CustomPayload payload, Player player) {
DataInputStream inStream = new DataInputStream(new ByteArrayInputStream(payload.data));
short data;
try {
data = inStream.readShort();
} catch (IOException e) {
e.printStackTrace();
return;
}
Entity ent = ((EntityPlayer)player).ridingEntity;
if (ent!=null && ent instanceof EntityAirship){
switch(data){
case 0: ((EntityPlayer)player).openGui(PChan3Mods.instance, PChan3Mods.instance.GUI_ID, ent.worldObj, (int)ent.posX, (int)ent.posY, (int)ent.posZ);break;
case 1: ((EntityAirship)ent).isGoingUp=true;break;
case 2: ((EntityAirship)ent).isGoingDown=true;break;
case 3: ((EntityAirship)ent).isFiring=true;break;
case 4: ((EntityAirship)ent).isGoingUp=false;break;
case 5: ((EntityAirship)ent).isGoingDown=false;break;
case 6: ((EntityAirship)ent).isFiring=false;break;
}
}
}
|
diff --git a/src/edu/ucla/cens/awserver/service/MessageLoggerService.java b/src/edu/ucla/cens/awserver/service/MessageLoggerService.java
index bbe5b293..55fad967 100644
--- a/src/edu/ucla/cens/awserver/service/MessageLoggerService.java
+++ b/src/edu/ucla/cens/awserver/service/MessageLoggerService.java
@@ -1,120 +1,124 @@
package edu.ucla.cens.awserver.service;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import edu.ucla.cens.awserver.datatransfer.AwRequest;
import edu.ucla.cens.awserver.util.JsonUtils;
/**
* Service for logging details about data uploads.
*
* @author selsky
*/
public class MessageLoggerService implements Service {
private static Logger _uploadLogger = Logger.getLogger("uploadLogger");
private static Logger _logger = Logger.getLogger(MessageLoggerService.class);
/**
* Performs the following tasks: logs the user's upload to the filesystem, logs the failed response message to the filesystem
* (if the request failed), and logs a statistic message to the upload logger.
*/
public void execute(AwRequest awRequest) {
_logger.info("beginning to log files and stats about a device upload");
logUploadToFilesystem(awRequest);
logUploadStats(awRequest);
_logger.info("finished with logging files and stats about a device upload");
}
private void logUploadStats(AwRequest awRequest) {
Object data = awRequest.getAttribute("jsonData");
String totalNumberOfMessages = "unknown";
String numberOfDuplicates = "unknown";
if(data instanceof JSONArray) {
totalNumberOfMessages = String.valueOf(((JSONArray) data).length());
List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList");
if(null != duplicateIndexList && duplicateIndexList.size() > 0) {
numberOfDuplicates = String.valueOf(duplicateIndexList.size());
} else {
numberOfDuplicates = "0";
}
}
long processingTime = System.currentTimeMillis() - (Long) awRequest.getAttribute("startTime");
StringBuilder builder = new StringBuilder();
if(awRequest.isFailedRequest()) {
builder.append("failed_upload");
} else {
builder.append("successful_upload");
}
builder.append(" user=" + awRequest.getUser().getUserName());
builder.append(" requestType=" + (String) awRequest.getAttribute("requestType"));
builder.append(" numberOfRecords=" + totalNumberOfMessages);
builder.append(" numberOfDuplicates=" + numberOfDuplicates);
builder.append(" proccessingTimeMillis=" + processingTime);
_uploadLogger.info(builder.toString());
}
private void logUploadToFilesystem(AwRequest awRequest) {
// Persist the devices's upload to the filesystem
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = awRequest.getUser().getUserName() + "-" + sdf.format(new Date());
String catalinaBase = System.getProperty("catalina.base"); // need a system prop called upload-logging-directory or something like that
Object data = awRequest.getAttribute("jsonData"); // could either be a String or a JSONArray depending on where the main
// application processing ended
try {
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload.json"))));
- printWriter.write(data.toString());
+ if(null != data) {
+ printWriter.write(data.toString());
+ } else {
+ printWriter.write("no data");
+ }
close(printWriter);
if(awRequest.isFailedRequest()) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-failed-upload-response.json"))));
printWriter.write(awRequest.getFailedRequestErrorMessage());
close(printWriter);
}
List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList");
if(null != duplicateIndexList && duplicateIndexList.size() > 0) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload-duplicates.json"))));
for(Integer index : duplicateIndexList) {
printWriter.write(JsonUtils.getJsonObjectFromJsonArray((JSONArray) data, index).toString());
}
close(printWriter);
}
}
catch(IOException ioe) {
_logger.warn("caught IOException when logging upload data to the filesystem. " + ioe.getMessage());
throw new ServiceException(ioe);
}
}
private void close(PrintWriter writer) throws IOException {
writer.flush();
writer.close();
writer = null;
}
}
| true | true | private void logUploadToFilesystem(AwRequest awRequest) {
// Persist the devices's upload to the filesystem
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = awRequest.getUser().getUserName() + "-" + sdf.format(new Date());
String catalinaBase = System.getProperty("catalina.base"); // need a system prop called upload-logging-directory or something like that
Object data = awRequest.getAttribute("jsonData"); // could either be a String or a JSONArray depending on where the main
// application processing ended
try {
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload.json"))));
printWriter.write(data.toString());
close(printWriter);
if(awRequest.isFailedRequest()) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-failed-upload-response.json"))));
printWriter.write(awRequest.getFailedRequestErrorMessage());
close(printWriter);
}
List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList");
if(null != duplicateIndexList && duplicateIndexList.size() > 0) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload-duplicates.json"))));
for(Integer index : duplicateIndexList) {
printWriter.write(JsonUtils.getJsonObjectFromJsonArray((JSONArray) data, index).toString());
}
close(printWriter);
}
}
catch(IOException ioe) {
_logger.warn("caught IOException when logging upload data to the filesystem. " + ioe.getMessage());
throw new ServiceException(ioe);
}
}
| private void logUploadToFilesystem(AwRequest awRequest) {
// Persist the devices's upload to the filesystem
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = awRequest.getUser().getUserName() + "-" + sdf.format(new Date());
String catalinaBase = System.getProperty("catalina.base"); // need a system prop called upload-logging-directory or something like that
Object data = awRequest.getAttribute("jsonData"); // could either be a String or a JSONArray depending on where the main
// application processing ended
try {
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload.json"))));
if(null != data) {
printWriter.write(data.toString());
} else {
printWriter.write("no data");
}
close(printWriter);
if(awRequest.isFailedRequest()) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-failed-upload-response.json"))));
printWriter.write(awRequest.getFailedRequestErrorMessage());
close(printWriter);
}
List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList");
if(null != duplicateIndexList && duplicateIndexList.size() > 0) {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/uploads/" + fileName + "-upload-duplicates.json"))));
for(Integer index : duplicateIndexList) {
printWriter.write(JsonUtils.getJsonObjectFromJsonArray((JSONArray) data, index).toString());
}
close(printWriter);
}
}
catch(IOException ioe) {
_logger.warn("caught IOException when logging upload data to the filesystem. " + ioe.getMessage());
throw new ServiceException(ioe);
}
}
|
diff --git a/BMC/src/bmc/game/level/Level.java b/BMC/src/bmc/game/level/Level.java
index 14c24d0..894b975 100644
--- a/BMC/src/bmc/game/level/Level.java
+++ b/BMC/src/bmc/game/level/Level.java
@@ -1,231 +1,231 @@
package bmc.game.level;
import java.util.ArrayList;
import bmc.game.Panel;
import bmc.game.gameobjects.GameObject;
import bmc.game.gameobjects.Sprite;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
public class Level {
protected ArrayList<Path> paths;
protected ArrayList<Entrance> entrances;
protected ArrayList<Block> blocksOnScreen;
protected Sprite[] mSprites;
protected RectF mRect = new RectF();
protected Rect mDestination = new Rect();
protected int mWidth;
protected int mHeight;
protected boolean initialized=false;
public enum CollisionStates
{
NONE,
LEFT,
RIGHT,
TOP,
BOTTOM,
TOPANDLEFT,
TOPANDRIGHT,
BOTTOMANDLEFT,
BOTTOMANDRIGHT
}
public Level()
{
paths = new ArrayList<Path>();
entrances = new ArrayList<Entrance>();
blocksOnScreen = new ArrayList<Block>();
}
public void AddPath (Path path)
{
paths.add(path);
}
public void AddEntrance (Entrance entrance)
{
entrances.add(entrance);
}
public void animate(long elapsedTime,float X, float Y) {
// TODO Auto-generated method stub
mWidth = (int) Panel.mWidth;
mHeight = (int) Panel.mHeight;
this.addX(X);
this.addY(Y);
if(X+Y != 0 || !initialized)
{
synchronized (blocksOnScreen)
{
blocksOnScreen.clear();
//if we change the screen look through blocks to see which ones we need to draw
synchronized (paths) {
for (Path path : paths) {
for (Block block : path.getBlocks())
{
if(block.shouldDraw(mDestination))
{
block.animate(elapsedTime);
blocksOnScreen.add(block);
}
}
}
}
initialized = true;
}
}
}
public void doDraw(Canvas canvas) {
// TODO Auto-generated method stub
synchronized (blocksOnScreen)
{
for (Block block : blocksOnScreen)
{
block.doDraw(canvas);
}
}
}
public CollisionStates IsCollidingWithLevel(RectF rect)
{
// We have the bounding rectangle for the object in question. Now
// we should check all of the blocks in our paths to see if they intersect in any direction.
CollisionStates state = CollisionStates.NONE;
boolean top = false, bottom = false, left = false, right = false;
for (Path p : paths)
{
ArrayList<Block> blocks = p.getBlocks();
for (Block b : blocks)
{
// Bounds for top and bottom
- if ((rect.left >= b.getXpos() || rect.right <= b.getXpos() + b.getWidth()))
+ if ((rect.left >= b.getXpos() && rect.left <= b.getXpos()+b.getWidth()) || (rect.right <= b.getXpos() + b.getWidth())&& rect.right <= b.getXpos())
{
// Top check
- if (rect.top < b.getYpos() + b.getHeight())
+ if (rect.top <= b.getYpos() + b.getHeight() && rect.top >= b.getYpos())
{
top = true;
}
- if (rect.bottom > b.getYpos())
+ if (rect.bottom >= b.getYpos() && rect.bottom <= b. getYpos() + b.getHeight())
{
bottom = true;
}
}
// Bounds for left and right
- if ((rect.top >= b.getYpos() || rect.bottom <= b.getYpos() + b.getHeight()))
+ if ((rect.top >= b.getYpos()&& rect.top <= b.getYpos()+b.getHeight()) || (rect.bottom <= b.getYpos() + b.getHeight() && rect.bottom >= b.getYpos()))
{
// Left check
- if (rect.left <= b.getXpos() + b.getWidth())
+ if (rect.left >= b.getXpos() && rect.left <= b.getXpos()+b.getWidth())
{
left = true;
}
// Right check
- if (rect.right >= b.getXpos())
+ if (rect.right <= b.getXpos()+ b.getWidth() && rect.right >= b.getXpos())
{
right = true;
}
}
}
}
// Now, merge the booleans
if (top)
{
if (left) { state = CollisionStates.TOPANDLEFT; }
else if (right) { state = CollisionStates.TOPANDRIGHT; }
else { state = CollisionStates.TOP; }
}
else if (bottom)
{
if (left) { state = CollisionStates.BOTTOMANDLEFT; }
else if (right) { state = CollisionStates.BOTTOMANDRIGHT; }
else { state = CollisionStates.BOTTOM; }
}
// We already checked for the combined ones, so we can safely use else if's to check for left and right
else if (left) { state = CollisionStates.LEFT; }
else if (right) { state = CollisionStates.RIGHT; }
// If it didn't hit any of those, it's already set to NONE.
return state;
}
public void addX(float X)
{
setX(mRect.left+X);
}
public void addY(float Y)
{
setY(mRect.top+Y);
}
public float getX() {
return mRect.left;
}
public void setX(float mX) {
this.mRect.left = mX;
mRect.right = mRect.left+mWidth;
this.mDestination.left = (int)mX;
mDestination.right = mDestination.left+mWidth;
}
public float getY() {
return mRect.top;
}
public void setY(float mY) {
this.mRect.top = mY;
mRect.bottom = mRect.top+mHeight;
this.mDestination.top = (int)mY;
mDestination.bottom = mDestination.top+mHeight;
}
public Rect getDestination() {
return mDestination;
}
public void setDestination(Rect mDestination) {
this.mDestination = mDestination;
}
public RectF getRect() {
return mRect;
}
public void setRect(RectF mRect) {
this.mRect = mRect;
}
public int getmWidth() {
return mWidth;
}
public void setmWidth(int mWidth) {
this.mWidth = mWidth;
}
public int getmHeight() {
return mHeight;
}
public void setmHeight(int mHeight) {
this.mHeight = mHeight;
}
public Sprite[] getmSprites() {
return mSprites;
}
public void setmSprites(Sprite[] mSprites) {
this.mSprites = mSprites;
}
}
| false | true | public CollisionStates IsCollidingWithLevel(RectF rect)
{
// We have the bounding rectangle for the object in question. Now
// we should check all of the blocks in our paths to see if they intersect in any direction.
CollisionStates state = CollisionStates.NONE;
boolean top = false, bottom = false, left = false, right = false;
for (Path p : paths)
{
ArrayList<Block> blocks = p.getBlocks();
for (Block b : blocks)
{
// Bounds for top and bottom
if ((rect.left >= b.getXpos() || rect.right <= b.getXpos() + b.getWidth()))
{
// Top check
if (rect.top < b.getYpos() + b.getHeight())
{
top = true;
}
if (rect.bottom > b.getYpos())
{
bottom = true;
}
}
// Bounds for left and right
if ((rect.top >= b.getYpos() || rect.bottom <= b.getYpos() + b.getHeight()))
{
// Left check
if (rect.left <= b.getXpos() + b.getWidth())
{
left = true;
}
// Right check
if (rect.right >= b.getXpos())
{
right = true;
}
}
}
}
// Now, merge the booleans
if (top)
{
if (left) { state = CollisionStates.TOPANDLEFT; }
else if (right) { state = CollisionStates.TOPANDRIGHT; }
else { state = CollisionStates.TOP; }
}
else if (bottom)
{
if (left) { state = CollisionStates.BOTTOMANDLEFT; }
else if (right) { state = CollisionStates.BOTTOMANDRIGHT; }
else { state = CollisionStates.BOTTOM; }
}
// We already checked for the combined ones, so we can safely use else if's to check for left and right
else if (left) { state = CollisionStates.LEFT; }
else if (right) { state = CollisionStates.RIGHT; }
// If it didn't hit any of those, it's already set to NONE.
return state;
}
| public CollisionStates IsCollidingWithLevel(RectF rect)
{
// We have the bounding rectangle for the object in question. Now
// we should check all of the blocks in our paths to see if they intersect in any direction.
CollisionStates state = CollisionStates.NONE;
boolean top = false, bottom = false, left = false, right = false;
for (Path p : paths)
{
ArrayList<Block> blocks = p.getBlocks();
for (Block b : blocks)
{
// Bounds for top and bottom
if ((rect.left >= b.getXpos() && rect.left <= b.getXpos()+b.getWidth()) || (rect.right <= b.getXpos() + b.getWidth())&& rect.right <= b.getXpos())
{
// Top check
if (rect.top <= b.getYpos() + b.getHeight() && rect.top >= b.getYpos())
{
top = true;
}
if (rect.bottom >= b.getYpos() && rect.bottom <= b. getYpos() + b.getHeight())
{
bottom = true;
}
}
// Bounds for left and right
if ((rect.top >= b.getYpos()&& rect.top <= b.getYpos()+b.getHeight()) || (rect.bottom <= b.getYpos() + b.getHeight() && rect.bottom >= b.getYpos()))
{
// Left check
if (rect.left >= b.getXpos() && rect.left <= b.getXpos()+b.getWidth())
{
left = true;
}
// Right check
if (rect.right <= b.getXpos()+ b.getWidth() && rect.right >= b.getXpos())
{
right = true;
}
}
}
}
// Now, merge the booleans
if (top)
{
if (left) { state = CollisionStates.TOPANDLEFT; }
else if (right) { state = CollisionStates.TOPANDRIGHT; }
else { state = CollisionStates.TOP; }
}
else if (bottom)
{
if (left) { state = CollisionStates.BOTTOMANDLEFT; }
else if (right) { state = CollisionStates.BOTTOMANDRIGHT; }
else { state = CollisionStates.BOTTOM; }
}
// We already checked for the combined ones, so we can safely use else if's to check for left and right
else if (left) { state = CollisionStates.LEFT; }
else if (right) { state = CollisionStates.RIGHT; }
// If it didn't hit any of those, it's already set to NONE.
return state;
}
|
diff --git a/src/main/java/com/mns/mojoinvest/server/pipeline/quote/ISharesQuoteFetcherControlJob.java b/src/main/java/com/mns/mojoinvest/server/pipeline/quote/ISharesQuoteFetcherControlJob.java
index 2e054a1..72c2c20 100644
--- a/src/main/java/com/mns/mojoinvest/server/pipeline/quote/ISharesQuoteFetcherControlJob.java
+++ b/src/main/java/com/mns/mojoinvest/server/pipeline/quote/ISharesQuoteFetcherControlJob.java
@@ -1,38 +1,34 @@
package com.mns.mojoinvest.server.pipeline.quote;
import com.google.appengine.tools.pipeline.FutureValue;
import com.google.appengine.tools.pipeline.Job1;
import com.google.appengine.tools.pipeline.Value;
import com.mns.mojoinvest.server.engine.model.Fund;
import com.mns.mojoinvest.server.engine.model.dao.FundDao;
import com.mns.mojoinvest.server.pipeline.GenericPipelines;
import com.mns.mojoinvest.server.pipeline.PipelineHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
public class ISharesQuoteFetcherControlJob extends Job1<String, String> {
private static final Logger log = Logger.getLogger(ISharesQuoteFetcherControlJob.class.getName());
@Override
public Value<String> run(String sessionId) {
List<FutureValue<String>> quotesUpdated = new ArrayList<FutureValue<String>>();
FundDao dao = PipelineHelper.getFundDao();
for (Fund fund : dao.list()) {
-// quotesUpdated.add(futureCall(new ISharesQuoteFetcherJob(), immediate(fund.getFundId()),
-// immediate(sessionId)));
- FutureValue<String> s = futureCall(new ISharesQuoteFetcherJob(), immediate("200306"),
- immediate(sessionId));
- log.info(s.getSourceJobHandle());
- break;
+ quotesUpdated.add(futureCall(new ISharesQuoteFetcherJob(), immediate(fund.getFundId()),
+ immediate(sessionId)));
}
return futureCall(new GenericPipelines.MergeListJob(), futureList(quotesUpdated));
}
}
| true | true | public Value<String> run(String sessionId) {
List<FutureValue<String>> quotesUpdated = new ArrayList<FutureValue<String>>();
FundDao dao = PipelineHelper.getFundDao();
for (Fund fund : dao.list()) {
// quotesUpdated.add(futureCall(new ISharesQuoteFetcherJob(), immediate(fund.getFundId()),
// immediate(sessionId)));
FutureValue<String> s = futureCall(new ISharesQuoteFetcherJob(), immediate("200306"),
immediate(sessionId));
log.info(s.getSourceJobHandle());
break;
}
return futureCall(new GenericPipelines.MergeListJob(), futureList(quotesUpdated));
}
| public Value<String> run(String sessionId) {
List<FutureValue<String>> quotesUpdated = new ArrayList<FutureValue<String>>();
FundDao dao = PipelineHelper.getFundDao();
for (Fund fund : dao.list()) {
quotesUpdated.add(futureCall(new ISharesQuoteFetcherJob(), immediate(fund.getFundId()),
immediate(sessionId)));
}
return futureCall(new GenericPipelines.MergeListJob(), futureList(quotesUpdated));
}
|
diff --git a/aura-impl/src/test/java/org/auraframework/impl/layouts/LayoutItemsUITest.java b/aura-impl/src/test/java/org/auraframework/impl/layouts/LayoutItemsUITest.java
index 2f57ef84c0..4d5b551839 100644
--- a/aura-impl/src/test/java/org/auraframework/impl/layouts/LayoutItemsUITest.java
+++ b/aura-impl/src/test/java/org/auraframework/impl/layouts/LayoutItemsUITest.java
@@ -1,110 +1,110 @@
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.layouts;
import java.util.concurrent.TimeUnit;
import org.auraframework.test.WebDriverTestCase;
import org.openqa.selenium.By;
/**
* Automation for verifying Layouts.
*/
public class LayoutItemsUITest extends WebDriverTestCase {
private final By resultBtn1 = By.cssSelector(".Button1");
private final By resultBtn2 = By.cssSelector(".Button2");
public LayoutItemsUITest(String name) {
super(name);
}
/**
* Verify that navigating forward and backward works when underlying LayoutsDef has multiple layoutitems per layout.
* Automation for W-954182
*/
public void testNavigationWhenLayoutHasMultipleLayoutItems() throws Exception {
By forwardButton = By.cssSelector(".Forward_Button");
By backButton = By.cssSelector(".Back_Button");
By layoutDone = By.cssSelector(".layoutDone");
By removeLayoutDone = By.cssSelector(".Remove_Layout_Done");
open("/layoutServiceTest/multipleLayoutItems.app");
// might take a while for initial layout to load
getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
// subsequent layouts should NOT take that long to load
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultForLayout2();
findDomElement(backButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(backButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(removeLayoutDone).click();
- getDriver().navigate().back();
+ auraUITestingUtil.getEval("window.history.back()");
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
findDomElement(removeLayoutDone).click();
- getDriver().navigate().forward();
+ auraUITestingUtil.getEval("window.history.forward()");
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
}
private void verifyExpectedResultsForInitialLayout() throws Exception {
assertEquals("Ready to party?", findDomElement(resultBtn1).getText());
assertEquals("", findDomElement(resultBtn2).getText());
}
private void verifyExpectedResultsForLayout1() throws Exception {
assertEquals("Step1", getHashToken());
assertEquals("Step 1a. Wear a Suit", findDomElement(resultBtn1).getText());
assertEquals("Step 1b. Wear a Jacket", findDomElement(resultBtn2).getText());
}
private void verifyExpectedResultForLayout2() throws Exception {
assertEquals("Step2", getHashToken());
assertEquals("Step 2a. Start your car", findDomElement(resultBtn1).getText());
assertEquals("Step 2b. Go party", findDomElement(resultBtn2).getText());
}
private String getHashToken() {
String URL = getDriver().getCurrentUrl();
assertTrue("URL does not contain a # token", URL.indexOf("#") > -1);
String[] tokens = URL.split("#");
assertEquals("URL has multiple # tokens", 2, tokens.length);
return tokens[1];
}
}
| false | true | public void testNavigationWhenLayoutHasMultipleLayoutItems() throws Exception {
By forwardButton = By.cssSelector(".Forward_Button");
By backButton = By.cssSelector(".Back_Button");
By layoutDone = By.cssSelector(".layoutDone");
By removeLayoutDone = By.cssSelector(".Remove_Layout_Done");
open("/layoutServiceTest/multipleLayoutItems.app");
// might take a while for initial layout to load
getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
// subsequent layouts should NOT take that long to load
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultForLayout2();
findDomElement(backButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(backButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(removeLayoutDone).click();
getDriver().navigate().back();
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
findDomElement(removeLayoutDone).click();
getDriver().navigate().forward();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
}
| public void testNavigationWhenLayoutHasMultipleLayoutItems() throws Exception {
By forwardButton = By.cssSelector(".Forward_Button");
By backButton = By.cssSelector(".Back_Button");
By layoutDone = By.cssSelector(".layoutDone");
By removeLayoutDone = By.cssSelector(".Remove_Layout_Done");
open("/layoutServiceTest/multipleLayoutItems.app");
// might take a while for initial layout to load
getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
// subsequent layouts should NOT take that long to load
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultForLayout2();
findDomElement(backButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(backButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
findDomElement(forwardButton).click();
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
findDomElement(removeLayoutDone).click();
auraUITestingUtil.getEval("window.history.back()");
findDomElement(layoutDone);
verifyExpectedResultsForInitialLayout();
findDomElement(removeLayoutDone).click();
auraUITestingUtil.getEval("window.history.forward()");
findDomElement(layoutDone);
verifyExpectedResultsForLayout1();
}
|
diff --git a/src/main/java/Sirius/server/search/builtin/GeoSearch.java b/src/main/java/Sirius/server/search/builtin/GeoSearch.java
index d15b587b..70649e57 100644
--- a/src/main/java/Sirius/server/search/builtin/GeoSearch.java
+++ b/src/main/java/Sirius/server/search/builtin/GeoSearch.java
@@ -1,126 +1,132 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2010 thorsten
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package Sirius.server.search.builtin;
import Sirius.server.localserver.object.ObjectHierarchy;
import Sirius.server.middleware.interfaces.domainserver.MetaService;
import Sirius.server.middleware.types.MetaClass;
import Sirius.server.middleware.types.MetaObjectNode;
import Sirius.server.middleware.types.Node;
import Sirius.server.search.CidsServerSearch;
import Sirius.server.search.StaticSearchTools;
import com.vividsolutions.jts.geom.Geometry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import de.cismet.cismap.commons.jtsgeometryfactories.PostGisGeometryFactory;
import de.cismet.tools.collections.MultiMap;
/**
* DOCUMENT ME!
*
* @author thorsten
* @version $Revision$, $Date$
*/
public class GeoSearch extends CidsServerSearch {
//~ Instance fields --------------------------------------------------------
Geometry searchGeometry = null;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new GeoSearch object.
*
* @param searchGeometry DOCUMENT ME!
*/
public GeoSearch(final Geometry searchGeometry) {
this.searchGeometry = searchGeometry;
}
//~ Methods ----------------------------------------------------------------
@Override
public Collection performServerSearch() {
final ArrayList<Node> aln = new ArrayList<Node>();
try {
getLog().info("geosearch started");
final Collection<MetaClass> classes = getValidClasses();
// "select class_id,object_id,name from GEOSUCHE where class_id in <cidsClassesInStatement> and geo_field && GeometryFromText('SRID=-1;<cidsSearchGeometryWKT>') and intersects(geo_field,GeometryFromText('SRID=-1;<cidsSearchGeometryWKT>'))";
final String sql = "WITH recursive derived_index(ocid,oid,acid,aid,depth) AS "
+ "( "
+ "SELECT class_id,object_id,cast (NULL AS int), cast (NULL AS int),0 "
+ "FROM GEOSUCHE WHERE class_id IN"
+ "( "
+ "WITH recursive derived_child(father,child,depth) AS ( "
+ "SELECT father,father,0 FROM cs_class_hierarchy WHERE father in <cidsClassesInStatement> "
+ "UNION ALL "
+ "SELECT ch.father,ch.child,dc.depth+1 FROM derived_child dc,cs_class_hierarchy ch WHERE ch.father=dc.child) "
+ "SELECT DISTINCT father FROM derived_child LIMIT 100 "
+ ") "
+ "AND geo_field && GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>') AND intersects(geo_field,GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>')) "
+ "UNION ALL "
+ "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_all_attr_mapping aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ ") "
+ "SELECT DISTINCT ocid,oid FROM derived_index WHERE ocid in <cidsClassesInStatement> LIMIT 1000 ";
// Deppensuche sequentiell
final HashSet keyset = new HashSet(getActiveLoaclServers().keySet());
final String cidsSearchGeometryWKT = searchGeometry.toText();
final String sridString = Integer.toString(searchGeometry.getSRID());
for (final Object key : keyset) {
final MetaService ms = (MetaService)getActiveLoaclServers().get(key);
final String classesInStatement = getClassesInSnippetsPerDomain().get((String)key);
- getLog().fatal("cidsClassesInStatement=" + classesInStatement);
- getLog().fatal("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
- getLog().fatal("cidsSearchGeometrySRID=" + sridString);
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("cidsClassesInStatement=" + classesInStatement);
+ }
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
+ }
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("cidsSearchGeometrySRID=" + sridString);
+ }
final String sqlStatement = sql.replaceAll("<cidsClassesInStatement>", classesInStatement)
.replaceAll("<cidsSearchGeometryWKT>", cidsSearchGeometryWKT)
.replaceAll("<cidsSearchGeometrySRID>", sridString);
getLog().info("geosearch: " + sqlStatement);
final ArrayList<ArrayList> result = ms.performCustomSearch(sqlStatement);
for (final ArrayList al : result) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final String name = null; // (String) al.get(2);
final MetaObjectNode mon = new MetaObjectNode((String)key, oid, cid);
aln.add(mon);
}
}
return aln;
} catch (Exception e) {
getLog().error("Problem during GEOSEARCH", e);
return aln;
}
}
}
| true | true | public Collection performServerSearch() {
final ArrayList<Node> aln = new ArrayList<Node>();
try {
getLog().info("geosearch started");
final Collection<MetaClass> classes = getValidClasses();
// "select class_id,object_id,name from GEOSUCHE where class_id in <cidsClassesInStatement> and geo_field && GeometryFromText('SRID=-1;<cidsSearchGeometryWKT>') and intersects(geo_field,GeometryFromText('SRID=-1;<cidsSearchGeometryWKT>'))";
final String sql = "WITH recursive derived_index(ocid,oid,acid,aid,depth) AS "
+ "( "
+ "SELECT class_id,object_id,cast (NULL AS int), cast (NULL AS int),0 "
+ "FROM GEOSUCHE WHERE class_id IN"
+ "( "
+ "WITH recursive derived_child(father,child,depth) AS ( "
+ "SELECT father,father,0 FROM cs_class_hierarchy WHERE father in <cidsClassesInStatement> "
+ "UNION ALL "
+ "SELECT ch.father,ch.child,dc.depth+1 FROM derived_child dc,cs_class_hierarchy ch WHERE ch.father=dc.child) "
+ "SELECT DISTINCT father FROM derived_child LIMIT 100 "
+ ") "
+ "AND geo_field && GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>') AND intersects(geo_field,GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>')) "
+ "UNION ALL "
+ "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_all_attr_mapping aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ ") "
+ "SELECT DISTINCT ocid,oid FROM derived_index WHERE ocid in <cidsClassesInStatement> LIMIT 1000 ";
// Deppensuche sequentiell
final HashSet keyset = new HashSet(getActiveLoaclServers().keySet());
final String cidsSearchGeometryWKT = searchGeometry.toText();
final String sridString = Integer.toString(searchGeometry.getSRID());
for (final Object key : keyset) {
final MetaService ms = (MetaService)getActiveLoaclServers().get(key);
final String classesInStatement = getClassesInSnippetsPerDomain().get((String)key);
getLog().fatal("cidsClassesInStatement=" + classesInStatement);
getLog().fatal("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
getLog().fatal("cidsSearchGeometrySRID=" + sridString);
final String sqlStatement = sql.replaceAll("<cidsClassesInStatement>", classesInStatement)
.replaceAll("<cidsSearchGeometryWKT>", cidsSearchGeometryWKT)
.replaceAll("<cidsSearchGeometrySRID>", sridString);
getLog().info("geosearch: " + sqlStatement);
final ArrayList<ArrayList> result = ms.performCustomSearch(sqlStatement);
for (final ArrayList al : result) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final String name = null; // (String) al.get(2);
final MetaObjectNode mon = new MetaObjectNode((String)key, oid, cid);
aln.add(mon);
}
}
return aln;
} catch (Exception e) {
getLog().error("Problem during GEOSEARCH", e);
return aln;
}
}
| public Collection performServerSearch() {
final ArrayList<Node> aln = new ArrayList<Node>();
try {
getLog().info("geosearch started");
final Collection<MetaClass> classes = getValidClasses();
// "select class_id,object_id,name from GEOSUCHE where class_id in <cidsClassesInStatement> and geo_field && GeometryFromText('SRID=-1;<cidsSearchGeometryWKT>') and intersects(geo_field,GeometryFromText('SRID=-1;<cidsSearchGeometryWKT>'))";
final String sql = "WITH recursive derived_index(ocid,oid,acid,aid,depth) AS "
+ "( "
+ "SELECT class_id,object_id,cast (NULL AS int), cast (NULL AS int),0 "
+ "FROM GEOSUCHE WHERE class_id IN"
+ "( "
+ "WITH recursive derived_child(father,child,depth) AS ( "
+ "SELECT father,father,0 FROM cs_class_hierarchy WHERE father in <cidsClassesInStatement> "
+ "UNION ALL "
+ "SELECT ch.father,ch.child,dc.depth+1 FROM derived_child dc,cs_class_hierarchy ch WHERE ch.father=dc.child) "
+ "SELECT DISTINCT father FROM derived_child LIMIT 100 "
+ ") "
+ "AND geo_field && GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>') AND intersects(geo_field,GeometryFromText('SRID=<cidsSearchGeometrySRID>;<cidsSearchGeometryWKT>')) "
+ "UNION ALL "
+ "SELECT aam.class_id,aam.object_id, aam.attr_class_id, aam.attr_object_id,di.depth+1 FROM cs_all_attr_mapping aam,derived_index di WHERE aam.attr_class_id=di.ocid AND aam.attr_object_id=di.oid"
+ ") "
+ "SELECT DISTINCT ocid,oid FROM derived_index WHERE ocid in <cidsClassesInStatement> LIMIT 1000 ";
// Deppensuche sequentiell
final HashSet keyset = new HashSet(getActiveLoaclServers().keySet());
final String cidsSearchGeometryWKT = searchGeometry.toText();
final String sridString = Integer.toString(searchGeometry.getSRID());
for (final Object key : keyset) {
final MetaService ms = (MetaService)getActiveLoaclServers().get(key);
final String classesInStatement = getClassesInSnippetsPerDomain().get((String)key);
if (getLog().isDebugEnabled()) {
getLog().debug("cidsClassesInStatement=" + classesInStatement);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometryWKT=" + cidsSearchGeometryWKT);
}
if (getLog().isDebugEnabled()) {
getLog().debug("cidsSearchGeometrySRID=" + sridString);
}
final String sqlStatement = sql.replaceAll("<cidsClassesInStatement>", classesInStatement)
.replaceAll("<cidsSearchGeometryWKT>", cidsSearchGeometryWKT)
.replaceAll("<cidsSearchGeometrySRID>", sridString);
getLog().info("geosearch: " + sqlStatement);
final ArrayList<ArrayList> result = ms.performCustomSearch(sqlStatement);
for (final ArrayList al : result) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final String name = null; // (String) al.get(2);
final MetaObjectNode mon = new MetaObjectNode((String)key, oid, cid);
aln.add(mon);
}
}
return aln;
} catch (Exception e) {
getLog().error("Problem during GEOSEARCH", e);
return aln;
}
}
|
diff --git a/src/com/joy/launcher2/push/PushDownloadManager.java b/src/com/joy/launcher2/push/PushDownloadManager.java
index 950adf8..962d7a2 100644
--- a/src/com/joy/launcher2/push/PushDownloadManager.java
+++ b/src/com/joy/launcher2/push/PushDownloadManager.java
@@ -1,220 +1,220 @@
package com.joy.launcher2.push;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.util.Log;
import android.view.View;
import com.joy.launcher2.LauncherApplication;
import com.joy.launcher2.network.impl.Service;
import com.joy.launcher2.util.Constants;
import com.joy.launcher2.util.Util;
/**
* download manager
*
* @author wanghao
*
*/
public class PushDownloadManager {
final String TAG = "PushDownloadManager";
public static Map<String, PushDownLoadTask> map = new HashMap<String, PushDownLoadTask>();
private Service mService;
static PushDownloadManager mDownloadManager;
public static boolean isPause = false;
Context mContext;
private PushDownloadManager(Context context) {
mContext = context;
try {
mService = Service.getInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public static PushDownloadManager getInstances() {
if (mDownloadManager == null) {
mDownloadManager = new PushDownloadManager(LauncherApplication.mContext);
}
return mDownloadManager;
}
public PushDownLoadTask newDownLoadTask(View view, PushDownloadInfo dInfo, PushCallBack callback, boolean secretly)
{
if (dInfo == null) {
return null;
}
int id = dInfo.getId();
// 已经在下载了
PushDownLoadTask task = getDowmloadingTask(id);
if (task != null) {
Log.i(TAG, "--------> 已经在下载了!!!");
return null;
}
Log.i(TAG, "-----dInfo---> getCompletesize :" + dInfo.getCompletesize());
//completesize == 0是新建下载
if (dInfo.getCompletesize() == 0) {
// 检查本地是否有重名了的文件
File localfile = new File(Constants.DOWNLOAD_APK_DIR + "/"+ dInfo.getFilename());
localfile = Util.getCleverFileName(localfile);
dInfo.setLocalname(localfile.getName());
}
// 创建线程开始下载
File file = new File(Constants.DOWNLOAD_APK_DIR + "/"+ dInfo.getLocalname());
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(file, "rwd");
rf.setLength(dInfo.getFilesize()*1024);
rf.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PushDownLoadTask downloader = new PushDownLoadTask(dInfo, file,callback,secretly);
// 加入map
map.put(String.valueOf(id), downloader);
return downloader;
}
// 下载子线程
public class PushDownLoadTask implements Runnable {
private boolean isSecretly;//下载方式 false正常 true静默下载
private File file;
private PushDownloadInfo downinfo;
PushCallBack callback;
public PushDownLoadTask(PushDownloadInfo downinfo,File file,PushCallBack callback,boolean secretly) {
this.downinfo = downinfo;
this.file = file;
this.callback = callback;
isSecretly = secretly;
callback.downloadUpdate();
}
public PushDownloadInfo getDownloadInfo(){
return downinfo;
}
public boolean isSecretly(){
return isSecretly;
}
public void run() {
InputStream is = null;
RandomAccessFile randomAccessFile = null;
try {
int startPos = downinfo.getCompletesize()*1024;
int endPos = downinfo.getFilesize()*1024;
is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos);
boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl());
randomAccessFile = new RandomAccessFile(file, "rwd");
if(!isBreakPoint)
{
downinfo.setCompletesize(0);
startPos = 0;
}
// 从断点处 继续下载(初始为0)
randomAccessFile.seek(startPos);
if (is == null) {
return;
}
final int length = 1024;
byte[] b = new byte[length];
int len = -1;
int pool = 0;
boolean isover = false;
long startime = System.currentTimeMillis();
Log.e(TAG, "-----downinfo starttime--->1 " + startime);
int tempLen = startPos;
callback.downloadUpdate();
while ((len = is.read(b))!=-1) {
if (isPause) {
return;
}
randomAccessFile.write(b, 0, len);
pool += len;
if (pool >= 100 * 1024) { // 100kb写一次数据库
Log.e(TAG, "-----下载 未完成----" + len);
PushDownLoadDBHelper.getInstances().update(downinfo); //暂不支持断点下载
pool = 0;
callback.downloadUpdate();// 刷新一次
}
tempLen += len;
downinfo.setCompletesize(tempLen/1024);
if (pool != 0) {
//PushDownLoadDBHelper.getInstances().update(downinfo);/// 暂不支持断点下载
}
}
long endtime = System.currentTimeMillis();
Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime));
} catch (Exception e) {
//Log.i(TAG, "-------->e " + e);
e.printStackTrace();
} finally {
// end.countDown();
Log.e(TAG, "---over----");
+ PushDownLoadDBHelper.getInstances().update(downinfo);
if (downinfo.getCompletesize() >= downinfo.getFilesize()) {
Log.i(TAG, "----finsh----");
- PushDownLoadDBHelper.getInstances().update(downinfo);
if(callback != null){
callback.downloadSucceed();
}
}else{
callback.downloadFailed();
}
callback.downloadUpdate();
map.remove(String.valueOf(downinfo.getId()));
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
}
}
}
}
}
public PushDownLoadTask getDowmloadingTask(int id){
PushDownLoadTask task = map.get(String.valueOf(id));
if (task != null) {
return task;
}
return null;
}
public boolean isCompleted(int id){
final PushDownloadInfo dInfo = PushDownLoadDBHelper.getInstances().get(id);
if (dInfo!= null&&dInfo.getCompletesize() >= dInfo.getFilesize()) {
return true;
}
return false;
}
public interface PushCallBack{
public void downloadSucceed();
public void downloadFailed();
public void downloadUpdate();
}
}
| false | true | public void run() {
InputStream is = null;
RandomAccessFile randomAccessFile = null;
try {
int startPos = downinfo.getCompletesize()*1024;
int endPos = downinfo.getFilesize()*1024;
is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos);
boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl());
randomAccessFile = new RandomAccessFile(file, "rwd");
if(!isBreakPoint)
{
downinfo.setCompletesize(0);
startPos = 0;
}
// 从断点处 继续下载(初始为0)
randomAccessFile.seek(startPos);
if (is == null) {
return;
}
final int length = 1024;
byte[] b = new byte[length];
int len = -1;
int pool = 0;
boolean isover = false;
long startime = System.currentTimeMillis();
Log.e(TAG, "-----downinfo starttime--->1 " + startime);
int tempLen = startPos;
callback.downloadUpdate();
while ((len = is.read(b))!=-1) {
if (isPause) {
return;
}
randomAccessFile.write(b, 0, len);
pool += len;
if (pool >= 100 * 1024) { // 100kb写一次数据库
Log.e(TAG, "-----下载 未完成----" + len);
PushDownLoadDBHelper.getInstances().update(downinfo); //暂不支持断点下载
pool = 0;
callback.downloadUpdate();// 刷新一次
}
tempLen += len;
downinfo.setCompletesize(tempLen/1024);
if (pool != 0) {
//PushDownLoadDBHelper.getInstances().update(downinfo);/// 暂不支持断点下载
}
}
long endtime = System.currentTimeMillis();
Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime));
} catch (Exception e) {
//Log.i(TAG, "-------->e " + e);
e.printStackTrace();
} finally {
// end.countDown();
Log.e(TAG, "---over----");
if (downinfo.getCompletesize() >= downinfo.getFilesize()) {
Log.i(TAG, "----finsh----");
PushDownLoadDBHelper.getInstances().update(downinfo);
if(callback != null){
callback.downloadSucceed();
}
}else{
callback.downloadFailed();
}
callback.downloadUpdate();
map.remove(String.valueOf(downinfo.getId()));
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
}
}
}
}
| public void run() {
InputStream is = null;
RandomAccessFile randomAccessFile = null;
try {
int startPos = downinfo.getCompletesize()*1024;
int endPos = downinfo.getFilesize()*1024;
is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos);
boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl());
randomAccessFile = new RandomAccessFile(file, "rwd");
if(!isBreakPoint)
{
downinfo.setCompletesize(0);
startPos = 0;
}
// 从断点处 继续下载(初始为0)
randomAccessFile.seek(startPos);
if (is == null) {
return;
}
final int length = 1024;
byte[] b = new byte[length];
int len = -1;
int pool = 0;
boolean isover = false;
long startime = System.currentTimeMillis();
Log.e(TAG, "-----downinfo starttime--->1 " + startime);
int tempLen = startPos;
callback.downloadUpdate();
while ((len = is.read(b))!=-1) {
if (isPause) {
return;
}
randomAccessFile.write(b, 0, len);
pool += len;
if (pool >= 100 * 1024) { // 100kb写一次数据库
Log.e(TAG, "-----下载 未完成----" + len);
PushDownLoadDBHelper.getInstances().update(downinfo); //暂不支持断点下载
pool = 0;
callback.downloadUpdate();// 刷新一次
}
tempLen += len;
downinfo.setCompletesize(tempLen/1024);
if (pool != 0) {
//PushDownLoadDBHelper.getInstances().update(downinfo);/// 暂不支持断点下载
}
}
long endtime = System.currentTimeMillis();
Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime));
} catch (Exception e) {
//Log.i(TAG, "-------->e " + e);
e.printStackTrace();
} finally {
// end.countDown();
Log.e(TAG, "---over----");
PushDownLoadDBHelper.getInstances().update(downinfo);
if (downinfo.getCompletesize() >= downinfo.getFilesize()) {
Log.i(TAG, "----finsh----");
if(callback != null){
callback.downloadSucceed();
}
}else{
callback.downloadFailed();
}
callback.downloadUpdate();
map.remove(String.valueOf(downinfo.getId()));
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
}
}
}
}
|
diff --git a/src/main/java/in/mDev/MiracleM4n/mChatSuite/mChatAPI.java b/src/main/java/in/mDev/MiracleM4n/mChatSuite/mChatAPI.java
index 32744bb..bbf0f0c 100644
--- a/src/main/java/in/mDev/MiracleM4n/mChatSuite/mChatAPI.java
+++ b/src/main/java/in/mDev/MiracleM4n/mChatSuite/mChatAPI.java
@@ -1,481 +1,481 @@
package in.mDev.MiracleM4n.mChatSuite;
import com.herocraftonline.dev.heroes.classes.HeroClass;
import com.herocraftonline.dev.heroes.hero.Hero;
import com.herocraftonline.dev.heroes.util.Messaging;
import com.herocraftonline.dev.heroes.util.Properties;
import com.nijikokun.register.payment.Methods;
import in.mDev.MiracleM4n.mChannel.mChannel;
import org.bukkit.entity.Player;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
public class mChatAPI {
static mChatSuite plugin;
public mChatAPI(mChatSuite plugin) {
mChatAPI.plugin = plugin;
}
/*
* Format Stuff
*/
public String ParseMessage(String pName, String msg, String format) {
Player player = plugin.getServer().getPlayer(pName);
if (player == null)
return addColour(format);
String prefix = plugin.getInfoReader().getRawPrefix(player);
String suffix = plugin.getInfoReader().getRawSuffix(player);
String group = plugin.getInfoReader().getRawGroup(player);
String vI = plugin.varIndicator;
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Location
Integer locX = (int) player.getLocation().getX();
Integer locY = (int) player.getLocation().getY();
Integer locZ = (int) player.getLocation().getZ();
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = healthBar(player);
String health = String.valueOf(player.getHealth());
// World
String world = player.getWorld().getName();
// 1.8 Vars
String hungerLevel = String.valueOf(player.getFoodLevel());
String hungerBar = basicBar(player.getFoodLevel(), 20, 10);
String level = String.valueOf(player.getLevel());
String exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10);
String expBar = basicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10);
String tExp = String.valueOf(player.getTotalExperience());
String gMode = "";
if (player.getGameMode() != null && player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat);
String time = dateFormat.format(now);
// mChannel Vars
String mCName = "";
String mCPref = "";
String mCSuf = "";
String mCType = "";
// Money Var/s
String money = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hExp = "";
String hEBar = "";
// Initialize mChannel Vars
if (plugin.mChanB) {
if (mChannel.API.getPlayersChannels(player)[0] != null)
mCName = mChannel.API.getPlayersChannels(player)[0];
mCPref = mChannel.API.getChannelPrefix(mCName);
mCSuf = mChannel.API.getChannelSuffix(mCName);
mCType = mChannel.API.getChannelType(mCName);
}
// Initialize Money Var/s
if (plugin.regB)
money = "$" + Methods.getMethod().getAccount(pName).balance();
// Initialize Heroes Vars
if (plugin.heroesB) {
Hero hero = plugin.heroes.getHeroManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = Properties.getLevel(hero.getExperience());
double hE = Properties.getExperience(hL);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar((float) hero.getHealth(), (float) hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hMBar = Messaging.createManaBar(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null)
hSClass = heroSClass.getName();
if ((hero.isMaster(heroClass))
&& (heroSClass == null || hero.isMaster(heroSClass)))
hMastered = plugin.hMasterT;
else
hMastered = plugin.hMasterF;
}
String formatAll = parseVars(format, player);
String[] search;
String[] replace;
msg = msg.replaceAll("%", "%%");
formatAll = formatAll.replaceAll("%", "%%");
if (formatAll == null)
return msg;
if (!checkPermissions(player, "mchat.coloredchat", false))
msg = removeColour(msg);
if (!checkPermissions(player, "mchat.censorbypass", false))
msg = replaceCensoredWords(msg);
search = new String[]{
vI + "mnameformat," + vI + "mnf",
vI + "displayname," + vI + "dname," + vI + "dn",
vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb",
vI + "experience," + vI + "exp",
vI + "gamemode," + vI + "gm",
vI + "group," + vI + "g",
vI + "hungerbar," + vI + "hub",
vI + "hunger",
vI + "healthbar," + vI + "hb",
vI + "health," + vI + "h",
vI + "location," + vI + "loc",
vI + "level," + vI + "l",
vI + "money," + vI + "mon",
vI + "mname," + vI + "mn",
vI + "name," + vI + "n",
vI + "prefix," + vI + "p",
vI + "suffix," + vI + "s",
vI + "totalexp," + vI + "texp," + vI + "te",
vI + "time," + vI + "t",
vI + "world," + vI + "w",
vI + "Cname," + vI + "Cn",
vI + "Cprefix," + vI + "Cp",
vI + "Csuffix," + vI + "Cs",
vI + "Ctype," + vI + "Ct",
vI + "Groupname," + vI + "Gname," + vI + "G",
vI + "HSecClass," + vI + "HSC",
vI + "HClass," + vI + "HC",
vI + "HExp," + vI + "HEx",
vI + "HEBar," + vI + "HEb",
vI + "HHBar," + vI + "HHB",
vI + "HHealth," + vI + "HH",
vI + "HLevel," + vI + "HL",
vI + "HMastered," + vI + "HMa",
vI + "HMana," + vI + "HMn",
vI + "HMBar," + vI + "HMb",
vI + "HParty," + vI + "HPa",
vI + "Worldname," + vI + "Wname," + vI + "W",
vI + "message," + vI + "msg," + vI + "m"
};
replace = new String[]{
plugin.nameFormat,
player.getDisplayName(),
expBar,
exp,
gMode,
group,
hungerBar,
hungerLevel,
healthbar,
health,
loc,
level,
money,
plugin.getInfoReader().getmName(player),
player.getName(),
prefix,
suffix,
tExp,
time,
world,
mCName,
mCPref,
mCSuf,
mCType,
plugin.getInfoReader().getGroupName(group),
hSClass,
hClass,
hExp,
hEBar,
hHBar,
hHealth,
hLevel,
hMastered,
hMana,
hMBar,
hParty,
plugin.getInfoReader().getWorldName(world),
msg
};
- formatAll = replaceCustVars(format);
+ formatAll = replaceCustVars(formatAll);
return replaceVars(formatAll, search, replace);
}
public String ParseChatMessage(Player player, String msg) {
return ParseMessage(player.getName(), msg, plugin.chatFormat);
}
public String ParsePlayerName(Player player) {
return ParseMessage(player.getName(), "", plugin.nameFormat);
}
public String ParseEventName(Player player) {
return ParseMessage(player.getName(), "", plugin.eventFormat);
}
public String ParseTabbedList(Player player) {
return ParseMessage(player.getName(), "", plugin.tabbedListFormat).replaceAll("(§([a-z0-9]))", "");
}
public String ParseListCmd(Player player) {
return ParseMessage(player.getName(), "", plugin.listCmdFormat);
}
public String ParseMe(Player player, String msg) {
return ParseMessage(player.getName(), msg, plugin.meFormat);
}
public String ParseChatMessage(String pName, String msg) {
return ParseMessage(pName, msg, plugin.chatFormat);
}
public String ParsePlayerName(String pName) {
return ParseMessage(pName, "", plugin.nameFormat);
}
public String ParseEventName(String pName) {
if (plugin.getServer().getPlayer(pName) == null)
return pName;
return ParseMessage(pName, "", plugin.eventFormat);
}
public String ParseTabbedList(String pName) {
return ParseMessage(pName, "", plugin.tabbedListFormat).replaceAll("(§([a-z0-9]))", "");
}
public String ParseListCmd(String pName) {
return ParseMessage(pName, "", plugin.listCmdFormat);
}
public String ParseMe(String pName, String msg) {
return ParseMessage(pName, msg, plugin.meFormat);
}
/*
* Misc Stuff
*/
public void addVar(String var, String value) {
if (var == null)
return;
if (value == null)
value = "";
plugin.cVarMap.put(var, value);
}
public String healthBar(Player player) {
float maxHealth = 20;
float barLength = 10;
float health = player.getHealth();
return basicBar(health, maxHealth, barLength);
}
public String basicBar(float currentValue, float maxValue, float barLength) {
int fill = Math.round((currentValue / maxValue) * barLength);
String barColor = (fill <= (barLength / 4)) ? "&4" : (fill <= (barLength / 7)) ? "&e" : "&2";
StringBuilder out = new StringBuilder();
out.append(barColor);
for (int i = 0; i < barLength; i++) {
if (i == fill)
out.append("&8");
out.append("|");
}
out.append("&f");
return out.toString();
}
public String addColour(String string) {
string = string.replace("`e", "")
.replace("`r", "\u00A7c").replace("`R", "\u00A74")
.replace("`y", "\u00A7e").replace("`Y", "\u00A76")
.replace("`g", "\u00A7a").replace("`G", "\u00A72")
.replace("`a", "\u00A7b").replace("`A", "\u00A73")
.replace("`b", "\u00A79").replace("`B", "\u00A71")
.replace("`p", "\u00A7d").replace("`P", "\u00A75")
.replace("`k", "\u00A70").replace("`s", "\u00A77")
.replace("`S", "\u00A78").replace("`w", "\u00A7f");
string = string.replace("<r>", "")
.replace("<black>", "\u00A70").replace("<navy>", "\u00A71")
.replace("<green>", "\u00A72").replace("<teal>", "\u00A73")
.replace("<red>", "\u00A74").replace("<purple>", "\u00A75")
.replace("<gold>", "\u00A76").replace("<silver>", "\u00A77")
.replace("<gray>", "\u00A78").replace("<blue>", "\u00A79")
.replace("<lime>", "\u00A7a").replace("<aqua>", "\u00A7b")
.replace("<rose>", "\u00A7c").replace("<pink>", "\u00A7d")
.replace("<yellow>", "\u00A7e").replace("<white>", "\u00A7f");
string = string.replaceAll("(§([a-fA-F0-9]))", "\u00A7$2");
string = string.replaceAll("(&([a-fA-F0-9]))", "\u00A7$2");
return string.replace("&&", "&");
}
public String removeColour(String string) {
addColour(string);
string = string.replaceAll("(§([a-fA-F0-9]))", "& $2");
string = string.replaceAll("(&([a-fA-F0-9]))", "& $2");
return string.replace("&&", "&");
}
public Boolean checkPermissions(Player player, String node) {
if (plugin.gmPermissionsB)
if (plugin.gmPermissionsWH.getWorldPermissions(player).has(player, node))
return true;
if (plugin.PEXB)
if (plugin.pexPermissions.has(player, node))
return true;
return player.hasPermission(node) || player.isOp();
}
public Boolean checkPermissions(Player player, String node, Boolean useOp) {
if (plugin.gmPermissionsB)
if (plugin.gmPermissionsWH.getWorldPermissions(player).has(player, node))
return true;
if (plugin.PEXB)
if (plugin.pexPermissions.has(player, node))
return true;
if (useOp)
if (player.isOp())
return true;
return player.hasPermission(node);
}
String parseVars(String format, Player player) {
String vI = "\\" + plugin.varIndicator;
Pattern pattern = Pattern.compile(vI + "<(.*?)>");
Matcher matcher = pattern.matcher(format);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String var = plugin.getInfoReader().getRawInfo(player, matcher.group(1));
matcher.appendReplacement(sb, Matcher.quoteReplacement(var));
}
matcher.appendTail(sb);
return sb.toString();
}
String replaceVars(String format, String[] search, String[] replace) {
if (search.length != replace.length)
return format;
for (int i = 0; i < search.length; i++) {
if (search[i].contains(","))
for (String s : search[i].split(",")) {
if (s == null || replace[i] == null)
continue;
format = format.replace(s, replace[i]);
}
else
format = format.replace(search[i], replace[i]);
}
return addColour(format);
}
String replaceCustVars(String format) {
for (Entry<String, String> entry : plugin.cVarMap.entrySet())
if (format.contains(plugin.cusVarIndicator + entry.getKey()))
format = format.replace(plugin.cusVarIndicator + entry.getKey(), entry.getValue());
return format;
}
String replaceCensoredWords(String msg) {
for (Entry<String, Object> entry : plugin.mCConfig.getValues(false).entrySet()) {
Pattern pattern = Pattern.compile("(?i)" + entry.getKey());
Matcher matcher = pattern.matcher(msg);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String var = entry.getValue().toString();
matcher.appendReplacement(sb, Matcher.quoteReplacement(var));
}
matcher.appendTail(sb);
msg = sb.toString();
}
return msg;
}
public void log(Object loggedObject) {
try {
plugin.getServer().getConsoleSender().sendMessage(loggedObject.toString());
} catch (IncompatibleClassChangeError ignored) {
System.out.println(loggedObject);
}
}
}
| true | true | public String ParseMessage(String pName, String msg, String format) {
Player player = plugin.getServer().getPlayer(pName);
if (player == null)
return addColour(format);
String prefix = plugin.getInfoReader().getRawPrefix(player);
String suffix = plugin.getInfoReader().getRawSuffix(player);
String group = plugin.getInfoReader().getRawGroup(player);
String vI = plugin.varIndicator;
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Location
Integer locX = (int) player.getLocation().getX();
Integer locY = (int) player.getLocation().getY();
Integer locZ = (int) player.getLocation().getZ();
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = healthBar(player);
String health = String.valueOf(player.getHealth());
// World
String world = player.getWorld().getName();
// 1.8 Vars
String hungerLevel = String.valueOf(player.getFoodLevel());
String hungerBar = basicBar(player.getFoodLevel(), 20, 10);
String level = String.valueOf(player.getLevel());
String exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10);
String expBar = basicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10);
String tExp = String.valueOf(player.getTotalExperience());
String gMode = "";
if (player.getGameMode() != null && player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat);
String time = dateFormat.format(now);
// mChannel Vars
String mCName = "";
String mCPref = "";
String mCSuf = "";
String mCType = "";
// Money Var/s
String money = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hExp = "";
String hEBar = "";
// Initialize mChannel Vars
if (plugin.mChanB) {
if (mChannel.API.getPlayersChannels(player)[0] != null)
mCName = mChannel.API.getPlayersChannels(player)[0];
mCPref = mChannel.API.getChannelPrefix(mCName);
mCSuf = mChannel.API.getChannelSuffix(mCName);
mCType = mChannel.API.getChannelType(mCName);
}
// Initialize Money Var/s
if (plugin.regB)
money = "$" + Methods.getMethod().getAccount(pName).balance();
// Initialize Heroes Vars
if (plugin.heroesB) {
Hero hero = plugin.heroes.getHeroManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = Properties.getLevel(hero.getExperience());
double hE = Properties.getExperience(hL);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar((float) hero.getHealth(), (float) hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hMBar = Messaging.createManaBar(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null)
hSClass = heroSClass.getName();
if ((hero.isMaster(heroClass))
&& (heroSClass == null || hero.isMaster(heroSClass)))
hMastered = plugin.hMasterT;
else
hMastered = plugin.hMasterF;
}
String formatAll = parseVars(format, player);
String[] search;
String[] replace;
msg = msg.replaceAll("%", "%%");
formatAll = formatAll.replaceAll("%", "%%");
if (formatAll == null)
return msg;
if (!checkPermissions(player, "mchat.coloredchat", false))
msg = removeColour(msg);
if (!checkPermissions(player, "mchat.censorbypass", false))
msg = replaceCensoredWords(msg);
search = new String[]{
vI + "mnameformat," + vI + "mnf",
vI + "displayname," + vI + "dname," + vI + "dn",
vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb",
vI + "experience," + vI + "exp",
vI + "gamemode," + vI + "gm",
vI + "group," + vI + "g",
vI + "hungerbar," + vI + "hub",
vI + "hunger",
vI + "healthbar," + vI + "hb",
vI + "health," + vI + "h",
vI + "location," + vI + "loc",
vI + "level," + vI + "l",
vI + "money," + vI + "mon",
vI + "mname," + vI + "mn",
vI + "name," + vI + "n",
vI + "prefix," + vI + "p",
vI + "suffix," + vI + "s",
vI + "totalexp," + vI + "texp," + vI + "te",
vI + "time," + vI + "t",
vI + "world," + vI + "w",
vI + "Cname," + vI + "Cn",
vI + "Cprefix," + vI + "Cp",
vI + "Csuffix," + vI + "Cs",
vI + "Ctype," + vI + "Ct",
vI + "Groupname," + vI + "Gname," + vI + "G",
vI + "HSecClass," + vI + "HSC",
vI + "HClass," + vI + "HC",
vI + "HExp," + vI + "HEx",
vI + "HEBar," + vI + "HEb",
vI + "HHBar," + vI + "HHB",
vI + "HHealth," + vI + "HH",
vI + "HLevel," + vI + "HL",
vI + "HMastered," + vI + "HMa",
vI + "HMana," + vI + "HMn",
vI + "HMBar," + vI + "HMb",
vI + "HParty," + vI + "HPa",
vI + "Worldname," + vI + "Wname," + vI + "W",
vI + "message," + vI + "msg," + vI + "m"
};
replace = new String[]{
plugin.nameFormat,
player.getDisplayName(),
expBar,
exp,
gMode,
group,
hungerBar,
hungerLevel,
healthbar,
health,
loc,
level,
money,
plugin.getInfoReader().getmName(player),
player.getName(),
prefix,
suffix,
tExp,
time,
world,
mCName,
mCPref,
mCSuf,
mCType,
plugin.getInfoReader().getGroupName(group),
hSClass,
hClass,
hExp,
hEBar,
hHBar,
hHealth,
hLevel,
hMastered,
hMana,
hMBar,
hParty,
plugin.getInfoReader().getWorldName(world),
msg
};
formatAll = replaceCustVars(format);
return replaceVars(formatAll, search, replace);
}
| public String ParseMessage(String pName, String msg, String format) {
Player player = plugin.getServer().getPlayer(pName);
if (player == null)
return addColour(format);
String prefix = plugin.getInfoReader().getRawPrefix(player);
String suffix = plugin.getInfoReader().getRawSuffix(player);
String group = plugin.getInfoReader().getRawGroup(player);
String vI = plugin.varIndicator;
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Location
Integer locX = (int) player.getLocation().getX();
Integer locY = (int) player.getLocation().getY();
Integer locZ = (int) player.getLocation().getZ();
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = healthBar(player);
String health = String.valueOf(player.getHealth());
// World
String world = player.getWorld().getName();
// 1.8 Vars
String hungerLevel = String.valueOf(player.getFoodLevel());
String hungerBar = basicBar(player.getFoodLevel(), 20, 10);
String level = String.valueOf(player.getLevel());
String exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10);
String expBar = basicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10);
String tExp = String.valueOf(player.getTotalExperience());
String gMode = "";
if (player.getGameMode() != null && player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat);
String time = dateFormat.format(now);
// mChannel Vars
String mCName = "";
String mCPref = "";
String mCSuf = "";
String mCType = "";
// Money Var/s
String money = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hExp = "";
String hEBar = "";
// Initialize mChannel Vars
if (plugin.mChanB) {
if (mChannel.API.getPlayersChannels(player)[0] != null)
mCName = mChannel.API.getPlayersChannels(player)[0];
mCPref = mChannel.API.getChannelPrefix(mCName);
mCSuf = mChannel.API.getChannelSuffix(mCName);
mCType = mChannel.API.getChannelType(mCName);
}
// Initialize Money Var/s
if (plugin.regB)
money = "$" + Methods.getMethod().getAccount(pName).balance();
// Initialize Heroes Vars
if (plugin.heroesB) {
Hero hero = plugin.heroes.getHeroManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = Properties.getLevel(hero.getExperience());
double hE = Properties.getExperience(hL);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar((float) hero.getHealth(), (float) hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hMBar = Messaging.createManaBar(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null)
hSClass = heroSClass.getName();
if ((hero.isMaster(heroClass))
&& (heroSClass == null || hero.isMaster(heroSClass)))
hMastered = plugin.hMasterT;
else
hMastered = plugin.hMasterF;
}
String formatAll = parseVars(format, player);
String[] search;
String[] replace;
msg = msg.replaceAll("%", "%%");
formatAll = formatAll.replaceAll("%", "%%");
if (formatAll == null)
return msg;
if (!checkPermissions(player, "mchat.coloredchat", false))
msg = removeColour(msg);
if (!checkPermissions(player, "mchat.censorbypass", false))
msg = replaceCensoredWords(msg);
search = new String[]{
vI + "mnameformat," + vI + "mnf",
vI + "displayname," + vI + "dname," + vI + "dn",
vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb",
vI + "experience," + vI + "exp",
vI + "gamemode," + vI + "gm",
vI + "group," + vI + "g",
vI + "hungerbar," + vI + "hub",
vI + "hunger",
vI + "healthbar," + vI + "hb",
vI + "health," + vI + "h",
vI + "location," + vI + "loc",
vI + "level," + vI + "l",
vI + "money," + vI + "mon",
vI + "mname," + vI + "mn",
vI + "name," + vI + "n",
vI + "prefix," + vI + "p",
vI + "suffix," + vI + "s",
vI + "totalexp," + vI + "texp," + vI + "te",
vI + "time," + vI + "t",
vI + "world," + vI + "w",
vI + "Cname," + vI + "Cn",
vI + "Cprefix," + vI + "Cp",
vI + "Csuffix," + vI + "Cs",
vI + "Ctype," + vI + "Ct",
vI + "Groupname," + vI + "Gname," + vI + "G",
vI + "HSecClass," + vI + "HSC",
vI + "HClass," + vI + "HC",
vI + "HExp," + vI + "HEx",
vI + "HEBar," + vI + "HEb",
vI + "HHBar," + vI + "HHB",
vI + "HHealth," + vI + "HH",
vI + "HLevel," + vI + "HL",
vI + "HMastered," + vI + "HMa",
vI + "HMana," + vI + "HMn",
vI + "HMBar," + vI + "HMb",
vI + "HParty," + vI + "HPa",
vI + "Worldname," + vI + "Wname," + vI + "W",
vI + "message," + vI + "msg," + vI + "m"
};
replace = new String[]{
plugin.nameFormat,
player.getDisplayName(),
expBar,
exp,
gMode,
group,
hungerBar,
hungerLevel,
healthbar,
health,
loc,
level,
money,
plugin.getInfoReader().getmName(player),
player.getName(),
prefix,
suffix,
tExp,
time,
world,
mCName,
mCPref,
mCSuf,
mCType,
plugin.getInfoReader().getGroupName(group),
hSClass,
hClass,
hExp,
hEBar,
hHBar,
hHealth,
hLevel,
hMastered,
hMana,
hMBar,
hParty,
plugin.getInfoReader().getWorldName(world),
msg
};
formatAll = replaceCustVars(formatAll);
return replaceVars(formatAll, search, replace);
}
|
diff --git a/src/uk/me/graphe/client/DrawingImpl.java b/src/uk/me/graphe/client/DrawingImpl.java
index 4ffa337..e1684d6 100644
--- a/src/uk/me/graphe/client/DrawingImpl.java
+++ b/src/uk/me/graphe/client/DrawingImpl.java
@@ -1,1041 +1,1041 @@
package uk.me.graphe.client;
import java.util.ArrayList;
import java.util.Collection;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.widgetideas.graphics.client.Color;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
import com.googlecode.gwtgl.array.Float32Array;
import com.googlecode.gwtgl.array.Uint16Array;
import com.googlecode.gwtgl.binding.WebGLBuffer;
import com.googlecode.gwtgl.binding.WebGLCanvas;
import com.googlecode.gwtgl.binding.WebGLProgram;
import com.googlecode.gwtgl.binding.WebGLRenderingContext;
import com.googlecode.gwtgl.binding.WebGLShader;
import com.googlecode.gwtgl.binding.WebGLUniformLocation;
import uk.me.graphe.client.webglUtil.math.FloatMatrix4x4;
import uk.me.graphe.client.webglUtil.math.MatrixUtil;
public class DrawingImpl implements Drawing {
// The level of zoom at which the edges begin to get thinner
public static final double EDGE_ZOOM_LIMIT = 0.61;
private WebGLRenderingContext mGlContext;
private WebGLProgram mShaderProgram;
private int mVertexPositionAttribute;
private WebGLBuffer mVertexBuffer;
private int mVertexColorAttribute;
private FloatMatrix4x4 mProjectionMatrix;
private WebGLBuffer mIndexBuffer;
private WebGLBuffer mColorBuffer;
private WebGLUniformLocation mProjectionMatrixUniform;
private boolean mRenderRequest;
private ArrayList<Float> mVerticesList = new ArrayList<Float>();
private ArrayList<Integer> mIndicesList = new ArrayList<Integer>();
private ArrayList<Float> mColorsList = new ArrayList<Float>();
private Collection<EdgeDrawable> mEdgesToDraw;
private Collection<VertexDrawable> mVerticesToDraw;
private GWTCanvas m2dCanvas;
private int mNumVertices = 0;
private boolean mTimeOutSet = false;
private boolean mCanRender = true;
private long mCurrentTime = -1;
private long mOldTime = -1;
private int mFramesDone = 0;
private int mCanvasWidth = Window.getClientWidth();
private int mCanvasHeight = Window.getClientWidth(); // Deliberate
private boolean mWebglReady = false;
private DrawingPolygon mCurrentPolygon;
WebGLCanvas webGLCanvas;
// used for styles
private boolean mIsFlowChart;
// used for UI line
private double[] mUIline = { 0, 0, 0, 0 };
private boolean mShowUILine = false;
// used for panning
private int mOffsetX, mOffsetY;
private double mZoom;
// Edits the HTML to ensure 3d canvas is visible
private static native int setUpCanvas()
/*-{
canvas1 = document.getElementsByTagName("canvas")[0];
canvas1.style.position = "absolute";
}-*/;
// Does one time set up to make page ready for repeated rendering of graph
private void setUpWebGL() {
setUpCanvas();
webGLCanvas = new WebGLCanvas(mCanvasWidth + "px", mCanvasHeight + "px");
mGlContext = webGLCanvas.getGlContext();
RootPanel.get("gwtGL").add(webGLCanvas);
mGlContext.viewport(0, 0, mCanvasWidth, mCanvasHeight);
initShaders();
mGlContext.clearColor(1.0f, 1.0f, 1.0f, 1.0f);
mGlContext.clearDepth(1.0f);
mGlContext.enable(WebGLRenderingContext.DEPTH_TEST);
mGlContext.depthFunc(WebGLRenderingContext.LEQUAL);
initProjectionMatrix();
mWebglReady = true;
}
// set the coordinates of the UI line, and displays it
public void setUILine(double startX, double startY, double endX, double endY) {
mUIline[0] = startX;
mUIline[1] = startY;
mUIline[2] = endX;
mUIline[3] = endY;
mShowUILine = true;
}
// displays the UI line
public void showUIline() {
mShowUILine = true;
}
// hides the UI line
public void hideUIline() {
mShowUILine = false;
}
// check for WebGL
private static native int webglCheck()/*-{
if (typeof Float32Array != "undefined")return 1;
return 0;
}-*/;
private void doRendering() {
// Update frames drawn
mFramesDone++;
// Can not render while render is happening
mCanRender = false;
// Do a (kind of reliable) check for webgl
if (webglCheck() == 1) {
// Can do WebGL
mNumVertices = 0;
String label = "";
int vertexStyle;
int edgeStyle;
double edgeThickness = 6;
float[] highlightColour = DrawingConstants.YELLOW;
if(mZoom <= EDGE_ZOOM_LIMIT) edgeThickness = edgeThickness*mZoom;
// Clear coordinates from last render
mVerticesList.clear();
mIndicesList.clear();
mColorsList.clear();
// SetupWebGl if not done so already
if (!mWebglReady)
setUpWebGL();
// Loop through all edges and draw them
for (EdgeDrawable thisEdge : mEdgesToDraw) {
mCurrentPolygon = thisEdge.getPolygon();
// Apply offset and zoom factors
double startX = (thisEdge.getStartX() + mOffsetX) * mZoom;
double startY = (thisEdge.getStartY() + mOffsetY) * mZoom;
double endX = (thisEdge.getEndX() + mOffsetX) * mZoom;
double endY = (thisEdge.getEndY() + mOffsetY) * mZoom;
int weight = thisEdge.getWeight();
float[] edgeColour = DrawingConstants.BLACK;
float[] textColour = DrawingConstants.BLACK;
int strokeThickness = 4;
// edgeStyle = thisEdge.getStyle();
edgeStyle = 100;
// If edge is highlighted apply set it to negative
if (thisEdge.isHilighted()){
edgeStyle = -edgeStyle;
edgeColour = DrawingConstants.YELLOW;
}
// Add edge to lists to be rendered
if(thisEdge.needsToFromArrow()){
if (thisEdge.isHilighted()){
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
- addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", edgeColour, textColour);
+ addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", highlightColour, textColour);
}else{
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
} else if(thisEdge.needsToFromArrow()){
if (thisEdge.isHilighted()){
addEdge(endX, endY, startX, startY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
- addEdge(endX, endY, startX, startY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", edgeColour, textColour);
+ addEdge(endX, endY, startX, startY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", highlightColour, textColour);
}else{
addEdge(endX, endY, startX, startY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
} else {
if (thisEdge.isHilighted()){
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
- addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", edgeColour, textColour);
+ addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", highlightColour, textColour);
}else{
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
}
}
// Add UI line if required
if (mShowUILine) {
addEdge((mUIline[0]+ mOffsetX)*mZoom, (mUIline[1]+ mOffsetY)*mZoom,
(mUIline[2]+ mOffsetX)*mZoom, (mUIline[3]+ mOffsetY)*mZoom,
edgeThickness, true,false,edgeThickness*5,edgeThickness*5,"", DrawingConstants.GREY, DrawingConstants.BLACK);
}
for (VertexDrawable thisVertex : mVerticesToDraw) {
mNumVertices++;
double centreX = (thisVertex.getCenterX() + mOffsetX) * mZoom;
double centreY = (thisVertex.getCenterY() + mOffsetY) * mZoom;
double width = (thisVertex.getWidth()) * mZoom;
double height = (thisVertex.getHeight()) * mZoom;
label = thisVertex.getLabel();
vertexStyle = thisVertex.getStyle();
float[] customColor = { 0, 0, 0, 1};
switch (vertexStyle) {
case VertexDrawable.STROKED_TERM_STYLE:
if (thisVertex.isHilighted()) {
addTerm(centreX, centreY,width,height, DrawingConstants.YELLOW);
addTerm(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
} else {
addTerm(centreX, centreY,width,height, DrawingConstants.BLACK);
addTerm(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
}
addStringBox(centreX, centreY, width-height,height, label, DrawingConstants.BLACK);
break;
case VertexDrawable.STROKED_SQUARE_STYLE:
if (thisVertex.isHilighted()) {
addSquare(centreX, centreY,width,height, DrawingConstants.YELLOW);
addSquare(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
} else {
addSquare(centreX, centreY,width,height, DrawingConstants.BLACK);
addSquare(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
}
addStringBox(centreX, centreY, width,height, label, DrawingConstants.BLACK);
break;
case VertexDrawable.STROKED_DIAMOND_STYLE:
if (thisVertex.isHilighted()) {
addDiamondStroke(centreX, centreY, width,height,DrawingConstants.GREY,
2,DrawingConstants.YELLOW);
} else {
addDiamondStroke(centreX, centreY, width,height,DrawingConstants.GREY,
2,DrawingConstants.BLACK);
}
addStringCircle(centreX, centreY, width/2, label, DrawingConstants.BLACK);
break;
case VertexDrawable.COLORED_FILLED_CIRCLE:
customColor = thisVertex.getColor();
addCircle(centreX, centreY, width, customColor);
break;
default:
if (thisVertex.isHilighted()) {
addCircle(centreX, centreY, width, highlightColour);
- addCircle(centreX, centreY, width - 4, DrawingConstants.YELLOW);
+ addCircle(centreX, centreY, width - 4, highlightColour);
} else {
addCircle(centreX, centreY, width, DrawingConstants.BLACK);
}
break;
}
}
renderGraph();
mCanRender = true;
} else {
// Can't do webGL so draw on 2d Canvas
renderGraph2d(m2dCanvas, mEdgesToDraw, mVerticesToDraw);
}
}
private static native String getUrlJsni()
/*-{
canvas = document.getElementsByTagName("canvas")[0];
return canvas.toDataURL();
}-*/;
public String getUrl(){
String url = getUrlJsni();
return url;
}
public void renderGraph(GWTCanvas canvasNew, Collection<EdgeDrawable> edgesNew,
Collection<VertexDrawable> verticesNew) {
m2dCanvas = canvasNew;
mEdgesToDraw = edgesNew;
mVerticesToDraw = verticesNew;
mRenderRequest = true;
if (!mTimeOutSet) {
mTimeOutSet = true;
mOldTime = System.currentTimeMillis();
Timer t = new Timer() {
public void run() {
if (mCanRender && mRenderRequest) {
doRendering();
mCurrentTime = System.currentTimeMillis();
float fps =
1 /(((float)(System.currentTimeMillis()-mOldTime))/(float)1000);
fps = (float) (Math.round(((double) fps) * 100.0) / 100.0);
RootPanel.get("frameRate").clear();
VerticalPanel panel = new VerticalPanel();
HTML gLabel =
new HTML("TotalFrames:" + mFramesDone +
" Nodes:"+ mNumVertices +
" Zoom:"+ mZoom +
" FPS:" + fps);
gLabel.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT);
panel.add(gLabel);
RootPanel.get("frameRate").add(panel);
mOldTime = System.currentTimeMillis();
mRenderRequest = false;
}
}
};
t.scheduleRepeating(100 / 6);
}
}
private void initProjectionMatrix() {
mProjectionMatrix =
MatrixUtil.createPerspectiveMatrix(45, mCanvasWidth / mCanvasHeight, 0.1f, 100);
}
public void initShaders() {
WebGLShader fragmentShader =
getShader(WebGLRenderingContext.FRAGMENT_SHADER, DrawingShaders.INSTANCE
.fragmentShader().getText());
WebGLShader vertexShader =
getShader(WebGLRenderingContext.VERTEX_SHADER, DrawingShaders.INSTANCE
.vertexShader().getText());
mShaderProgram = mGlContext.createProgram();
mGlContext.attachShader(mShaderProgram, vertexShader);
mGlContext.attachShader(mShaderProgram, fragmentShader);
mGlContext.linkProgram(mShaderProgram);
if (!mGlContext.getProgramParameterb(mShaderProgram, WebGLRenderingContext.LINK_STATUS)) {
throw new RuntimeException("Could not initialise shaders");
}
mGlContext.useProgram(mShaderProgram);
mVertexPositionAttribute = mGlContext.getAttribLocation(mShaderProgram, "vertexPosition");
mVertexColorAttribute = mGlContext.getAttribLocation(mShaderProgram, "vertexColor");
mProjectionMatrixUniform =
mGlContext.getUniformLocation(mShaderProgram, "projectionMatrix");
}
private WebGLShader getShader(int type, String source) {
WebGLShader shader = mGlContext.createShader(type);
mGlContext.shaderSource(shader, source);
mGlContext.compileShader(shader);
if (!mGlContext.getShaderParameterb(shader, WebGLRenderingContext.COMPILE_STATUS)) {
throw new RuntimeException(mGlContext.getShaderInfoLog(shader));
}
return shader;
}
private int verticesIndex() {
if (mVerticesList.size() == 0)
return 0;
else
return mVerticesList.size() / 2;
}
private double stringPixelLength(String string)
{
int code;
double width = 0;
for(int i=0;i<string.length();i++)
{
code = string.codePointAt(i)-32;
width += DrawingConstants.HERSHEY_FONT[code][1];
}
return width;
}
private ArrayList<String> getLines(String string, double width, double size)
{
String[] wordArray = string.split(" ");
int numWords = wordArray.length;
ArrayList<String> lineList = new ArrayList<String>();
String[] lineArray = new String[100];
int lineNum = 1;
double lineWidth = 0;
int wordNum =0;
double spaceWidth = stringPixelLength(" ")*size;
lineArray[0]="0";
lineList.add("0");
lineArray[lineNum]="";
lineList.add("");
for(int i = 0;i<numWords;i++)
{
double charWidth = spaceWidth+stringPixelLength(wordArray[i])*size;
if(width<=lineWidth+charWidth && i>0)
{
if(lineNum < numWords)
{
lineNum++;
lineArray[lineNum] = "";
lineList.add("");
lineWidth = 0;
wordNum = 0;
}
}
if(wordNum > 0 && i>0)
{
wordArray[i] = " "+wordArray[i];
}
lineArray[lineNum] += wordArray[i];
lineList.set(lineNum, lineList.get(lineNum)+""+wordArray[i]);
lineWidth += charWidth;
wordNum++;
if(stringPixelLength(wordArray[i]) > stringPixelLength(wordArray[Integer.parseInt(lineArray[0])])) lineArray[0] = ""+i;
if(stringPixelLength(wordArray[i]) > stringPixelLength(wordArray[Integer.parseInt(lineList.get(0))])) lineList.set(0, ""+i);
}
return lineList;
}
private void addStringCircle(double left, double top, double width, String string, float[] color)
{
double rad = width;
double dis = Math.sin(Math.PI/4)*rad;
addStringBox(left,top,dis,dis, string, color);
}
private void addStringBox(double left, double top, double width, double height,String string, float[] color)
{
double sizeInc = 0.05;
double bufferX = 5;
double bufferY = 0;
width-=bufferX;
height-=bufferY;
boolean cont = true;
double orginLength = stringPixelLength(string);
double origSize = (width/orginLength);
double size = origSize;
double lineHeight = size*35;
ArrayList<String> lineList = getLines(string, width, size);
double hOff;
int count = 0;
String[] wordArray = string.split(" ");
double longestWidth = 0;
while(cont)
{
longestWidth = stringPixelLength(wordArray[Integer.parseInt(lineList.get(0))])*size;
double tempSize = size+sizeInc;
lineList = getLines(string, width, tempSize);
lineHeight = tempSize*35;
double vSpace = height-(lineHeight*(lineList.size()-1));
if(vSpace>lineHeight && width>longestWidth+10)
{
size=tempSize;
}
else if(vSpace < -10 || width<longestWidth )
{
size=size*0.5;
}
else
{
cont = false;
}
count++;
}
hOff = -((lineList.size()-2)*lineHeight)/2;
for(int i =1;i<lineList.size();i++)
{
addString(left,top+hOff,lineList.get(i),color,size);
hOff+=lineHeight;
}
}
private void addString(double left,double top,String string,float[] color, double size)
{
double offset = -((stringPixelLength(string)/2)*size);
for(int i=0;i<string.length();i++)
{
offset += addChar(left+offset,top,string.charAt(i)+"",color,size);
}
}
private double addChar(double left,double top,String character,float[] color, double size){
int code = character.codePointAt(0)-32;
int verticesNeeded = DrawingConstants.HERSHEY_FONT[code][0];
double width = DrawingConstants.HERSHEY_FONT[code][1];
double left1;
double top1;
double left2=0;
double top2=0;
int j = 0;
int i = 2;
double fHeight = 9*size;
double thickness = 1.5;
while(i<(verticesNeeded*2)+2)
{
j++;
left1 = DrawingConstants.HERSHEY_FONT[code][i]*size+left;
top1 = (fHeight-DrawingConstants.HERSHEY_FONT[code][i+1]*size)+top;
if(DrawingConstants.HERSHEY_FONT[code][i] != -1 && DrawingConstants.HERSHEY_FONT[code][i+1] != -1)
{
if(i>2 && DrawingConstants.HERSHEY_FONT[code][i-1] != -1 && DrawingConstants.HERSHEY_FONT[code][i-2] != -1)
{
addEdge(left2,top2,left1,top1,thickness,false,false,0,0,"",color, color);
}
if(DrawingConstants.HERSHEY_FONT[code][i+2] != -1 && DrawingConstants.HERSHEY_FONT[code][i+3] != -1)
{
left2 = DrawingConstants.HERSHEY_FONT[code][i+2]*size+left;
top2 = (fHeight-DrawingConstants.HERSHEY_FONT[code][i+3]*size)+top;
addEdge(left1,top1,left2,top2,thickness,false,false,0,0,"",color, color);
}
i+=4;
}
else
{
i+=2;
}
}
return width*size;
}
private void addTerm(double x, double y, double width, double height, float[] color){
double squareWidth = width-height;
addSquare(x,y, squareWidth, height,color);
addCircle(x-squareWidth/2,y,height,color);
addCircle(x+squareWidth/2,y,height,color);
}
private void addTriangle(double centreX, double centreY, double width, double height,
double angle, boolean addToPolygon,float[] color) {
int startIndex = verticesIndex();
double halfHeight = (height / 2);
double halfWidth = (width / 2);
double[][] coords =
{ { 0, halfHeight }, { -halfWidth, -halfHeight }, { halfWidth, -halfHeight } };
double oldX;
double oldY;
for (int i = 0; i < coords.length; i++) {
oldX = coords[i][0];
oldY = coords[i][1];
coords[i][0] = (oldX * Math.cos(angle)) - (oldY * Math.sin(angle));
coords[i][1] = (oldX * Math.sin(angle)) + (oldY * Math.cos(angle));
}
mVerticesList.add((float) (coords[0][0] + centreX)); // topLeftX
mVerticesList.add((float) (coords[0][1] + centreY));// topLeftY
mVerticesList.add((float) (coords[1][0] + centreX)); // bottomLeftX
mVerticesList.add((float) (coords[1][1] + centreY));// bottomLeftY
mVerticesList.add((float) (coords[2][0] + centreX)); // bottomRightX
mVerticesList.add((float) (coords[2][1] + centreY));// bottomRightY
mIndicesList.add(startIndex + 0);
mIndicesList.add(startIndex + 1);
mIndicesList.add(startIndex + 2);
Integer[] xArray = {(int) ((coords[0][0] + centreX)),
(int) ((coords[2][0] + centreX)),
(int) ((coords[1][0] + centreX))};
Integer[] yArray = {(int) ((coords[0][1] + centreY)),
(int) ((coords[2][1] + centreY)),
(int) ((coords[1][1] + centreY))};
if(addToPolygon)mCurrentPolygon.set(xArray, yArray,mZoom, mOffsetX,mOffsetY);
for (int i = 0; i < 3; i++) {
mColorsList.add(color[0]);
mColorsList.add(color[1]);
mColorsList.add(color[2]);
mColorsList.add(color[3]);
}
}
private void addCircle(double centreX, double centreY, double width, float[] color) {
float radius = (float) (width / 2);
float oldX;
float newX;
float newY;
float movedX;
float movedY;
int numSegments = (int) ((int) 4 * Math.sqrt((double) radius));
float theta = (float) (2 * 3.1415926 / numSegments);
float cosValue = (float) Math.cos(theta);
float sineValue = (float) Math.sin(theta);
newY = 0;
newX = (float) radius;
int startIndex;
int currentIndex;
int oldIndex = 0;
int circleStart = 0;
if (mVerticesList.size() == 0)
startIndex = 0;
else
startIndex = mVerticesList.size() / 2;
mVerticesList.add((float) centreX);
mVerticesList.add((float) centreY);
for (int i = 0; i < numSegments; i++) {
oldX = newX;
newX = (cosValue * newX) - (sineValue * newY);
newY = (sineValue * oldX) + (cosValue * newY);
movedX = (float) (newX + centreX);
movedY = (float) (newY + centreY);
if (mVerticesList.size() == 0)
currentIndex = 0;
else
currentIndex = mVerticesList.size() / 2;
mVerticesList.add(movedX);
mVerticesList.add(movedY);
if (i == numSegments - 1) {
mIndicesList.add(startIndex);
mIndicesList.add(currentIndex);
mIndicesList.add(currentIndex - 1);
mIndicesList.add(startIndex);
mIndicesList.add(currentIndex);
mIndicesList.add(circleStart);
} else if (oldIndex > 0) {
mIndicesList.add(startIndex);
mIndicesList.add(currentIndex);
mIndicesList.add(currentIndex - 1);
} else {
circleStart = currentIndex;
}
if (mVerticesList.size() == 0)
oldIndex = 0;
else
oldIndex = mVerticesList.size() / 2;
}
for (int i = 0; i < numSegments + 1; i++) {
mColorsList.add(color[0]);
mColorsList.add(color[1]);
mColorsList.add(color[2]);
mColorsList.add(color[3]);
}
}
double diamondStrokeAlgorithm(double width, double height, double strokeSize)
{
double angle1 = Math.atan(height/width);
double angle2 = Math.PI/2 - angle1;
double opp = strokeSize*Math.sin(angle2);
double width1Sq = (strokeSize*strokeSize)-(opp*opp);
double width1 = Math.sqrt(width1Sq);
double width2 = opp/(Math.tan(angle1));
double fWidth = (width1+width2)*2;
return fWidth;
}
private void addDiamondStroke(double x, double y, double width, double height, float[] color,
double strokeSize, float[] strokeColor){
double wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize);
double hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize);
addDiamond(x,y,width,height,strokeColor);
addDiamond(x,y,width-wOff,height-hOff,color);
}
private void addDiamond(double x, double y, double width, double height, float[] color){
float halfWidth = (float) (width/2);
float halfHeight = (float) (height/2);
int startIndex = verticesIndex();
mVerticesList.add((float) x-halfWidth);
mVerticesList.add((float) y);
mVerticesList.add((float) x);
mVerticesList.add((float) y-halfHeight);
mVerticesList.add((float) x+halfWidth);
mVerticesList.add((float) y);
mVerticesList.add((float) x);
mVerticesList.add((float) y+halfHeight);
mIndicesList.add(startIndex + 0);
mIndicesList.add(startIndex + 1);
mIndicesList.add(startIndex + 2);
mIndicesList.add(startIndex + 0);
mIndicesList.add(startIndex + 2);
mIndicesList.add(startIndex + 3);
for (int i = 0; i < 4; i++) {
mColorsList.add(color[0]);
mColorsList.add(color[1]);
mColorsList.add(color[2]);
mColorsList.add(color[3]);
}
}
private void addEdge(double x1, double y1, double x2, double y2, double thickness,
boolean arrow, boolean addToPolygon,double arrowThickness,double arrowHeight,String label, float[] color, float[] textColor) {
double height = y2 - y1;
double width = x2 - x1;
double length = Math.sqrt((height * height) + (width * width));
double halfThick = thickness / 2;
double halfLength = length / 2;
double xOffset = x1 + (width / 2);
double yOffset = y1 + (height / 2);
double oldX;
double oldY;
double lineAngle = Math.atan(height / width);
double arrowAngle = lineAngle;
double[][] coords =
{ { -halfLength, halfThick },
{ halfLength, halfThick },
{ -halfLength, -halfThick },
{ halfLength, -halfThick } };
for (int i = 0; i < coords.length; i++) {
oldX = coords[i][0];
oldY = coords[i][1];
coords[i][0] = (oldX * Math.cos(lineAngle)) - (oldY * Math.sin(lineAngle));
coords[i][1] = (oldX * Math.sin(lineAngle)) + (oldY * Math.cos(lineAngle));
}
addSquare(coords[0][0] + xOffset, coords[0][1] + yOffset,
coords[1][0] + xOffset, coords[1][1] + yOffset,
coords[2][0] + xOffset, coords[2][1] + yOffset,
coords[3][0] + xOffset, coords[3][1] + yOffset, color);
Integer[] xArray = {(int) ((coords[0][0] + xOffset)),
(int) ((coords[2][0] + xOffset)),
(int) ((coords[3][0] + xOffset)),
(int) ((coords[1][0] + xOffset))};
Integer[] yArray = {(int) ((coords[0][1] + yOffset)),
(int) ((coords[2][1] + yOffset)),
(int) ((coords[3][1] + yOffset)),
(int) ((coords[1][1] + yOffset))
};
if(addToPolygon){
mCurrentPolygon.clear();
mCurrentPolygon.set(xArray, yArray,mZoom, mOffsetX,mOffsetY);
}
if (arrow) {
if (x1 > x2)
arrowAngle -= Math.PI;
addTriangle(xOffset, yOffset, arrowThickness, arrowHeight, arrowAngle - Math.PI / 2, addToPolygon,color);
}
if(!label.equals("")){
double lX;
double lY;
double nlX;
double nlY;
double lLength;
double halfLLength;
lLength = stringPixelLength(label);
halfLLength = lLength/2;
double dLine = thickness*2;
lX = 0;
lY = -dLine;
nlX = (lX * Math.cos(lineAngle)) - (lY * Math.sin(lineAngle))+xOffset;
nlY = (lX * Math.sin(lineAngle)) + (lY * Math.cos(lineAngle))+yOffset;
if(x2>=x1 && y1<y2)nlX+=halfLLength*0.7;
else if(x2<x1 && y1<y2)nlX-=halfLLength*0.7;
else if(x2<x1 && y1>y2)nlX+=halfLLength*0.7;
else if(x2>=x1 && y1>y2)nlX-=halfLLength*0.7;
addString(nlX, nlY-(thickness*1.6),label,textColor,thickness*0.1);
}
}
private void addSquare(double x, double y, double width, double height, float[] color) {
float halfWidth = (float) (width / 2);
float halfHeight = (float) (height / 2);
addSquare(x - halfWidth, y - halfHeight, x + halfWidth, y - halfHeight, x - halfWidth, y
+ halfHeight, x + halfWidth, y + halfHeight, color);
}
private void addSquare(double topLeftX, double topLeftY, double topRightX, double topRightY,
double bottomLeftX, double bottomLeftY, double bottomRightX, double bottomRightY,
float[] color) {
int startIndex = verticesIndex();
mVerticesList.add((float) topLeftX);
mVerticesList.add((float) topLeftY);
mVerticesList.add((float) bottomLeftX);
mVerticesList.add((float) bottomLeftY);
mVerticesList.add((float) topRightX);
mVerticesList.add((float) topRightY);
mVerticesList.add((float) bottomRightX);
mVerticesList.add((float) bottomRightY);
mIndicesList.add(startIndex + 0);
mIndicesList.add(startIndex + 1);
mIndicesList.add(startIndex + 2);
mIndicesList.add(startIndex + 1);
mIndicesList.add(startIndex + 2);
mIndicesList.add(startIndex + 3);
for (int i = 0; i < 4; i++) {
mColorsList.add(color[0]);
mColorsList.add(color[1]);
mColorsList.add(color[2]);
mColorsList.add(color[3]);
}
}
private void renderGraph() {
int vl = 0;
float factor;
float glWidth = 5f;
float unit = 5f;
float[] colors = new float[mColorsList.size()];
for (int i = 0; i < colors.length; i++) {
colors[i] = mColorsList.get(i);
}
int[] indices = new int[mIndicesList.size()];
for (int i = 0; i < mIndicesList.size(); i++) {
Integer f = mIndicesList.get(i);
indices[i] = f;
}
if (mCanvasWidth >= mCanvasHeight)
factor = glWidth / mCanvasHeight;
else
factor = glWidth / mCanvasWidth;
factor = factor * 2;
float[] vertices2 = new float[(mVerticesList.size() / 2) + mVerticesList.size()];
for (int i = 0; i < mVerticesList.size(); i++) {
float current = (mVerticesList.get(i)) * factor;
if (i % 2 != 0) {
vertices2[vl] = -current + unit;
vl++;
vertices2[vl] = (-5.0f);
} else {
vertices2[vl] = (current) - unit;
}
vl++;
}
mGlContext.clear(WebGLRenderingContext.COLOR_BUFFER_BIT
| WebGLRenderingContext.DEPTH_BUFFER_BIT);
mVertexBuffer = mGlContext.createBuffer();
mGlContext.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, mVertexBuffer);
mGlContext.bufferData(WebGLRenderingContext.ARRAY_BUFFER, Float32Array.create(vertices2),
WebGLRenderingContext.STATIC_DRAW);
// create the colorBuffer
mColorBuffer = mGlContext.createBuffer();
mGlContext.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, mColorBuffer);
mGlContext.bufferData(WebGLRenderingContext.ARRAY_BUFFER, Float32Array.create(colors),
WebGLRenderingContext.STATIC_DRAW);
// create the indexBuffer
mIndexBuffer = mGlContext.createBuffer();
mGlContext.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, mIndexBuffer);
mGlContext.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER,
Uint16Array.create(indices), WebGLRenderingContext.STATIC_DRAW);
mGlContext.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, mVertexBuffer);
mGlContext.vertexAttribPointer(mVertexPositionAttribute, 3, WebGLRenderingContext.FLOAT,
false, 0, 0);
mGlContext.enableVertexAttribArray(mVertexPositionAttribute);
mGlContext.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, mColorBuffer);
mGlContext.vertexAttribPointer(mVertexColorAttribute, 4, WebGLRenderingContext.FLOAT,
false, 0, 0);
mGlContext.enableVertexAttribArray(mVertexColorAttribute);
mGlContext.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, mIndexBuffer);
// Bind the projection matrix to the shader
mGlContext.uniformMatrix4fv(mProjectionMatrixUniform, false,
mProjectionMatrix.getColumnWiseFlatData());
// Draw the polygon
mGlContext.drawElements(WebGLRenderingContext.TRIANGLES, indices.length,
WebGLRenderingContext.UNSIGNED_SHORT, 0);
mGlContext.flush();
}
private float[] createPerspectiveMatrix(int fieldOfViewVertical, float aspectRatio,
float minimumClearance, float maximumClearance) {
float top = minimumClearance * (float) Math.tan(fieldOfViewVertical * Math.PI / 360.0);
float bottom = -top;
float left = bottom * aspectRatio;
float right = top * aspectRatio;
float X = 2 * minimumClearance / (right - left);
float Y = 2 * minimumClearance / (top - bottom);
float A = (right + left) / (right - left);
float B = (top + bottom) / (top - bottom);
float C = -(maximumClearance + minimumClearance) / (maximumClearance - minimumClearance);
float D = -2 * maximumClearance * minimumClearance / (maximumClearance - minimumClearance);
return new float[] { X,
0.0f,
A,
0.0f,
0.0f,
Y,
B,
0.0f,
0.0f,
0.0f,
C,
-1.0f,
0.0f,
0.0f,
D,
0.0f };
};
// old 2d canvas functions
public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
canvas.setLineWidth(1);
canvas.setStrokeStyle(Color.BLACK);
canvas.setFillStyle(Color.BLACK);
canvas.setFillStyle(Color.WHITE);
canvas.fillRect(0, 0, 2000, 2000);
canvas.setFillStyle(Color.BLACK);
drawGraph(edges, vertices, canvas);
}
// Draws a single vertex, currently only draws circular nodes
private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) {
double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + mOffsetX) * mZoom;
double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + mOffsetY) * mZoom;
double radius = (0.25 * vertex.getWidth()) * mZoom;
canvas.moveTo(centreX, centreY);
canvas.beginPath();
canvas.arc(centreX, centreY, radius, 0, 360, false);
canvas.closePath();
canvas.stroke();
canvas.fill();
}
// Draws a line from coordinates to other coordinates
private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) {
double startX = (edge.getStartX() + mOffsetX) * mZoom;
double startY = (edge.getStartY() + mOffsetY) * mZoom;
double endX = (edge.getEndX() + mOffsetX) * mZoom;
double endY = (edge.getEndY() + mOffsetY) * mZoom;
canvas.beginPath();
canvas.moveTo(startX, startY);
canvas.lineTo(endX, endY);
canvas.closePath();
canvas.stroke();
}
// Takes collections of edges and vertices and draws a graph on a specified
// canvas.
private void drawGraph(Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices,
GWTCanvas canvas) {
for (EdgeDrawable thisEdge : edges) {
drawEdge(thisEdge, canvas);
}
for (VertexDrawable thisVertex : vertices) {
drawVertex(thisVertex, canvas);
}
}
// set offset in the event of a pan
public void setOffset(int x, int y) {
mOffsetX = x;
mOffsetY = y;
}
// getters for offsets
public int getOffsetX() {
return mOffsetX;
}
// set the mode
public void setFlowChart(boolean mode) {
mIsFlowChart = mode;
}
public int getOffsetY() {
return mOffsetY;
}
// set zoom
public void setZoom(double z) {
mZoom = z;
}
public double getZoom() {
return mZoom;
}
}
| false | true | private void doRendering() {
// Update frames drawn
mFramesDone++;
// Can not render while render is happening
mCanRender = false;
// Do a (kind of reliable) check for webgl
if (webglCheck() == 1) {
// Can do WebGL
mNumVertices = 0;
String label = "";
int vertexStyle;
int edgeStyle;
double edgeThickness = 6;
float[] highlightColour = DrawingConstants.YELLOW;
if(mZoom <= EDGE_ZOOM_LIMIT) edgeThickness = edgeThickness*mZoom;
// Clear coordinates from last render
mVerticesList.clear();
mIndicesList.clear();
mColorsList.clear();
// SetupWebGl if not done so already
if (!mWebglReady)
setUpWebGL();
// Loop through all edges and draw them
for (EdgeDrawable thisEdge : mEdgesToDraw) {
mCurrentPolygon = thisEdge.getPolygon();
// Apply offset and zoom factors
double startX = (thisEdge.getStartX() + mOffsetX) * mZoom;
double startY = (thisEdge.getStartY() + mOffsetY) * mZoom;
double endX = (thisEdge.getEndX() + mOffsetX) * mZoom;
double endY = (thisEdge.getEndY() + mOffsetY) * mZoom;
int weight = thisEdge.getWeight();
float[] edgeColour = DrawingConstants.BLACK;
float[] textColour = DrawingConstants.BLACK;
int strokeThickness = 4;
// edgeStyle = thisEdge.getStyle();
edgeStyle = 100;
// If edge is highlighted apply set it to negative
if (thisEdge.isHilighted()){
edgeStyle = -edgeStyle;
edgeColour = DrawingConstants.YELLOW;
}
// Add edge to lists to be rendered
if(thisEdge.needsToFromArrow()){
if (thisEdge.isHilighted()){
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", edgeColour, textColour);
}else{
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
} else if(thisEdge.needsToFromArrow()){
if (thisEdge.isHilighted()){
addEdge(endX, endY, startX, startY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
addEdge(endX, endY, startX, startY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", edgeColour, textColour);
}else{
addEdge(endX, endY, startX, startY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
} else {
if (thisEdge.isHilighted()){
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", edgeColour, textColour);
}else{
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
}
}
// Add UI line if required
if (mShowUILine) {
addEdge((mUIline[0]+ mOffsetX)*mZoom, (mUIline[1]+ mOffsetY)*mZoom,
(mUIline[2]+ mOffsetX)*mZoom, (mUIline[3]+ mOffsetY)*mZoom,
edgeThickness, true,false,edgeThickness*5,edgeThickness*5,"", DrawingConstants.GREY, DrawingConstants.BLACK);
}
for (VertexDrawable thisVertex : mVerticesToDraw) {
mNumVertices++;
double centreX = (thisVertex.getCenterX() + mOffsetX) * mZoom;
double centreY = (thisVertex.getCenterY() + mOffsetY) * mZoom;
double width = (thisVertex.getWidth()) * mZoom;
double height = (thisVertex.getHeight()) * mZoom;
label = thisVertex.getLabel();
vertexStyle = thisVertex.getStyle();
float[] customColor = { 0, 0, 0, 1};
switch (vertexStyle) {
case VertexDrawable.STROKED_TERM_STYLE:
if (thisVertex.isHilighted()) {
addTerm(centreX, centreY,width,height, DrawingConstants.YELLOW);
addTerm(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
} else {
addTerm(centreX, centreY,width,height, DrawingConstants.BLACK);
addTerm(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
}
addStringBox(centreX, centreY, width-height,height, label, DrawingConstants.BLACK);
break;
case VertexDrawable.STROKED_SQUARE_STYLE:
if (thisVertex.isHilighted()) {
addSquare(centreX, centreY,width,height, DrawingConstants.YELLOW);
addSquare(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
} else {
addSquare(centreX, centreY,width,height, DrawingConstants.BLACK);
addSquare(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
}
addStringBox(centreX, centreY, width,height, label, DrawingConstants.BLACK);
break;
case VertexDrawable.STROKED_DIAMOND_STYLE:
if (thisVertex.isHilighted()) {
addDiamondStroke(centreX, centreY, width,height,DrawingConstants.GREY,
2,DrawingConstants.YELLOW);
} else {
addDiamondStroke(centreX, centreY, width,height,DrawingConstants.GREY,
2,DrawingConstants.BLACK);
}
addStringCircle(centreX, centreY, width/2, label, DrawingConstants.BLACK);
break;
case VertexDrawable.COLORED_FILLED_CIRCLE:
customColor = thisVertex.getColor();
addCircle(centreX, centreY, width, customColor);
break;
default:
if (thisVertex.isHilighted()) {
addCircle(centreX, centreY, width, highlightColour);
addCircle(centreX, centreY, width - 4, DrawingConstants.YELLOW);
} else {
addCircle(centreX, centreY, width, DrawingConstants.BLACK);
}
break;
}
}
renderGraph();
mCanRender = true;
} else {
// Can't do webGL so draw on 2d Canvas
renderGraph2d(m2dCanvas, mEdgesToDraw, mVerticesToDraw);
}
}
| private void doRendering() {
// Update frames drawn
mFramesDone++;
// Can not render while render is happening
mCanRender = false;
// Do a (kind of reliable) check for webgl
if (webglCheck() == 1) {
// Can do WebGL
mNumVertices = 0;
String label = "";
int vertexStyle;
int edgeStyle;
double edgeThickness = 6;
float[] highlightColour = DrawingConstants.YELLOW;
if(mZoom <= EDGE_ZOOM_LIMIT) edgeThickness = edgeThickness*mZoom;
// Clear coordinates from last render
mVerticesList.clear();
mIndicesList.clear();
mColorsList.clear();
// SetupWebGl if not done so already
if (!mWebglReady)
setUpWebGL();
// Loop through all edges and draw them
for (EdgeDrawable thisEdge : mEdgesToDraw) {
mCurrentPolygon = thisEdge.getPolygon();
// Apply offset and zoom factors
double startX = (thisEdge.getStartX() + mOffsetX) * mZoom;
double startY = (thisEdge.getStartY() + mOffsetY) * mZoom;
double endX = (thisEdge.getEndX() + mOffsetX) * mZoom;
double endY = (thisEdge.getEndY() + mOffsetY) * mZoom;
int weight = thisEdge.getWeight();
float[] edgeColour = DrawingConstants.BLACK;
float[] textColour = DrawingConstants.BLACK;
int strokeThickness = 4;
// edgeStyle = thisEdge.getStyle();
edgeStyle = 100;
// If edge is highlighted apply set it to negative
if (thisEdge.isHilighted()){
edgeStyle = -edgeStyle;
edgeColour = DrawingConstants.YELLOW;
}
// Add edge to lists to be rendered
if(thisEdge.needsToFromArrow()){
if (thisEdge.isHilighted()){
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", highlightColour, textColour);
}else{
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
} else if(thisEdge.needsToFromArrow()){
if (thisEdge.isHilighted()){
addEdge(endX, endY, startX, startY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
addEdge(endX, endY, startX, startY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", highlightColour, textColour);
}else{
addEdge(endX, endY, startX, startY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
} else {
if (thisEdge.isHilighted()){
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", highlightColour, textColour);
addEdge(startX, startY, endX, endY, edgeThickness-strokeThickness, false,false,(edgeThickness*5)-strokeThickness,0,"", highlightColour, textColour);
}else{
addEdge(startX, startY, endX, endY, edgeThickness, true,true,(edgeThickness*5),(edgeThickness*5),weight+"", edgeColour, textColour);
}
}
}
// Add UI line if required
if (mShowUILine) {
addEdge((mUIline[0]+ mOffsetX)*mZoom, (mUIline[1]+ mOffsetY)*mZoom,
(mUIline[2]+ mOffsetX)*mZoom, (mUIline[3]+ mOffsetY)*mZoom,
edgeThickness, true,false,edgeThickness*5,edgeThickness*5,"", DrawingConstants.GREY, DrawingConstants.BLACK);
}
for (VertexDrawable thisVertex : mVerticesToDraw) {
mNumVertices++;
double centreX = (thisVertex.getCenterX() + mOffsetX) * mZoom;
double centreY = (thisVertex.getCenterY() + mOffsetY) * mZoom;
double width = (thisVertex.getWidth()) * mZoom;
double height = (thisVertex.getHeight()) * mZoom;
label = thisVertex.getLabel();
vertexStyle = thisVertex.getStyle();
float[] customColor = { 0, 0, 0, 1};
switch (vertexStyle) {
case VertexDrawable.STROKED_TERM_STYLE:
if (thisVertex.isHilighted()) {
addTerm(centreX, centreY,width,height, DrawingConstants.YELLOW);
addTerm(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
} else {
addTerm(centreX, centreY,width,height, DrawingConstants.BLACK);
addTerm(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
}
addStringBox(centreX, centreY, width-height,height, label, DrawingConstants.BLACK);
break;
case VertexDrawable.STROKED_SQUARE_STYLE:
if (thisVertex.isHilighted()) {
addSquare(centreX, centreY,width,height, DrawingConstants.YELLOW);
addSquare(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
} else {
addSquare(centreX, centreY,width,height, DrawingConstants.BLACK);
addSquare(centreX, centreY,width-4,height-4, DrawingConstants.GREY);
}
addStringBox(centreX, centreY, width,height, label, DrawingConstants.BLACK);
break;
case VertexDrawable.STROKED_DIAMOND_STYLE:
if (thisVertex.isHilighted()) {
addDiamondStroke(centreX, centreY, width,height,DrawingConstants.GREY,
2,DrawingConstants.YELLOW);
} else {
addDiamondStroke(centreX, centreY, width,height,DrawingConstants.GREY,
2,DrawingConstants.BLACK);
}
addStringCircle(centreX, centreY, width/2, label, DrawingConstants.BLACK);
break;
case VertexDrawable.COLORED_FILLED_CIRCLE:
customColor = thisVertex.getColor();
addCircle(centreX, centreY, width, customColor);
break;
default:
if (thisVertex.isHilighted()) {
addCircle(centreX, centreY, width, highlightColour);
addCircle(centreX, centreY, width - 4, highlightColour);
} else {
addCircle(centreX, centreY, width, DrawingConstants.BLACK);
}
break;
}
}
renderGraph();
mCanRender = true;
} else {
// Can't do webGL so draw on 2d Canvas
renderGraph2d(m2dCanvas, mEdgesToDraw, mVerticesToDraw);
}
}
|
diff --git a/src/somebody/is/madbro/handlers/BotHandler.java b/src/somebody/is/madbro/handlers/BotHandler.java
index c9679dc..cbf48a2 100644
--- a/src/somebody/is/madbro/handlers/BotHandler.java
+++ b/src/somebody/is/madbro/handlers/BotHandler.java
@@ -1,252 +1,252 @@
package somebody.is.madbro.handlers;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import somebody.is.madbro.AntiBotCore;
import somebody.is.madbro.datatrack.DataTrackCore;
import somebody.is.madbro.settings.Settings;
public class BotHandler {
private AntiBotCore botclass = null;
private DataTrackCore data = null;
public BotHandler(AntiBotCore instance, DataTrackCore instance2) {
// transfer instance for compatibility
botclass = instance;
data = instance2;
// TODO Auto-generated constructor stub
}
public void onPlayerKick(PlayerKickEvent event) {
if (!Settings.enabled) {
return;
}
if (data.getBotTracker().autokick.contains(event.getPlayer().getName())) {
event.setLeaveMessage(null);
return;
}
if (data.getBotTracker().autoipkick.contains(event.getPlayer()
.getAddress().toString().split(":")[0])) {
event.setLeaveMessage(null);
return;
}
}
// falsified antibot trigger bug fix, or brolos bug fix.
public void onPlayerQuit(PlayerQuitEvent event) {
if (botclass.getHandler().getPermissions().hasPerms(event.getPlayer())) {
return;
} else {
if (data.getBotTracker().botcts < 1) {
return;
} else {
data.getBotTracker().botcts -= 1;
}
}
}
public void onPlayerMove(PlayerMoveEvent event) {
if (!Settings.enabled) {
return;
}
try {
String pl = event.getPlayer().getName();
if (data.getChatTracker().trackplayers.containsKey(pl)) {
if (!(data.getChatTracker().trackplayers.get(pl)).hasMoved) {
(data.getChatTracker().trackplayers.get(pl)).moved();
}
}
} catch (Exception e) {
botclass.getUtility()
.getDebug()
.debug("Player " + event.getPlayer().getName()
+ " did not get updated successfully for move.");
}
}
public void onPlayerJoin(PlayerJoinEvent event) {
if (!Settings.enabled) {
return;
}
try {
botclass.getUtility().getDebug()
.debug("User is trying to connect..");
data.getBotTracker().time = System.currentTimeMillis();
if (botclass.getHandler().getPermissions()
.hasPerms(event.getPlayer())) {
botclass.getUtility().getDebug().debug("Whitelisted.");
if (data.getBotTracker().reanibo
&& botclass
.getHandler()
.getPermissions()
- .ownPermission("AntiBot.Settings.notify",
+ .ownPermission("AntiBot.notify",
event.getPlayer(), 1)) {
event.getPlayer().sendMessage(
Settings.prefix + "\247c"
+ Settings.connectInvasion);
// updates notify
if (botclass.getUpdates().newVersion) {
event.getPlayer()
.sendMessage(
Settings.prefix
+ "\247a"
+ "There is currently a new update for AntiBot!");
event.getPlayer().sendMessage(
Settings.prefix + "\247a" + "New version: v"
+ botclass.getUpdates().version
+ " Your version: v"
+ botclass.getVersion());
}
}
if (data.getBotTracker().reanibo
&& botclass
.getHandler()
.getPermissions()
- .ownPermission("AntiBot.admin.Settings.notify",
+ .ownPermission("AntiBot.admin.notify",
event.getPlayer(), 2)
&& Settings.interval > 100000) {
event.getPlayer()
.sendMessage(
Settings.prefix
+ "\247cThe system needs a flush. Please type /antibot flush. Thanks.");
}
return;
}
if (data.getBotTracker().autokick.contains(event.getPlayer()
.getName())) {
event.getPlayer().kickPlayer(Settings.kickMsg);
event.setJoinMessage("");
return;
}
if (!data.getBotTracker().reanibo) {
// IP tracking usernames system.
data.getBotTracker()
.trackPlayer(
event.getPlayer(),
event.getPlayer().getAddress().toString()
.split(":")[0]);
botclass.getUtility().getDebug()
.debug("Added user to tracking");
data.getBotTracker().addConnected(event.getPlayer().getName());
botclass.getUtility().getDebug()
.debug("Added user to connected");
data.getChatTracker().trackplayers.put(
event.getPlayer().getName(),
botclass.getDataTrack().getPlayer(
event.getPlayer().getName(), this));
botclass.getUtility().getDebug()
.debug("Added user to trackplayer");
}
if (data.getBotTracker().botcts > Settings.accounts + 2
&& data.getBotTracker().reanibo) {
Settings.accounts = Settings.accounts + 2;
Settings.interval = Settings.interval + 5000;
}
// bug workaround
if (Settings.interval < 1) {
botclass.getUtility().getDebug()
.debug("Bug detected! Fixing bug.");
// lets try setting this back to default Settings.intervals, if
// not,
// reload
// the configuration.
Settings.interval = botclass.getDefaultinterval();
if (botclass.getDefaultinterval() < 1) {
// have to fix.
botclass.getSettings().loadSettings(
botclass.getDataFolder());
}
}
long math = data.getBotTracker().time
- data.getBotTracker().lasttime;
int cb = Settings.interval
+ botclass.getUtility().getBot().getRandomIntInvasion();
botclass.getUtility().getDebug().debug("Checking....0");
botclass.getUtility().getDebug().debug("Math: " + math);
botclass.getUtility().getDebug()
.debug("Time: " + data.getBotTracker().time);
botclass.getUtility().getDebug()
.debug("Current Interval: " + Settings.interval);
botclass.getUtility().getDebug().debug("Random Interval: " + cb);
botclass.getUtility().getDebug()
.debug("Lasttime: " + data.getBotTracker().lasttime);
botclass.getUtility()
.getDebug()
.debug("BotCts: " + data.getBotTracker().botcts + " Accs: "
+ Settings.accounts);
if (data.getBotTracker().botcts > Settings.accounts && math < cb) {
botclass.getUtility().getDebug().debug("Hit #1!");
// Incoming invasion.
if (!data.getBotTracker().reanibo) {
if (Settings.whiteList) {
if (Settings.notify && Settings.whiteList) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247cOh no! A minecraft bot invasion has began. Connection Throttling: \247aEnabled");
}
data.getBotTracker().reanibo = true;
} else {
if (Settings.notify) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247chas detected minecraft spam!");
}
}
botclass.getUtility().getDebug().debug("Tripswitched!");
botclass.getUtility().getBot().kickConnected();
botclass.getUtility().getBot().flush();
}
data.getBotTracker().botattempt = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
event.getPlayer().kickPlayer(Settings.connectMsg);
event.setJoinMessage("");
} else if (data.getBotTracker().botattempt < Settings.interval
&& data.getBotTracker().reanibo) {
botclass.getUtility().getDebug().debug("Hit #2");
// Attempting to connect.
data.getBotTracker().botattempt = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
event.getPlayer().kickPlayer(Settings.connectMsg);
event.setJoinMessage("");
} else {
botclass.getUtility().getDebug().debug("Hit #3");
if (data.getBotTracker().reanibo) {
botclass.getUtility().getBot().flush();
}
// No invasion.
data.getBotTracker().lasttime = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
}
if (!botclass.getServer()
.getOfflinePlayer(event.getPlayer().getName()).isOnline()) {
event.setJoinMessage("");
}
} catch (Exception e) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247cAn error had occured! Please check console.");
e.printStackTrace();
}
}
}
| false | true | public void onPlayerJoin(PlayerJoinEvent event) {
if (!Settings.enabled) {
return;
}
try {
botclass.getUtility().getDebug()
.debug("User is trying to connect..");
data.getBotTracker().time = System.currentTimeMillis();
if (botclass.getHandler().getPermissions()
.hasPerms(event.getPlayer())) {
botclass.getUtility().getDebug().debug("Whitelisted.");
if (data.getBotTracker().reanibo
&& botclass
.getHandler()
.getPermissions()
.ownPermission("AntiBot.Settings.notify",
event.getPlayer(), 1)) {
event.getPlayer().sendMessage(
Settings.prefix + "\247c"
+ Settings.connectInvasion);
// updates notify
if (botclass.getUpdates().newVersion) {
event.getPlayer()
.sendMessage(
Settings.prefix
+ "\247a"
+ "There is currently a new update for AntiBot!");
event.getPlayer().sendMessage(
Settings.prefix + "\247a" + "New version: v"
+ botclass.getUpdates().version
+ " Your version: v"
+ botclass.getVersion());
}
}
if (data.getBotTracker().reanibo
&& botclass
.getHandler()
.getPermissions()
.ownPermission("AntiBot.admin.Settings.notify",
event.getPlayer(), 2)
&& Settings.interval > 100000) {
event.getPlayer()
.sendMessage(
Settings.prefix
+ "\247cThe system needs a flush. Please type /antibot flush. Thanks.");
}
return;
}
if (data.getBotTracker().autokick.contains(event.getPlayer()
.getName())) {
event.getPlayer().kickPlayer(Settings.kickMsg);
event.setJoinMessage("");
return;
}
if (!data.getBotTracker().reanibo) {
// IP tracking usernames system.
data.getBotTracker()
.trackPlayer(
event.getPlayer(),
event.getPlayer().getAddress().toString()
.split(":")[0]);
botclass.getUtility().getDebug()
.debug("Added user to tracking");
data.getBotTracker().addConnected(event.getPlayer().getName());
botclass.getUtility().getDebug()
.debug("Added user to connected");
data.getChatTracker().trackplayers.put(
event.getPlayer().getName(),
botclass.getDataTrack().getPlayer(
event.getPlayer().getName(), this));
botclass.getUtility().getDebug()
.debug("Added user to trackplayer");
}
if (data.getBotTracker().botcts > Settings.accounts + 2
&& data.getBotTracker().reanibo) {
Settings.accounts = Settings.accounts + 2;
Settings.interval = Settings.interval + 5000;
}
// bug workaround
if (Settings.interval < 1) {
botclass.getUtility().getDebug()
.debug("Bug detected! Fixing bug.");
// lets try setting this back to default Settings.intervals, if
// not,
// reload
// the configuration.
Settings.interval = botclass.getDefaultinterval();
if (botclass.getDefaultinterval() < 1) {
// have to fix.
botclass.getSettings().loadSettings(
botclass.getDataFolder());
}
}
long math = data.getBotTracker().time
- data.getBotTracker().lasttime;
int cb = Settings.interval
+ botclass.getUtility().getBot().getRandomIntInvasion();
botclass.getUtility().getDebug().debug("Checking....0");
botclass.getUtility().getDebug().debug("Math: " + math);
botclass.getUtility().getDebug()
.debug("Time: " + data.getBotTracker().time);
botclass.getUtility().getDebug()
.debug("Current Interval: " + Settings.interval);
botclass.getUtility().getDebug().debug("Random Interval: " + cb);
botclass.getUtility().getDebug()
.debug("Lasttime: " + data.getBotTracker().lasttime);
botclass.getUtility()
.getDebug()
.debug("BotCts: " + data.getBotTracker().botcts + " Accs: "
+ Settings.accounts);
if (data.getBotTracker().botcts > Settings.accounts && math < cb) {
botclass.getUtility().getDebug().debug("Hit #1!");
// Incoming invasion.
if (!data.getBotTracker().reanibo) {
if (Settings.whiteList) {
if (Settings.notify && Settings.whiteList) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247cOh no! A minecraft bot invasion has began. Connection Throttling: \247aEnabled");
}
data.getBotTracker().reanibo = true;
} else {
if (Settings.notify) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247chas detected minecraft spam!");
}
}
botclass.getUtility().getDebug().debug("Tripswitched!");
botclass.getUtility().getBot().kickConnected();
botclass.getUtility().getBot().flush();
}
data.getBotTracker().botattempt = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
event.getPlayer().kickPlayer(Settings.connectMsg);
event.setJoinMessage("");
} else if (data.getBotTracker().botattempt < Settings.interval
&& data.getBotTracker().reanibo) {
botclass.getUtility().getDebug().debug("Hit #2");
// Attempting to connect.
data.getBotTracker().botattempt = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
event.getPlayer().kickPlayer(Settings.connectMsg);
event.setJoinMessage("");
} else {
botclass.getUtility().getDebug().debug("Hit #3");
if (data.getBotTracker().reanibo) {
botclass.getUtility().getBot().flush();
}
// No invasion.
data.getBotTracker().lasttime = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
}
if (!botclass.getServer()
.getOfflinePlayer(event.getPlayer().getName()).isOnline()) {
event.setJoinMessage("");
}
} catch (Exception e) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247cAn error had occured! Please check console.");
e.printStackTrace();
}
}
| public void onPlayerJoin(PlayerJoinEvent event) {
if (!Settings.enabled) {
return;
}
try {
botclass.getUtility().getDebug()
.debug("User is trying to connect..");
data.getBotTracker().time = System.currentTimeMillis();
if (botclass.getHandler().getPermissions()
.hasPerms(event.getPlayer())) {
botclass.getUtility().getDebug().debug("Whitelisted.");
if (data.getBotTracker().reanibo
&& botclass
.getHandler()
.getPermissions()
.ownPermission("AntiBot.notify",
event.getPlayer(), 1)) {
event.getPlayer().sendMessage(
Settings.prefix + "\247c"
+ Settings.connectInvasion);
// updates notify
if (botclass.getUpdates().newVersion) {
event.getPlayer()
.sendMessage(
Settings.prefix
+ "\247a"
+ "There is currently a new update for AntiBot!");
event.getPlayer().sendMessage(
Settings.prefix + "\247a" + "New version: v"
+ botclass.getUpdates().version
+ " Your version: v"
+ botclass.getVersion());
}
}
if (data.getBotTracker().reanibo
&& botclass
.getHandler()
.getPermissions()
.ownPermission("AntiBot.admin.notify",
event.getPlayer(), 2)
&& Settings.interval > 100000) {
event.getPlayer()
.sendMessage(
Settings.prefix
+ "\247cThe system needs a flush. Please type /antibot flush. Thanks.");
}
return;
}
if (data.getBotTracker().autokick.contains(event.getPlayer()
.getName())) {
event.getPlayer().kickPlayer(Settings.kickMsg);
event.setJoinMessage("");
return;
}
if (!data.getBotTracker().reanibo) {
// IP tracking usernames system.
data.getBotTracker()
.trackPlayer(
event.getPlayer(),
event.getPlayer().getAddress().toString()
.split(":")[0]);
botclass.getUtility().getDebug()
.debug("Added user to tracking");
data.getBotTracker().addConnected(event.getPlayer().getName());
botclass.getUtility().getDebug()
.debug("Added user to connected");
data.getChatTracker().trackplayers.put(
event.getPlayer().getName(),
botclass.getDataTrack().getPlayer(
event.getPlayer().getName(), this));
botclass.getUtility().getDebug()
.debug("Added user to trackplayer");
}
if (data.getBotTracker().botcts > Settings.accounts + 2
&& data.getBotTracker().reanibo) {
Settings.accounts = Settings.accounts + 2;
Settings.interval = Settings.interval + 5000;
}
// bug workaround
if (Settings.interval < 1) {
botclass.getUtility().getDebug()
.debug("Bug detected! Fixing bug.");
// lets try setting this back to default Settings.intervals, if
// not,
// reload
// the configuration.
Settings.interval = botclass.getDefaultinterval();
if (botclass.getDefaultinterval() < 1) {
// have to fix.
botclass.getSettings().loadSettings(
botclass.getDataFolder());
}
}
long math = data.getBotTracker().time
- data.getBotTracker().lasttime;
int cb = Settings.interval
+ botclass.getUtility().getBot().getRandomIntInvasion();
botclass.getUtility().getDebug().debug("Checking....0");
botclass.getUtility().getDebug().debug("Math: " + math);
botclass.getUtility().getDebug()
.debug("Time: " + data.getBotTracker().time);
botclass.getUtility().getDebug()
.debug("Current Interval: " + Settings.interval);
botclass.getUtility().getDebug().debug("Random Interval: " + cb);
botclass.getUtility().getDebug()
.debug("Lasttime: " + data.getBotTracker().lasttime);
botclass.getUtility()
.getDebug()
.debug("BotCts: " + data.getBotTracker().botcts + " Accs: "
+ Settings.accounts);
if (data.getBotTracker().botcts > Settings.accounts && math < cb) {
botclass.getUtility().getDebug().debug("Hit #1!");
// Incoming invasion.
if (!data.getBotTracker().reanibo) {
if (Settings.whiteList) {
if (Settings.notify && Settings.whiteList) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247cOh no! A minecraft bot invasion has began. Connection Throttling: \247aEnabled");
}
data.getBotTracker().reanibo = true;
} else {
if (Settings.notify) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247chas detected minecraft spam!");
}
}
botclass.getUtility().getDebug().debug("Tripswitched!");
botclass.getUtility().getBot().kickConnected();
botclass.getUtility().getBot().flush();
}
data.getBotTracker().botattempt = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
event.getPlayer().kickPlayer(Settings.connectMsg);
event.setJoinMessage("");
} else if (data.getBotTracker().botattempt < Settings.interval
&& data.getBotTracker().reanibo) {
botclass.getUtility().getDebug().debug("Hit #2");
// Attempting to connect.
data.getBotTracker().botattempt = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
event.getPlayer().kickPlayer(Settings.connectMsg);
event.setJoinMessage("");
} else {
botclass.getUtility().getDebug().debug("Hit #3");
if (data.getBotTracker().reanibo) {
botclass.getUtility().getBot().flush();
}
// No invasion.
data.getBotTracker().lasttime = System.currentTimeMillis();
data.getBotTracker().botcts += 1;
}
if (!botclass.getServer()
.getOfflinePlayer(event.getPlayer().getName()).isOnline()) {
event.setJoinMessage("");
}
} catch (Exception e) {
botclass.getServer()
.broadcastMessage(
Settings.prefix
+ "\247cAn error had occured! Please check console.");
e.printStackTrace();
}
}
|
diff --git a/src/uurss/DownloadTask.java b/src/uurss/DownloadTask.java
index c118403..aefe1ce 100644
--- a/src/uurss/DownloadTask.java
+++ b/src/uurss/DownloadTask.java
@@ -1,111 +1,111 @@
package uurss;
import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.security.*;
import java.util.concurrent.*;
import java.util.zip.*;
import org.apache.log4j.*;
/**
* The task which download feed data(XML).
*/
final class DownloadTask implements Callable<File> {
private static final Logger log = Logger.getLogger(DownloadTask.class);
private static MessageDigest instance;
static {
try {
instance = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
private FeedInfo info;
private File root;
DownloadTask(FeedInfo info, File root) {
this.info = info;
this.root = root;
}
/* @see java.util.concurrent.Callable#call() */
public File call() throws Exception {
File feedFile = new File(root, getMessageDigestString(info.name) + ".xml");
info.setFile(feedFile);
if (log.isDebugEnabled()) {
log.debug(String.format("%s(%s) => [%s]", info.name, info.url, feedFile.getName()));
}
URL url = new URL(info.url);
InputStream is = url.openStream();
try {
transfer(is, feedFile);
} finally {
is.close();
}
if (isGzipFile(feedFile)) {
if (log.isDebugEnabled()) {
log.debug(String.format("unzip [%s]", feedFile.getName()));
}
- File tmp = new File(root, ".tmp.dat");
+ File tmp = new File(root, String.format("%s.tmp", feedFile.getName()));
// unzip
InputStream gis = new GZIPInputStream(new FileInputStream(feedFile));
try {
transfer(gis, tmp);
} finally {
gis.close();
}
if (feedFile.delete() && !tmp.renameTo(feedFile)) {
log.warn(String.format("failed to rename [%s] to [%s]",
tmp.getName(),
feedFile.getName()));
}
}
return feedFile;
}
private static boolean isGzipFile(File file) throws IOException {
if (file.length() >= 2) {
InputStream fis = new FileInputStream(file);
try {
byte[] bytes = new byte[2];
if (fis.read(bytes) >= 2) {
if (((bytes[1] & 0xFF) * 0x100 + (bytes[0] & 0xFF)) == GZIPInputStream.GZIP_MAGIC) {
return true;
}
}
} finally {
fis.close();
}
}
return false;
}
private static long transfer(InputStream is, File dst) throws IOException {
FileOutputStream fos = new FileOutputStream(dst);
try {
final FileChannel wch = fos.getChannel();
final ReadableByteChannel rch = Channels.newChannel(is);
long p = 0L;
for (long read = 0L; (read = wch.transferFrom(rch, p, 8192)) > 0; p += read) {
//
}
return p;
} finally {
fos.close();
}
}
private static String getMessageDigestString(String input) {
StringBuilder buffer = new StringBuilder();
for (byte b : instance.digest(input.getBytes())) {
buffer.append(String.format("%02X", b));
}
return buffer.toString();
}
}
| true | true | public File call() throws Exception {
File feedFile = new File(root, getMessageDigestString(info.name) + ".xml");
info.setFile(feedFile);
if (log.isDebugEnabled()) {
log.debug(String.format("%s(%s) => [%s]", info.name, info.url, feedFile.getName()));
}
URL url = new URL(info.url);
InputStream is = url.openStream();
try {
transfer(is, feedFile);
} finally {
is.close();
}
if (isGzipFile(feedFile)) {
if (log.isDebugEnabled()) {
log.debug(String.format("unzip [%s]", feedFile.getName()));
}
File tmp = new File(root, ".tmp.dat");
// unzip
InputStream gis = new GZIPInputStream(new FileInputStream(feedFile));
try {
transfer(gis, tmp);
} finally {
gis.close();
}
if (feedFile.delete() && !tmp.renameTo(feedFile)) {
log.warn(String.format("failed to rename [%s] to [%s]",
tmp.getName(),
feedFile.getName()));
}
}
return feedFile;
}
| public File call() throws Exception {
File feedFile = new File(root, getMessageDigestString(info.name) + ".xml");
info.setFile(feedFile);
if (log.isDebugEnabled()) {
log.debug(String.format("%s(%s) => [%s]", info.name, info.url, feedFile.getName()));
}
URL url = new URL(info.url);
InputStream is = url.openStream();
try {
transfer(is, feedFile);
} finally {
is.close();
}
if (isGzipFile(feedFile)) {
if (log.isDebugEnabled()) {
log.debug(String.format("unzip [%s]", feedFile.getName()));
}
File tmp = new File(root, String.format("%s.tmp", feedFile.getName()));
// unzip
InputStream gis = new GZIPInputStream(new FileInputStream(feedFile));
try {
transfer(gis, tmp);
} finally {
gis.close();
}
if (feedFile.delete() && !tmp.renameTo(feedFile)) {
log.warn(String.format("failed to rename [%s] to [%s]",
tmp.getName(),
feedFile.getName()));
}
}
return feedFile;
}
|
diff --git a/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/EnsurePhoneConnectedCommand.java b/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/EnsurePhoneConnectedCommand.java
index 552b7e10..86417260 100644
--- a/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/EnsurePhoneConnectedCommand.java
+++ b/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/EnsurePhoneConnectedCommand.java
@@ -1,56 +1,56 @@
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.appinventor.client.explorer.commands;
import com.google.appinventor.client.ErrorReporter;
import static com.google.appinventor.client.Ode.MESSAGES;
import com.google.appinventor.client.youngandroid.CodeblocksManager;
import com.google.appinventor.shared.rpc.project.ProjectNode;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* Command for testing if the phone is connected
*
* @author [email protected] (Debby Wallach)
*/
public class EnsurePhoneConnectedCommand extends ChainableCommand {
/**
* Creates a new ensure phone connected command, with additional behavior
* provided by another ChainableCommand.
*
* @param nextCommand the command to execute iff the phone is connected
*/
public EnsurePhoneConnectedCommand(ChainableCommand nextCommand) {
super(nextCommand);
}
@Override
public boolean willCallExecuteNextCommand() {
return true;
}
@Override
public void execute(final ProjectNode node) {
AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
ErrorReporter.reportError(caught.getMessage());
executionFailedOrCanceled();
}
@Override
public void onSuccess(Boolean result) {
if (result) {
executeNextCommand(node);
} else {
- ErrorReporter.reportError(MESSAGES.phoneNotConnected());
+ ErrorReporter.reportInfo(MESSAGES.phoneNotConnected());
executionFailedOrCanceled();
}
}
};
CodeblocksManager.getCodeblocksManager().isPhoneConnected(callback);
}
}
| true | true | public void execute(final ProjectNode node) {
AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
ErrorReporter.reportError(caught.getMessage());
executionFailedOrCanceled();
}
@Override
public void onSuccess(Boolean result) {
if (result) {
executeNextCommand(node);
} else {
ErrorReporter.reportError(MESSAGES.phoneNotConnected());
executionFailedOrCanceled();
}
}
};
CodeblocksManager.getCodeblocksManager().isPhoneConnected(callback);
}
| public void execute(final ProjectNode node) {
AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
ErrorReporter.reportError(caught.getMessage());
executionFailedOrCanceled();
}
@Override
public void onSuccess(Boolean result) {
if (result) {
executeNextCommand(node);
} else {
ErrorReporter.reportInfo(MESSAGES.phoneNotConnected());
executionFailedOrCanceled();
}
}
};
CodeblocksManager.getCodeblocksManager().isPhoneConnected(callback);
}
|
diff --git a/src/org/eclipse/core/internal/resources/Synchronizer.java b/src/org/eclipse/core/internal/resources/Synchronizer.java
index 21240891..55fe50a4 100644
--- a/src/org/eclipse/core/internal/resources/Synchronizer.java
+++ b/src/org/eclipse/core/internal/resources/Synchronizer.java
@@ -1,261 +1,265 @@
/*******************************************************************************
* Copyright (c) 2000, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.resources;
import java.io.*;
import java.util.*;
import org.eclipse.core.internal.localstore.SafeChunkyInputStream;
import org.eclipse.core.internal.localstore.SafeFileInputStream;
import org.eclipse.core.internal.utils.Messages;
import org.eclipse.core.internal.utils.Policy;
import org.eclipse.core.internal.watson.IPathRequestor;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.osgi.util.NLS;
//
public class Synchronizer implements ISynchronizer {
protected Workspace workspace;
protected SyncInfoWriter writer;
// Registry of sync partners. Set of qualified names.
protected Set registry = new HashSet(5);
public Synchronizer(Workspace workspace) {
super();
this.workspace = workspace;
this.writer = new SyncInfoWriter(workspace, this);
}
/**
* @see ISynchronizer#accept(QualifiedName, IResource, IResourceVisitor, int)
*/
public void accept(QualifiedName partner, IResource resource, IResourceVisitor visitor, int depth) throws CoreException {
Assert.isLegal(partner != null);
Assert.isLegal(resource != null);
Assert.isLegal(visitor != null);
// if we don't have sync info for the given identifier, then skip it
if (getSyncInfo(partner, resource) != null) {
// visit the resource and if the visitor says to stop the recursion then return
if (!visitor.visit(resource))
return;
}
// adjust depth if necessary
if (depth == IResource.DEPTH_ZERO || resource.getType() == IResource.FILE)
return;
if (depth == IResource.DEPTH_ONE)
depth = IResource.DEPTH_ZERO;
// otherwise recurse over the children
IResource[] children = ((IContainer) resource).members();
for (int i = 0; i < children.length; i++)
accept(partner, children[i], visitor, depth);
}
/**
* @see ISynchronizer#add(QualifiedName)
*/
public void add(QualifiedName partner) {
Assert.isLegal(partner != null);
registry.add(partner);
}
/**
* @see ISynchronizer#flushSyncInfo(QualifiedName, IResource, int)
*/
public void flushSyncInfo(final QualifiedName partner, final IResource root, final int depth) throws CoreException {
Assert.isLegal(partner != null);
Assert.isLegal(root != null);
IWorkspaceRunnable body = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IResourceVisitor visitor = new IResourceVisitor() {
public boolean visit(IResource resource) throws CoreException {
//only need to flush sync info if there is sync info
if (getSyncInfo(partner, resource) != null)
setSyncInfo(partner, resource, null);
return true;
}
};
root.accept(visitor, depth, true);
}
};
workspace.run(body, root, IResource.NONE, null);
}
/**
* @see ISynchronizer#getPartners()
*/
public QualifiedName[] getPartners() {
return (QualifiedName[]) registry.toArray(new QualifiedName[registry.size()]);
}
/**
* For use by the serialization code.
*/
protected Set getRegistry() {
return registry;
}
/**
* @see ISynchronizer#getSyncInfo(QualifiedName, IResource)
*/
public byte[] getSyncInfo(QualifiedName partner, IResource resource) throws CoreException {
Assert.isLegal(partner != null);
Assert.isLegal(resource != null);
if (!isRegistered(partner)) {
String message = NLS.bind(Messages.synchronizer_partnerNotRegistered, partner);
throw new ResourceException(new ResourceStatus(IResourceStatus.PARTNER_NOT_REGISTERED, message));
}
// namespace check, if the resource doesn't exist then return null
ResourceInfo info = workspace.getResourceInfo(resource.getFullPath(), true, false);
return (info == null) ? null : info.getSyncInfo(partner, true);
}
protected boolean isRegistered(QualifiedName partner) {
Assert.isLegal(partner != null);
return registry.contains(partner);
}
/**
* @see #savePartners(DataOutputStream)
*/
public void readPartners(DataInputStream input) throws CoreException {
SyncInfoReader reader = new SyncInfoReader(workspace, this);
reader.readPartners(input);
}
public void restore(IResource resource, IProgressMonitor monitor) throws CoreException {
// first restore from the last save and then apply any snapshots
restoreFromSave(resource);
restoreFromSnap(resource);
}
protected void restoreFromSave(IResource resource) throws CoreException {
IPath sourceLocation = workspace.getMetaArea().getSyncInfoLocationFor(resource);
IPath tempLocation = workspace.getMetaArea().getBackupLocationFor(sourceLocation);
if (!sourceLocation.toFile().exists() && !tempLocation.toFile().exists())
return;
try {
DataInputStream input = new DataInputStream(new SafeFileInputStream(sourceLocation.toOSString(), tempLocation.toOSString()));
try {
SyncInfoReader reader = new SyncInfoReader(workspace, this);
reader.readSyncInfo(input);
} finally {
input.close();
}
} catch (Exception e) {
//don't let runtime exceptions such as ArrayIndexOutOfBounds prevent startup
String msg = NLS.bind(Messages.resources_readMeta, sourceLocation);
throw new ResourceException(IResourceStatus.FAILED_READ_METADATA, sourceLocation, msg, e);
}
}
protected void restoreFromSnap(IResource resource) {
IPath sourceLocation = workspace.getMetaArea().getSyncInfoSnapshotLocationFor(resource);
if (!sourceLocation.toFile().exists())
return;
try {
DataInputStream input = new DataInputStream(new SafeChunkyInputStream(sourceLocation.toFile()));
try {
SyncInfoSnapReader reader = new SyncInfoSnapReader(workspace, this);
while (true)
reader.readSyncInfo(input);
} catch (EOFException eof) {
// ignore end of file -- proceed with what we successfully read
} finally {
input.close();
}
} catch (Exception e) {
// only log the exception, we should not fail restoring the snapshot
String msg = NLS.bind(Messages.resources_readMeta, sourceLocation);
Policy.log(new ResourceStatus(IResourceStatus.FAILED_READ_METADATA, sourceLocation, msg, e));
}
}
/**
* @see ISynchronizer#remove(QualifiedName)
*/
public void remove(QualifiedName partner) {
Assert.isLegal(partner != null);
if (isRegistered(partner)) {
// remove all sync info for this partner
try {
flushSyncInfo(partner, workspace.getRoot(), IResource.DEPTH_INFINITE);
registry.remove(partner);
} catch (CoreException e) {
// XXX: flush needs to be more resilient and not throw exceptions all the time
Policy.log(e);
}
}
}
public void savePartners(DataOutputStream output) throws IOException {
writer.savePartners(output);
}
public void saveSyncInfo(ResourceInfo info, IPathRequestor requestor, DataOutputStream output, List writtenPartners) throws IOException {
writer.saveSyncInfo(info, requestor, output, writtenPartners);
}
protected void setRegistry(Set registry) {
this.registry = registry;
}
/**
* @see ISynchronizer#setSyncInfo(QualifiedName, IResource, byte[])
*/
public void setSyncInfo(QualifiedName partner, IResource resource, byte[] info) throws CoreException {
Assert.isLegal(partner != null);
Assert.isLegal(resource != null);
try {
workspace.prepareOperation(resource, null);
workspace.beginOperation(true);
if (!isRegistered(partner)) {
String message = NLS.bind(Messages.synchronizer_partnerNotRegistered, partner);
throw new ResourceException(new ResourceStatus(IResourceStatus.PARTNER_NOT_REGISTERED, message));
}
// we do not store sync info on the workspace root
if (resource.getType() == IResource.ROOT)
return;
// if the resource doesn't yet exist then create a phantom so we can set the sync info on it
Resource target = (Resource) resource;
ResourceInfo resourceInfo = workspace.getResourceInfo(target.getFullPath(), true, false);
int flags = target.getFlags(resourceInfo);
if (!target.exists(flags, false)) {
if (info == null)
return;
- workspace.createResource(resource, true);
+ //ensure it is possible to create this resource
+ target.checkValidPath(target.getFullPath(), target.getType(), false);
+ Container parent = (Container)target.getParent();
+ parent.checkAccessible(parent.getFlags(parent.getResourceInfo(true, false)));
+ workspace.createResource(target, true);
}
resourceInfo = target.getResourceInfo(true, true);
resourceInfo.setSyncInfo(partner, info);
resourceInfo.incrementSyncInfoGenerationCount();
resourceInfo.set(ICoreConstants.M_SYNCINFO_SNAP_DIRTY);
flags = target.getFlags(resourceInfo);
if (target.isPhantom(flags) && resourceInfo.getSyncInfo(false) == null) {
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, Messages.resources_deleteProblem, null);
((Resource) resource).deleteResource(false, status);
if (!status.isOK())
throw new ResourceException(status);
}
} finally {
workspace.endOperation(resource, false, null);
}
}
public void snapSyncInfo(ResourceInfo info, IPathRequestor requestor, DataOutputStream output) throws IOException {
writer.snapSyncInfo(info, requestor, output);
}
}
| true | true | public void setSyncInfo(QualifiedName partner, IResource resource, byte[] info) throws CoreException {
Assert.isLegal(partner != null);
Assert.isLegal(resource != null);
try {
workspace.prepareOperation(resource, null);
workspace.beginOperation(true);
if (!isRegistered(partner)) {
String message = NLS.bind(Messages.synchronizer_partnerNotRegistered, partner);
throw new ResourceException(new ResourceStatus(IResourceStatus.PARTNER_NOT_REGISTERED, message));
}
// we do not store sync info on the workspace root
if (resource.getType() == IResource.ROOT)
return;
// if the resource doesn't yet exist then create a phantom so we can set the sync info on it
Resource target = (Resource) resource;
ResourceInfo resourceInfo = workspace.getResourceInfo(target.getFullPath(), true, false);
int flags = target.getFlags(resourceInfo);
if (!target.exists(flags, false)) {
if (info == null)
return;
workspace.createResource(resource, true);
}
resourceInfo = target.getResourceInfo(true, true);
resourceInfo.setSyncInfo(partner, info);
resourceInfo.incrementSyncInfoGenerationCount();
resourceInfo.set(ICoreConstants.M_SYNCINFO_SNAP_DIRTY);
flags = target.getFlags(resourceInfo);
if (target.isPhantom(flags) && resourceInfo.getSyncInfo(false) == null) {
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, Messages.resources_deleteProblem, null);
((Resource) resource).deleteResource(false, status);
if (!status.isOK())
throw new ResourceException(status);
}
} finally {
workspace.endOperation(resource, false, null);
}
}
| public void setSyncInfo(QualifiedName partner, IResource resource, byte[] info) throws CoreException {
Assert.isLegal(partner != null);
Assert.isLegal(resource != null);
try {
workspace.prepareOperation(resource, null);
workspace.beginOperation(true);
if (!isRegistered(partner)) {
String message = NLS.bind(Messages.synchronizer_partnerNotRegistered, partner);
throw new ResourceException(new ResourceStatus(IResourceStatus.PARTNER_NOT_REGISTERED, message));
}
// we do not store sync info on the workspace root
if (resource.getType() == IResource.ROOT)
return;
// if the resource doesn't yet exist then create a phantom so we can set the sync info on it
Resource target = (Resource) resource;
ResourceInfo resourceInfo = workspace.getResourceInfo(target.getFullPath(), true, false);
int flags = target.getFlags(resourceInfo);
if (!target.exists(flags, false)) {
if (info == null)
return;
//ensure it is possible to create this resource
target.checkValidPath(target.getFullPath(), target.getType(), false);
Container parent = (Container)target.getParent();
parent.checkAccessible(parent.getFlags(parent.getResourceInfo(true, false)));
workspace.createResource(target, true);
}
resourceInfo = target.getResourceInfo(true, true);
resourceInfo.setSyncInfo(partner, info);
resourceInfo.incrementSyncInfoGenerationCount();
resourceInfo.set(ICoreConstants.M_SYNCINFO_SNAP_DIRTY);
flags = target.getFlags(resourceInfo);
if (target.isPhantom(flags) && resourceInfo.getSyncInfo(false) == null) {
MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, Messages.resources_deleteProblem, null);
((Resource) resource).deleteResource(false, status);
if (!status.isOK())
throw new ResourceException(status);
}
} finally {
workspace.endOperation(resource, false, null);
}
}
|
diff --git a/WikiOnThisDay.java b/WikiOnThisDay.java
index 65f176a..67f6493 100644
--- a/WikiOnThisDay.java
+++ b/WikiOnThisDay.java
@@ -1,182 +1,185 @@
/*
*
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Raveesh Bhalla <[email protected]>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
*
*
* Credit to Colin Mitchell (http://muffinlabs.com)
* whose Really Simple History API
* (https://github.com/muffinista/really-simple-history-api/)
* project I used prior to developing this.
*
* The JSON return structure in this project is
* the same as his work so as to simplify porting, if required.
*
* You will require the HTMLCleaner library which can be downloaded
* from http://htmlcleaner.sourceforge.net/
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Raveesh
*
*/
/**
* @author Raveesh
*
*/
/**
* @author Raveesh
*
*/
public class WikiOnThisDay {
JSONObject entireData;
JSONArray Births, Deaths, Events;
/**
* @param month month in the form of integer, eg, 1 corresponds to January, 2 to February
* @param date date of the month
* @throws JSONException
* @throws IOException
* @throws XPatherException
*/
public WikiOnThisDay(int month,int date) throws JSONException, IOException, XPatherException{
String[] months = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
URL url = new URL("http://wikipedia.org/wiki/"+months[month-1]+"_"+date);
TagNode node;
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17");
InputStreamReader is = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(is);
node = cleaner.clean(is);
Object[] info_nodes = node.evaluateXPath("//ul");
int eventsNode = 1;
if (month == 1 && date == 1)
eventsNode++;
TagNode EventsNode = (TagNode) info_nodes[eventsNode];
List EventsChildren = EventsNode.getElementListByName("li", false);
Events = new JSONArray();
for (int i=0;i<EventsChildren.size();i++){
TagNode child = (TagNode) EventsChildren.get(i);
String text = child.getText().toString();
- String[] split = text.split(" – ");
+ String splitby = "–";
+ String[] split = text.split(splitby);
JSONObject item = new JSONObject();
- item.put("year", split[0]);
- item.put("text", split[1]);
+ item.put("year", split[0].trim());
+ item.put("text", split[1].trim());
Events.put(item);
}
TagNode BirthsNode = (TagNode) info_nodes[eventsNode+1];
List BirthsChildren = BirthsNode.getElementListByName("li", false);
Births = new JSONArray();
for (int i=0;i<BirthsChildren.size();i++){
TagNode child = (TagNode) BirthsChildren.get(i);
String text = child.getText().toString();
- String[] split = text.split(" – ");
+ String splitby = "–";
+ String[] split = text.split(splitby);
JSONObject item = new JSONObject();
- item.put("year", split[0]);
- item.put("text", split[1]);
+ item.put("year", split[0].trim());
+ item.put("text", split[1].trim());
Births.put(item);
}
TagNode DeathsNode = (TagNode) info_nodes[eventsNode+2];
List DeathsChildren = DeathsNode.getElementListByName("li", false);
Deaths = new JSONArray();
for (int i=0;i<DeathsChildren.size();i++){
TagNode child = (TagNode) DeathsChildren.get(i);
String text = child.getText().toString();
- String[] split = text.split(" – ");
+ String splitby = "–";
+ String[] split = text.split(splitby);
JSONObject item = new JSONObject();
- item.put("year", split[0]);
- item.put("text", split[1]);
+ item.put("year", split[0].trim());
+ item.put("text", split[1].trim());
Deaths.put(item);
}
JSONObject data = new JSONObject();
data.put("Deaths", Deaths);
data.put("Births", Births);
data.put("Events", Events);
entireData = new JSONObject();
entireData.put("data", data);
entireData.put("url", url.toString());
entireData.put("date", months[month-1]+" "+date);
}
/**
* @return JSONObject for the entire data
*/
public JSONObject getEntireData(){
return entireData;
}
/**
* @return JSONArray for Births
*/
public JSONArray getBirths(){
return Births;
}
/**
* @return JSONArray for Deaths
*/
public JSONArray getDeaths(){
return Deaths;
}
/**
* @return JSONArray for Events
*/
public JSONArray getEvents(){
return Events;
}
}
| false | true | public WikiOnThisDay(int month,int date) throws JSONException, IOException, XPatherException{
String[] months = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
URL url = new URL("http://wikipedia.org/wiki/"+months[month-1]+"_"+date);
TagNode node;
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17");
InputStreamReader is = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(is);
node = cleaner.clean(is);
Object[] info_nodes = node.evaluateXPath("//ul");
int eventsNode = 1;
if (month == 1 && date == 1)
eventsNode++;
TagNode EventsNode = (TagNode) info_nodes[eventsNode];
List EventsChildren = EventsNode.getElementListByName("li", false);
Events = new JSONArray();
for (int i=0;i<EventsChildren.size();i++){
TagNode child = (TagNode) EventsChildren.get(i);
String text = child.getText().toString();
String[] split = text.split(" – ");
JSONObject item = new JSONObject();
item.put("year", split[0]);
item.put("text", split[1]);
Events.put(item);
}
TagNode BirthsNode = (TagNode) info_nodes[eventsNode+1];
List BirthsChildren = BirthsNode.getElementListByName("li", false);
Births = new JSONArray();
for (int i=0;i<BirthsChildren.size();i++){
TagNode child = (TagNode) BirthsChildren.get(i);
String text = child.getText().toString();
String[] split = text.split(" – ");
JSONObject item = new JSONObject();
item.put("year", split[0]);
item.put("text", split[1]);
Births.put(item);
}
TagNode DeathsNode = (TagNode) info_nodes[eventsNode+2];
List DeathsChildren = DeathsNode.getElementListByName("li", false);
Deaths = new JSONArray();
for (int i=0;i<DeathsChildren.size();i++){
TagNode child = (TagNode) DeathsChildren.get(i);
String text = child.getText().toString();
String[] split = text.split(" – ");
JSONObject item = new JSONObject();
item.put("year", split[0]);
item.put("text", split[1]);
Deaths.put(item);
}
JSONObject data = new JSONObject();
data.put("Deaths", Deaths);
data.put("Births", Births);
data.put("Events", Events);
entireData = new JSONObject();
entireData.put("data", data);
entireData.put("url", url.toString());
entireData.put("date", months[month-1]+" "+date);
}
| public WikiOnThisDay(int month,int date) throws JSONException, IOException, XPatherException{
String[] months = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
URL url = new URL("http://wikipedia.org/wiki/"+months[month-1]+"_"+date);
TagNode node;
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17");
InputStreamReader is = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(is);
node = cleaner.clean(is);
Object[] info_nodes = node.evaluateXPath("//ul");
int eventsNode = 1;
if (month == 1 && date == 1)
eventsNode++;
TagNode EventsNode = (TagNode) info_nodes[eventsNode];
List EventsChildren = EventsNode.getElementListByName("li", false);
Events = new JSONArray();
for (int i=0;i<EventsChildren.size();i++){
TagNode child = (TagNode) EventsChildren.get(i);
String text = child.getText().toString();
String splitby = "–";
String[] split = text.split(splitby);
JSONObject item = new JSONObject();
item.put("year", split[0].trim());
item.put("text", split[1].trim());
Events.put(item);
}
TagNode BirthsNode = (TagNode) info_nodes[eventsNode+1];
List BirthsChildren = BirthsNode.getElementListByName("li", false);
Births = new JSONArray();
for (int i=0;i<BirthsChildren.size();i++){
TagNode child = (TagNode) BirthsChildren.get(i);
String text = child.getText().toString();
String splitby = "–";
String[] split = text.split(splitby);
JSONObject item = new JSONObject();
item.put("year", split[0].trim());
item.put("text", split[1].trim());
Births.put(item);
}
TagNode DeathsNode = (TagNode) info_nodes[eventsNode+2];
List DeathsChildren = DeathsNode.getElementListByName("li", false);
Deaths = new JSONArray();
for (int i=0;i<DeathsChildren.size();i++){
TagNode child = (TagNode) DeathsChildren.get(i);
String text = child.getText().toString();
String splitby = "–";
String[] split = text.split(splitby);
JSONObject item = new JSONObject();
item.put("year", split[0].trim());
item.put("text", split[1].trim());
Deaths.put(item);
}
JSONObject data = new JSONObject();
data.put("Deaths", Deaths);
data.put("Births", Births);
data.put("Events", Events);
entireData = new JSONObject();
entireData.put("data", data);
entireData.put("url", url.toString());
entireData.put("date", months[month-1]+" "+date);
}
|
diff --git a/nuxeo-core-event/src/test/java/org/nuxeo/ecm/core/event/test/TestEventListenerContrib.java b/nuxeo-core-event/src/test/java/org/nuxeo/ecm/core/event/test/TestEventListenerContrib.java
index b33de1d8f..f89fdc758 100644
--- a/nuxeo-core-event/src/test/java/org/nuxeo/ecm/core/event/test/TestEventListenerContrib.java
+++ b/nuxeo-core-event/src/test/java/org/nuxeo/ecm/core/event/test/TestEventListenerContrib.java
@@ -1,93 +1,94 @@
/*
* Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.ecm.core.event.test;
import java.net.URL;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.nuxeo.ecm.core.event.EventService;
import org.nuxeo.ecm.core.event.PostCommitEventListener;
import org.nuxeo.ecm.core.event.impl.EventListenerDescriptor;
import org.nuxeo.ecm.core.event.impl.EventServiceImpl;
import org.nuxeo.ecm.core.event.script.ScriptingPostCommitEventListener;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.model.RuntimeContext;
import org.nuxeo.runtime.test.NXRuntimeTestCase;
public class TestEventListenerContrib extends NXRuntimeTestCase {
@Before
public void setUp() throws Exception {
super.setUp();
deployBundle("org.nuxeo.ecm.core.event");
}
@Test
public void testMerge() throws Exception {
URL url = EventListenerTest.class.getClassLoader().getResource(
"test-listeners.xml");
RuntimeContext rc = deployTestContrib("org.nuxeo.ecm.core.event", url);
EventService service = Framework.getService(EventService.class);
EventServiceImpl serviceImpl = (EventServiceImpl) service;
+ int N = 2;
List<EventListenerDescriptor> inLineDescs = serviceImpl.getEventListenerList().getInlineListenersDescriptors();
- assertEquals(1, inLineDescs.size());
- assertEquals(1, serviceImpl.getEventListenerList().getInLineListeners().size());
+ assertEquals(N, inLineDescs.size());
+ assertEquals(N, serviceImpl.getEventListenerList().getInLineListeners().size());
// check enable flag
EventListenerDescriptor desc = inLineDescs.get(0);
desc.setEnabled(false);
serviceImpl.addEventListener(desc);
- assertEquals(0, serviceImpl.getEventListenerList().getInLineListeners().size());
+ assertEquals(N - 1, serviceImpl.getEventListenerList().getInLineListeners().size());
desc.setEnabled(true);
serviceImpl.addEventListener(desc);
- assertEquals(1, serviceImpl.getEventListenerList().getInLineListeners().size());
+ assertEquals(N, serviceImpl.getEventListenerList().getInLineListeners().size());
// test PostCommit
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
List<EventListenerDescriptor> apcDescs = serviceImpl.getEventListenerList().getAsyncPostCommitListenersDescriptors();
assertEquals(1, apcDescs.size());
assertEquals(1, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners2.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
assertEquals(0, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
assertEquals(1, serviceImpl.getEventListenerList().getSyncPostCommitListeners().size());
boolean isScriptListener = false;
PostCommitEventListener listener = serviceImpl.getEventListenerList().getSyncPostCommitListeners().get(0);
if ( listener instanceof ScriptingPostCommitEventListener) {
isScriptListener=true;
}
assertTrue(isScriptListener);
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners3.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
assertEquals(1, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
assertEquals(0, serviceImpl.getEventListenerList().getSyncPostCommitListeners().size());
listener = serviceImpl.getEventListenerList().getAsyncPostCommitListeners().get(0);
isScriptListener = listener instanceof ScriptingPostCommitEventListener;
assertFalse(isScriptListener);
}
}
| false | true | public void testMerge() throws Exception {
URL url = EventListenerTest.class.getClassLoader().getResource(
"test-listeners.xml");
RuntimeContext rc = deployTestContrib("org.nuxeo.ecm.core.event", url);
EventService service = Framework.getService(EventService.class);
EventServiceImpl serviceImpl = (EventServiceImpl) service;
List<EventListenerDescriptor> inLineDescs = serviceImpl.getEventListenerList().getInlineListenersDescriptors();
assertEquals(1, inLineDescs.size());
assertEquals(1, serviceImpl.getEventListenerList().getInLineListeners().size());
// check enable flag
EventListenerDescriptor desc = inLineDescs.get(0);
desc.setEnabled(false);
serviceImpl.addEventListener(desc);
assertEquals(0, serviceImpl.getEventListenerList().getInLineListeners().size());
desc.setEnabled(true);
serviceImpl.addEventListener(desc);
assertEquals(1, serviceImpl.getEventListenerList().getInLineListeners().size());
// test PostCommit
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
List<EventListenerDescriptor> apcDescs = serviceImpl.getEventListenerList().getAsyncPostCommitListenersDescriptors();
assertEquals(1, apcDescs.size());
assertEquals(1, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners2.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
assertEquals(0, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
assertEquals(1, serviceImpl.getEventListenerList().getSyncPostCommitListeners().size());
boolean isScriptListener = false;
PostCommitEventListener listener = serviceImpl.getEventListenerList().getSyncPostCommitListeners().get(0);
if ( listener instanceof ScriptingPostCommitEventListener) {
isScriptListener=true;
}
assertTrue(isScriptListener);
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners3.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
assertEquals(1, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
assertEquals(0, serviceImpl.getEventListenerList().getSyncPostCommitListeners().size());
listener = serviceImpl.getEventListenerList().getAsyncPostCommitListeners().get(0);
isScriptListener = listener instanceof ScriptingPostCommitEventListener;
assertFalse(isScriptListener);
}
| public void testMerge() throws Exception {
URL url = EventListenerTest.class.getClassLoader().getResource(
"test-listeners.xml");
RuntimeContext rc = deployTestContrib("org.nuxeo.ecm.core.event", url);
EventService service = Framework.getService(EventService.class);
EventServiceImpl serviceImpl = (EventServiceImpl) service;
int N = 2;
List<EventListenerDescriptor> inLineDescs = serviceImpl.getEventListenerList().getInlineListenersDescriptors();
assertEquals(N, inLineDescs.size());
assertEquals(N, serviceImpl.getEventListenerList().getInLineListeners().size());
// check enable flag
EventListenerDescriptor desc = inLineDescs.get(0);
desc.setEnabled(false);
serviceImpl.addEventListener(desc);
assertEquals(N - 1, serviceImpl.getEventListenerList().getInLineListeners().size());
desc.setEnabled(true);
serviceImpl.addEventListener(desc);
assertEquals(N, serviceImpl.getEventListenerList().getInLineListeners().size());
// test PostCommit
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
List<EventListenerDescriptor> apcDescs = serviceImpl.getEventListenerList().getAsyncPostCommitListenersDescriptors();
assertEquals(1, apcDescs.size());
assertEquals(1, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners2.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
assertEquals(0, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
assertEquals(1, serviceImpl.getEventListenerList().getSyncPostCommitListeners().size());
boolean isScriptListener = false;
PostCommitEventListener listener = serviceImpl.getEventListenerList().getSyncPostCommitListeners().get(0);
if ( listener instanceof ScriptingPostCommitEventListener) {
isScriptListener=true;
}
assertTrue(isScriptListener);
url = EventListenerTest.class.getClassLoader().getResource("test-PostCommitListeners3.xml");
deployTestContrib("org.nuxeo.ecm.core.event", url);
assertEquals(1, serviceImpl.getEventListenerList().getAsyncPostCommitListeners().size());
assertEquals(0, serviceImpl.getEventListenerList().getSyncPostCommitListeners().size());
listener = serviceImpl.getEventListenerList().getAsyncPostCommitListeners().get(0);
isScriptListener = listener instanceof ScriptingPostCommitEventListener;
assertFalse(isScriptListener);
}
|
diff --git a/src/test/java/dbmigrate/parser/LoaderTest.java b/src/test/java/dbmigrate/parser/LoaderTest.java
index 1fed5f7..671b1bf 100644
--- a/src/test/java/dbmigrate/parser/LoaderTest.java
+++ b/src/test/java/dbmigrate/parser/LoaderTest.java
@@ -1,37 +1,37 @@
package dbmigrate.parser;
import java.io.File;
import junit.framework.TestCase;
import dbmigrate.executor.CreateTableExecutor;
import dbmigrate.model.operation.CreateTableOperationDescriptor;
import dbmigrate.model.operation.MigrationConfiguration;
import dbmigrate.parser.model.Migration;
import dbmigrate.parser.model.RemoveColumn;
public class LoaderTest extends TestCase{
public void testMapping() throws Exception {
Migration m=new Migration();
RemoveColumn rm=new RemoveColumn();
rm.setTable("TEST");
rm.setName("TEST2|");
m.getDoList().add(rm);
Loader.map(m);
}
public void testCreateMigrationConfiguration(){
try {
- MigrationConfiguration mc = Loader.load(new File("migrations/2011111001_first_migration.xml", false));
+ MigrationConfiguration mc = Loader.load(new File("migrations/2011111001_first_migration.xml"), false);
CreateTableOperationDescriptor desc = (CreateTableOperationDescriptor) mc.getOperations().get(0);
CreateTableExecutor executor = new CreateTableExecutor(null);
assertEquals("CREATE TABLE \"users\" ( id INT NOT NULL,username TEXT (40) NOT NULL,password TEXT (40) NOT NULL);", executor.createSql(desc).trim());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public void testCreateMigrationConfiguration(){
try {
MigrationConfiguration mc = Loader.load(new File("migrations/2011111001_first_migration.xml", false));
CreateTableOperationDescriptor desc = (CreateTableOperationDescriptor) mc.getOperations().get(0);
CreateTableExecutor executor = new CreateTableExecutor(null);
assertEquals("CREATE TABLE \"users\" ( id INT NOT NULL,username TEXT (40) NOT NULL,password TEXT (40) NOT NULL);", executor.createSql(desc).trim());
} catch (Exception e) {
e.printStackTrace();
}
}
| public void testCreateMigrationConfiguration(){
try {
MigrationConfiguration mc = Loader.load(new File("migrations/2011111001_first_migration.xml"), false);
CreateTableOperationDescriptor desc = (CreateTableOperationDescriptor) mc.getOperations().get(0);
CreateTableExecutor executor = new CreateTableExecutor(null);
assertEquals("CREATE TABLE \"users\" ( id INT NOT NULL,username TEXT (40) NOT NULL,password TEXT (40) NOT NULL);", executor.createSql(desc).trim());
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/ch/entwine/weblounge/taglib/content/HTMLHeaderTag.java b/src/main/java/ch/entwine/weblounge/taglib/content/HTMLHeaderTag.java
index ca5f1aff8..943997ba1 100644
--- a/src/main/java/ch/entwine/weblounge/taglib/content/HTMLHeaderTag.java
+++ b/src/main/java/ch/entwine/weblounge/taglib/content/HTMLHeaderTag.java
@@ -1,182 +1,181 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.taglib.content;
import ch.entwine.weblounge.common.content.page.DeclarativeHTMLHeadElement;
import ch.entwine.weblounge.common.content.page.HTMLHeadElement;
import ch.entwine.weblounge.common.content.page.HTMLInclude;
import ch.entwine.weblounge.common.content.page.Page;
import ch.entwine.weblounge.common.content.page.PageTemplate;
import ch.entwine.weblounge.common.content.page.Pagelet;
import ch.entwine.weblounge.common.content.page.PageletRenderer;
import ch.entwine.weblounge.common.content.page.Script;
import ch.entwine.weblounge.common.impl.request.RequestUtils;
import ch.entwine.weblounge.common.request.WebloungeRequest;
import ch.entwine.weblounge.common.site.HTMLAction;
import ch.entwine.weblounge.common.site.Module;
import ch.entwine.weblounge.common.site.Site;
import ch.entwine.weblounge.kernel.shared.WebloungeSharedResources;
import ch.entwine.weblounge.taglib.WebloungeTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.jsp.JspException;
/**
* This tag prints out various headers for the <head> section of an html
* page.
*/
public class HTMLHeaderTag extends WebloungeTag {
/** Serial version uid */
private static final long serialVersionUID = -1813975272420106327L;
/** Logging facility provided by log4j */
private static final Logger logger = LoggerFactory.getLogger(HTMLHeaderTag.class);
/** A list for link and script head elements */
private ArrayList<HTMLHeadElement> headElements = new ArrayList<HTMLHeadElement>();
/** A flag if an script head element need jquery */
private boolean needsJQuery = false;
/**
* Does the tag processing.
*
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException {
HTMLAction action = (HTMLAction) getRequest().getAttribute(WebloungeRequest.ACTION);
// See what the action has to contribute
try {
pageContext.getOut().flush();
if (action != null && action.startHeader(request, response) == HTMLAction.SKIP_HEADER) {
pageContext.getOut().flush();
return EVAL_PAGE;
}
} catch (Exception e) {
logger.error("Error asking action '" + action + "' for headers", e);
}
// Start with the default processing
Site site = request.getSite();
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
if (page != null) {
// Page template links & scripts
PageTemplate template = site.getTemplate(page.getTemplate());
template.setEnvironment(request.getEnvironment());
for (HTMLHeadElement header : template.getHTMLHeaders()) {
addHeadElement(header, site, null);
}
// Pagelets links & scripts
for (Pagelet p : page.getPagelets()) {
String moduleId = p.getModule();
Module module = site.getModule(moduleId);
if (module == null) {
logger.debug("Unable to load includes for renderer '{}': module '{}' not installed", new Object[] {
p.getIdentifier(),
site,
request.getRequestedUrl(),
moduleId });
continue;
}
PageletRenderer renderer = module.getRenderer(p.getIdentifier());
if (renderer == null) {
logger.warn("Renderer '" + p + "' not found for " + request.getUrl() + "!");
continue;
}
renderer.setEnvironment(request.getEnvironment());
for (HTMLHeadElement header : renderer.getHTMLHeaders()) {
addHeadElement(header, site, module);
}
}
}
// Action links & scripts
if (action != null) {
Module module = action.getModule();
for (HTMLHeadElement header : action.getHTMLHeaders()) {
- if (header instanceof DeclarativeHTMLHeadElement)
- ((DeclarativeHTMLHeadElement) header).configure(request, site, module);
- if (!headElements.contains(header))
- headElements.add(header);
+ addHeadElement(header, site, module);
}
}
// Write links & scripts to output
try {
pageContext.getOut().flush();
// Write first jQuery script to output
if (!RequestUtils.isEditingState(request) && needsJQuery) {
StringBuffer linkToJQuery = new StringBuffer("/weblounge-shared/scripts/jquery/");
linkToJQuery.append(WebloungeSharedResources.JQUERY_VERSION);
linkToJQuery.append("/jquery.min.js");
pageContext.getOut().print("<script src=\"" + linkToJQuery + "\" type=\"text/javascript\"></script>");
StringBuffer linkToJQueryTools = new StringBuffer("/weblounge-shared/scripts/jquery-tools/");
linkToJQueryTools.append(WebloungeSharedResources.JQUERY_TOOLS_VERSION);
linkToJQueryTools.append("/jquery.tools.min.js");
pageContext.getOut().print("<script src=\"" + linkToJQueryTools + "\" type=\"text/javascript\"></script>");
+ } else if (RequestUtils.isEditingState(request)) {
+ pageContext.getOut().print("<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />");
}
for (HTMLHeadElement s : headElements) {
pageContext.getOut().println(s.toXml());
}
pageContext.getOut().flush();
} catch (IOException e) {
throw new JspException();
}
return super.doEndTag();
}
/**
* Adds a head element to the list if it isn't only used by the editor.
*
* @param headElement
* the head element to include
* @param site
* the site
* @param module
* the module
*/
private void addHeadElement(HTMLHeadElement headElement, Site site,
Module module) {
if (headElement instanceof DeclarativeHTMLHeadElement)
((DeclarativeHTMLHeadElement) headElement).configure(request, site, module);
if (headElement.getUse().equals(HTMLInclude.Use.Editor))
return;
if (headElement instanceof Script)
if (((Script) headElement).getJQuery() != null)
needsJQuery = true;
if (!headElements.contains(headElement))
headElements.add(headElement);
}
}
| false | true | public int doEndTag() throws JspException {
HTMLAction action = (HTMLAction) getRequest().getAttribute(WebloungeRequest.ACTION);
// See what the action has to contribute
try {
pageContext.getOut().flush();
if (action != null && action.startHeader(request, response) == HTMLAction.SKIP_HEADER) {
pageContext.getOut().flush();
return EVAL_PAGE;
}
} catch (Exception e) {
logger.error("Error asking action '" + action + "' for headers", e);
}
// Start with the default processing
Site site = request.getSite();
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
if (page != null) {
// Page template links & scripts
PageTemplate template = site.getTemplate(page.getTemplate());
template.setEnvironment(request.getEnvironment());
for (HTMLHeadElement header : template.getHTMLHeaders()) {
addHeadElement(header, site, null);
}
// Pagelets links & scripts
for (Pagelet p : page.getPagelets()) {
String moduleId = p.getModule();
Module module = site.getModule(moduleId);
if (module == null) {
logger.debug("Unable to load includes for renderer '{}': module '{}' not installed", new Object[] {
p.getIdentifier(),
site,
request.getRequestedUrl(),
moduleId });
continue;
}
PageletRenderer renderer = module.getRenderer(p.getIdentifier());
if (renderer == null) {
logger.warn("Renderer '" + p + "' not found for " + request.getUrl() + "!");
continue;
}
renderer.setEnvironment(request.getEnvironment());
for (HTMLHeadElement header : renderer.getHTMLHeaders()) {
addHeadElement(header, site, module);
}
}
}
// Action links & scripts
if (action != null) {
Module module = action.getModule();
for (HTMLHeadElement header : action.getHTMLHeaders()) {
if (header instanceof DeclarativeHTMLHeadElement)
((DeclarativeHTMLHeadElement) header).configure(request, site, module);
if (!headElements.contains(header))
headElements.add(header);
}
}
// Write links & scripts to output
try {
pageContext.getOut().flush();
// Write first jQuery script to output
if (!RequestUtils.isEditingState(request) && needsJQuery) {
StringBuffer linkToJQuery = new StringBuffer("/weblounge-shared/scripts/jquery/");
linkToJQuery.append(WebloungeSharedResources.JQUERY_VERSION);
linkToJQuery.append("/jquery.min.js");
pageContext.getOut().print("<script src=\"" + linkToJQuery + "\" type=\"text/javascript\"></script>");
StringBuffer linkToJQueryTools = new StringBuffer("/weblounge-shared/scripts/jquery-tools/");
linkToJQueryTools.append(WebloungeSharedResources.JQUERY_TOOLS_VERSION);
linkToJQueryTools.append("/jquery.tools.min.js");
pageContext.getOut().print("<script src=\"" + linkToJQueryTools + "\" type=\"text/javascript\"></script>");
}
for (HTMLHeadElement s : headElements) {
pageContext.getOut().println(s.toXml());
}
pageContext.getOut().flush();
} catch (IOException e) {
throw new JspException();
}
return super.doEndTag();
}
| public int doEndTag() throws JspException {
HTMLAction action = (HTMLAction) getRequest().getAttribute(WebloungeRequest.ACTION);
// See what the action has to contribute
try {
pageContext.getOut().flush();
if (action != null && action.startHeader(request, response) == HTMLAction.SKIP_HEADER) {
pageContext.getOut().flush();
return EVAL_PAGE;
}
} catch (Exception e) {
logger.error("Error asking action '" + action + "' for headers", e);
}
// Start with the default processing
Site site = request.getSite();
Page page = (Page) request.getAttribute(WebloungeRequest.PAGE);
if (page != null) {
// Page template links & scripts
PageTemplate template = site.getTemplate(page.getTemplate());
template.setEnvironment(request.getEnvironment());
for (HTMLHeadElement header : template.getHTMLHeaders()) {
addHeadElement(header, site, null);
}
// Pagelets links & scripts
for (Pagelet p : page.getPagelets()) {
String moduleId = p.getModule();
Module module = site.getModule(moduleId);
if (module == null) {
logger.debug("Unable to load includes for renderer '{}': module '{}' not installed", new Object[] {
p.getIdentifier(),
site,
request.getRequestedUrl(),
moduleId });
continue;
}
PageletRenderer renderer = module.getRenderer(p.getIdentifier());
if (renderer == null) {
logger.warn("Renderer '" + p + "' not found for " + request.getUrl() + "!");
continue;
}
renderer.setEnvironment(request.getEnvironment());
for (HTMLHeadElement header : renderer.getHTMLHeaders()) {
addHeadElement(header, site, module);
}
}
}
// Action links & scripts
if (action != null) {
Module module = action.getModule();
for (HTMLHeadElement header : action.getHTMLHeaders()) {
addHeadElement(header, site, module);
}
}
// Write links & scripts to output
try {
pageContext.getOut().flush();
// Write first jQuery script to output
if (!RequestUtils.isEditingState(request) && needsJQuery) {
StringBuffer linkToJQuery = new StringBuffer("/weblounge-shared/scripts/jquery/");
linkToJQuery.append(WebloungeSharedResources.JQUERY_VERSION);
linkToJQuery.append("/jquery.min.js");
pageContext.getOut().print("<script src=\"" + linkToJQuery + "\" type=\"text/javascript\"></script>");
StringBuffer linkToJQueryTools = new StringBuffer("/weblounge-shared/scripts/jquery-tools/");
linkToJQueryTools.append(WebloungeSharedResources.JQUERY_TOOLS_VERSION);
linkToJQueryTools.append("/jquery.tools.min.js");
pageContext.getOut().print("<script src=\"" + linkToJQueryTools + "\" type=\"text/javascript\"></script>");
} else if (RequestUtils.isEditingState(request)) {
pageContext.getOut().print("<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />");
}
for (HTMLHeadElement s : headElements) {
pageContext.getOut().println(s.toXml());
}
pageContext.getOut().flush();
} catch (IOException e) {
throw new JspException();
}
return super.doEndTag();
}
|
diff --git a/module-api/src/main/java/org/xbrlapi/data/XBRLStoreImpl.java b/module-api/src/main/java/org/xbrlapi/data/XBRLStoreImpl.java
index b1b146a1..7a34db6f 100644
--- a/module-api/src/main/java/org/xbrlapi/data/XBRLStoreImpl.java
+++ b/module-api/src/main/java/org/xbrlapi/data/XBRLStoreImpl.java
@@ -1,402 +1,403 @@
package org.xbrlapi.data;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.xbrlapi.Arc;
import org.xbrlapi.ArcEnd;
import org.xbrlapi.ArcroleType;
import org.xbrlapi.Concept;
import org.xbrlapi.ExtendedLink;
import org.xbrlapi.Fact;
import org.xbrlapi.Fragment;
import org.xbrlapi.FragmentList;
import org.xbrlapi.Instance;
import org.xbrlapi.Item;
import org.xbrlapi.Resource;
import org.xbrlapi.RoleType;
import org.xbrlapi.Tuple;
import org.xbrlapi.impl.FragmentListImpl;
import org.xbrlapi.utilities.Constants;
import org.xbrlapi.utilities.XBRLException;
/**
* Abstract implementation of the XBRL data store.
* @author Geoffrey Shuetrim ([email protected])
*/
public abstract class XBRLStoreImpl extends BaseStoreImpl implements XBRLStore {
public XBRLStoreImpl() {
super();
}
/**
* @return a list of all of the root-level facts in the data store (those facts
* that are children of the root element of an XBRL instance). Returns an empty list
* if no facts are found.
* @throws XBRLException
*/
public FragmentList<Fact> getFacts() throws XBRLException {
FragmentList<Instance> instances = this.<Instance>getFragments("Instance");
return getFactsFromInstances(instances);
}
/**
* This method is provided as a helper method for the getFact methods.
* @param instances The list of instance fragments to extract facts from.
* @return The list of facts in the instances.
* @throws XBRLException
*/
private FragmentList<Fact> getFactsFromInstances(FragmentList<Instance> instances) throws XBRLException {
FragmentList<Fact> facts = new FragmentListImpl<Fact>();
for (Instance instance: instances) {
facts.addAll(instance.getFacts());
}
return facts;
}
/**
* Helper method for common code in the getItem methods.
* @param instances The instances to retrieve items for.
* @return a list of root items in the instances.
* @throws XBRLException
*/
private FragmentList<Item> getItemsFromInstances(FragmentList<Instance> instances) throws XBRLException {
FragmentList<Fact> facts = getFactsFromInstances(instances);
FragmentList<Item> items = new FragmentListImpl<Item>();
for (Fact fact: facts) {
if (! fact.getType().equals("org.xbrlapi.org.impl.TupleImpl"))
items.addFragment((Item) fact);
}
return items;
}
/**
* Helper method for common code in the getTuple methods.
* @param instances The instances to retrieve tuples for.
* @return a list of root tuples in the instances.
* @throws XBRLException
*/
private FragmentList<Tuple> getTuplesFromInstances(FragmentList<Instance> instances) throws XBRLException {
FragmentList<Fact> facts = getFactsFromInstances(instances);
FragmentList<Tuple> tuples = new FragmentListImpl<Tuple>();
for (Fact fact: facts) {
if (fact.getType().equals("org.xbrlapi.org.impl.TupleImpl"))
tuples.addFragment((Tuple) fact);
}
return tuples;
}
/**
* @return a list of all of the root-level items in the data store(those items
* that are children of the root element of an XBRL instance).
* TODO eliminate the redundant retrieval of tuples from the getItems methods.
* @throws XBRLException
*/
public FragmentList<Item> getItems() throws XBRLException {
FragmentList<Instance> instances = this.<Instance>getFragments("Instance");
return getItemsFromInstances(instances);
}
/**
* @return a list of all of the tuples in the data store.
* @throws XBRLException
*/
public FragmentList<Tuple> getTuples() throws XBRLException {
FragmentList<Instance> instances = this.<Instance>getFragments("Instance");
return this.getTuplesFromInstances(instances);
}
/**
* @param url The URL of the document to get the facts from.
* @return a list of all of the root-level facts in the specified document.
* @throws XBRLException
*/
public FragmentList<Fact> getFacts(URL url) throws XBRLException {
FragmentList<Instance> instances = this.<Instance>getFragmentsFromDocument(url,"Instance");
return this.getFactsFromInstances(instances);
}
/**
* @param url The URL of the document to get the items from.
* @return a list of all of the root-level items in the data store.
* @throws XBRLException
*/
public FragmentList<Item> getItems(URL url) throws XBRLException {
FragmentList<Instance> instances = this.<Instance>getFragmentsFromDocument(url,"Instance");
return this.getItemsFromInstances(instances);
}
/**
* @param url The URL of the document to get the facts from.
* @return a list of all of the root-level tuples in the specified document.
* @throws XBRLException
*/
public FragmentList<Tuple> getTuples(URL url) throws XBRLException {
FragmentList<Instance> instances = this.<Instance>getFragmentsFromDocument(url,"Instance");
return this.getTuplesFromInstances(instances);
}
/**
* Implementation strategy is:<br/>
* 1. Get all extended link elements matching network requirements.<br/>
* 2. Get all arcs defining relationships in the network.<br/>
* 3. Get all resources at the source of the arcs.<br/>
* 4. Return only those source resources that that are not target resources also.<br/>
*
* @param linkNamespace The namespace of the link element.
* @param linkName The name of the link element.
* @param linkRole the role on the extended links that contain the network arcs.
* @param arcNamespace The namespace of the arc element.
* @param arcName The name of the arc element.
* @param arcRole the arcrole on the arcs describing the network.
* @return The list of fragments for each of the resources that is identified as a root
* of the specified network (noting that a root resource is defined as a resource that is
* at the source of one or more relationships in the network and that is not at the target
* of any relationships in the network).
* @throws XBRLException
*/
public FragmentList<Fragment> getNetworkRoots(String linkNamespace, String linkName, String linkRole, String arcNamespace, String arcName, String arcRole) throws XBRLException {
// Get the links that contain the network declaring arcs.
- String linkQuery = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment[@type='org.xbrlapi.impl.ExtendedLinkImpl']/"+ Constants.XBRLAPIPrefix+ ":" + "data/*[namespace-uri()='" + linkNamespace + "' and local-name()='" + linkName + "' and @xlink:role='" + linkRole + "']";
+ String linkQuery = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment[@type='org.xbrlapi.impl.ExtendedLinkImpl' and "+ Constants.XBRLAPIPrefix+ ":" + "data/*[namespace-uri()='" + linkNamespace + "' and local-name()='" + linkName + "' and @xlink:role='" + linkRole + "']";
+ System.out.println(linkQuery);
FragmentList<ExtendedLink> links = this.<ExtendedLink>query(linkQuery);
// Get the arcs that declare the relationships in the network.
// For each arc map the ids of the fragments at their sources and targets.
HashMap<String,String> sourceIds = new HashMap<String,String>();
HashMap<String,String> targetIds = new HashMap<String,String>();
for (int i=0; i<links.getLength(); i++) {
ExtendedLink link = links.getFragment(i);
FragmentList<Arc> arcs = link.getArcs();
for (Arc arc: arcs) {
if (arc.getNamespaceURI().equals(arcNamespace))
if (arc.getLocalname().equals(arcName))
if (arc.getArcrole().equals(arcRole)) {
FragmentList<ArcEnd> sources = arc.getSourceFragments();
FragmentList<ArcEnd> targets = arc.getTargetFragments();
for (int k=0; k<sources.getLength(); k++) {
sourceIds.put(sources.getFragment(k).getFragmentIndex(),"");
}
for (int k=0; k<sources.getLength(); k++) {
targetIds.put(targets.getFragment(k).getFragmentIndex(),"");
}
}
}
}
// Get the root resources in the network
FragmentList<Fragment> roots = new FragmentListImpl<Fragment>();
Set<String> ids = sourceIds.keySet();
Iterator<String> iterator = sourceIds.keySet().iterator();
while (iterator.hasNext()) {
String id = iterator.next();
if (! targetIds.containsKey(id)) {
roots.addFragment(this.getFragment(id));
}
}
return roots;
}
/**
* This implementation is not as strict as the XBRL 2.1 specification
* requires but it is generally faster and delivers sensible results.
* It will only fail if people use the same link role and arc role but
* rely on arc or link element differences to distinguish networks.<br/><br/>
*
* Implementation strategy is:<br/>
* 1. Get all extended link elements with the given link role.<br/>
* 2. Get all arcs with the given arc role.<br/>
* 3. Get all resources at the source of the arcs.<br/>
* 4. Return only those source resources that that are not target resources also.<br/>
*
* @param linkRole the role on the extended links that contain the network arcs.
* @param arcRole the arcrole on the arcs describing the network.
* @return The list of fragments for each of the resources that is identified as a root
* of the specified network (noting that a root resource is defined as a resource that is
* at the source of one or more relationships in the network and that is not at the target
* of any relationships in the network).
* @throws XBRLException
*/
public FragmentList<Fragment> getNetworkRoots(String linkRole, String arcRole) throws XBRLException {
// Get the links that contain the network declaring arcs.
String linkQuery = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment[@type='org.xbrlapi.impl.ExtendedLinkImpl']/"+ Constants.XBRLAPIPrefix+ ":" + "data/*[@xlink:role='" + linkRole + "']";
FragmentList<ExtendedLink> links = this.<ExtendedLink>query(linkQuery);
// Get the arcs that declare the relationships in the network.
// For each arc map the ids of the fragments at their sources and targets.
HashMap<String,String> sourceIds = new HashMap<String,String>();
HashMap<String,String> targetIds = new HashMap<String,String>();
for (int i=0; i<links.getLength(); i++) {
ExtendedLink link = links.getFragment(i);
FragmentList<Arc> arcs = link.getArcs();
for (Arc arc: arcs) {
if (arc.getArcrole().equals(arcRole)) {
FragmentList<ArcEnd> sources = arc.getSourceFragments();
FragmentList<ArcEnd> targets = arc.getTargetFragments();
for (int k=0; k<sources.getLength(); k++) {
sourceIds.put(sources.getFragment(k).getFragmentIndex(),"");
}
for (int k=0; k<sources.getLength(); k++) {
targetIds.put(targets.getFragment(k).getFragmentIndex(),"");
}
}
}
}
// Get the root resources in the network
FragmentList<Fragment> roots = new FragmentListImpl<Fragment>();
Set<String> ids = sourceIds.keySet();
Iterator<String> iterator = sourceIds.keySet().iterator();
while (iterator.hasNext()) {
String id = iterator.next();
if (! targetIds.containsKey(id)) {
roots.addFragment(this.getFragment(id));
}
}
return roots;
}
/**
* @param namespace The namespace for the concept.
* @param name The local name for the concept.
* @return the concept fragment for the specified namespace and name.
* @throws XBRLException if more than one matching concept is found in the data store
* or if no matching concepts are found in the data store.
*/
public Concept getConcept(String namespace, String name) throws XBRLException {
// TODO Make sure that non-concept element declarations are handled.
FragmentList<Concept> concepts = this.<Concept>query("/"+ Constants.XBRLAPIPrefix+ ":" + "fragment/"+ Constants.XBRLAPIPrefix+ ":" + "data/xsd:element[@name='" + name + "']");
FragmentList<Concept> matches = new FragmentListImpl<Concept>();
for (Concept concept: concepts) {
if (concept.getTargetNamespaceURI().equals(namespace)) {
matches.addFragment(concept);
}
}
if (matches.getLength() == 0)
throw new XBRLException("No matching concepts were found for " + namespace + ":" + name + ".");
if (matches.getLength() > 1)
throw new XBRLException(new Integer(matches.getLength()) + "matching concepts were found for " + namespace + ":" + name + ".");
return matches.getFragment(0);
}
/**
* @see org.xbrlapi.data.XBRLStore#getLinkRoles()
*/
public HashMap<String,String> getLinkRoles() throws XBRLException {
HashMap<String,String> roles = new HashMap<String,String>();
FragmentList<RoleType> types = this.getRoleTypes();
for (RoleType type: types) {
String role = type.getCustomURI();
String query = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment[@type='org.xbrlapi.impl.ExtendedLinkImpl' and "+ Constants.XBRLAPIPrefix+ ":" + "data/*/@xlink:role='" + role + "']";
FragmentList<ExtendedLink> links = this.<ExtendedLink>query(query);
if (links.getLength() > 0) {
roles.put(role,"");
}
}
return roles;
}
/**
* @see org.xbrlapi.data.XBRLStore#getArcRoles()
*/
public HashMap<String,String> getArcRoles() throws XBRLException {
// TODO Simplify getArcRoles method of the XBRLStore to eliminate need to get all arcs in the data store.
HashMap<String,String> roles = new HashMap<String,String>();
FragmentList<ArcroleType> types = this.getArcroleTypes();
for (ArcroleType type: types) {
String role = type.getCustomURI();
String query = "/"+ Constants.XBRLAPIPrefix + ":" + "fragment["+ Constants.XBRLAPIPrefix+ ":" + "data/*[@xlink:type='arc' and @xlink:arcrole='" + role + "']]";
FragmentList<Arc> arcs = this.<Arc>query(query);
if (arcs.getLength() > 0) {
roles.put(role,"");
}
}
return roles;
}
/**
* @see org.xbrlapi.data.XBRLStore#getLinkRoles(String)
*/
public HashMap<String,String> getLinkRoles(String arcrole) throws XBRLException {
HashMap<String,String> roles = new HashMap<String,String>();
HashMap<String,Fragment> links = new HashMap<String,Fragment>();
String query = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment["+ Constants.XBRLAPIPrefix+ ":" + "data/*[@xlink:type='arc' and @xlink:arcrole='" + arcrole + "']]";
FragmentList<Arc> arcs = this.<Arc>query(query);
for (Arc arc: arcs) {
if (! links.containsKey(arc.getParentIndex())) {
ExtendedLink link = arc.getExtendedLink();
links.put(link.getFragmentIndex(),link);
}
}
for (Fragment l: links.values()) {
ExtendedLink link = (ExtendedLink) l;
if (! roles.containsKey(link.getLinkRole())) {
roles.put(link.getLinkRole(),"");
}
}
return roles;
}
/**
* @return a list of roleType fragments
* @throws XBRLException
*/
public FragmentList<RoleType> getRoleTypes() throws XBRLException {
return this.<RoleType>getFragments("RoleType");
}
/**
* @see org.xbrlapi.data.XBRLStore#getRoleTypes(String)
*/
public FragmentList<RoleType> getRoleTypes(String uri) throws XBRLException {
String query = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment["+ Constants.XBRLAPIPrefix+ ":" + "data/link:roleType/@roleURI='" + uri + "']";
return this.<RoleType>query(query);
}
/**
* @return a list of ArcroleType fragments
* @throws XBRLException
*/
public FragmentList<ArcroleType> getArcroleTypes() throws XBRLException {
return this.<ArcroleType>getFragments("ArcroleType");
}
/**
* @return a list of arcroleType fragments that define a given arcrole.
* @throws XBRLException
*/
public FragmentList<ArcroleType> getArcroleTypes(String uri) throws XBRLException {
String query = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment["+ Constants.XBRLAPIPrefix+ ":" + "data/link:arcroleType/@arcroleURI='" + uri + "']";
return this.<ArcroleType>query(query);
}
/**
* @see org.xbrlapi.data.XBRLStore#getResourceRoles()
*/
public HashMap<String,String> getResourceRoles() throws XBRLException {
HashMap<String,String> roles = new HashMap<String,String>();
FragmentList<Resource> resources = this.<Resource>query("/"+ Constants.XBRLAPIPrefix+ ":" + "fragment["+ Constants.XBRLAPIPrefix+ ":" + "data/*/@xlink:type='resource']");
for (Resource resource: resources) {
String role = resource.getResourceRole();
if (! roles.containsKey(role)) roles.put(role,"");
}
return roles;
}
}
| true | true | public FragmentList<Fragment> getNetworkRoots(String linkNamespace, String linkName, String linkRole, String arcNamespace, String arcName, String arcRole) throws XBRLException {
// Get the links that contain the network declaring arcs.
String linkQuery = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment[@type='org.xbrlapi.impl.ExtendedLinkImpl']/"+ Constants.XBRLAPIPrefix+ ":" + "data/*[namespace-uri()='" + linkNamespace + "' and local-name()='" + linkName + "' and @xlink:role='" + linkRole + "']";
FragmentList<ExtendedLink> links = this.<ExtendedLink>query(linkQuery);
// Get the arcs that declare the relationships in the network.
// For each arc map the ids of the fragments at their sources and targets.
HashMap<String,String> sourceIds = new HashMap<String,String>();
HashMap<String,String> targetIds = new HashMap<String,String>();
for (int i=0; i<links.getLength(); i++) {
ExtendedLink link = links.getFragment(i);
FragmentList<Arc> arcs = link.getArcs();
for (Arc arc: arcs) {
if (arc.getNamespaceURI().equals(arcNamespace))
if (arc.getLocalname().equals(arcName))
if (arc.getArcrole().equals(arcRole)) {
FragmentList<ArcEnd> sources = arc.getSourceFragments();
FragmentList<ArcEnd> targets = arc.getTargetFragments();
for (int k=0; k<sources.getLength(); k++) {
sourceIds.put(sources.getFragment(k).getFragmentIndex(),"");
}
for (int k=0; k<sources.getLength(); k++) {
targetIds.put(targets.getFragment(k).getFragmentIndex(),"");
}
}
}
}
// Get the root resources in the network
FragmentList<Fragment> roots = new FragmentListImpl<Fragment>();
Set<String> ids = sourceIds.keySet();
Iterator<String> iterator = sourceIds.keySet().iterator();
while (iterator.hasNext()) {
String id = iterator.next();
if (! targetIds.containsKey(id)) {
roots.addFragment(this.getFragment(id));
}
}
return roots;
}
| public FragmentList<Fragment> getNetworkRoots(String linkNamespace, String linkName, String linkRole, String arcNamespace, String arcName, String arcRole) throws XBRLException {
// Get the links that contain the network declaring arcs.
String linkQuery = "/"+ Constants.XBRLAPIPrefix+ ":" + "fragment[@type='org.xbrlapi.impl.ExtendedLinkImpl' and "+ Constants.XBRLAPIPrefix+ ":" + "data/*[namespace-uri()='" + linkNamespace + "' and local-name()='" + linkName + "' and @xlink:role='" + linkRole + "']";
System.out.println(linkQuery);
FragmentList<ExtendedLink> links = this.<ExtendedLink>query(linkQuery);
// Get the arcs that declare the relationships in the network.
// For each arc map the ids of the fragments at their sources and targets.
HashMap<String,String> sourceIds = new HashMap<String,String>();
HashMap<String,String> targetIds = new HashMap<String,String>();
for (int i=0; i<links.getLength(); i++) {
ExtendedLink link = links.getFragment(i);
FragmentList<Arc> arcs = link.getArcs();
for (Arc arc: arcs) {
if (arc.getNamespaceURI().equals(arcNamespace))
if (arc.getLocalname().equals(arcName))
if (arc.getArcrole().equals(arcRole)) {
FragmentList<ArcEnd> sources = arc.getSourceFragments();
FragmentList<ArcEnd> targets = arc.getTargetFragments();
for (int k=0; k<sources.getLength(); k++) {
sourceIds.put(sources.getFragment(k).getFragmentIndex(),"");
}
for (int k=0; k<sources.getLength(); k++) {
targetIds.put(targets.getFragment(k).getFragmentIndex(),"");
}
}
}
}
// Get the root resources in the network
FragmentList<Fragment> roots = new FragmentListImpl<Fragment>();
Set<String> ids = sourceIds.keySet();
Iterator<String> iterator = sourceIds.keySet().iterator();
while (iterator.hasNext()) {
String id = iterator.next();
if (! targetIds.containsKey(id)) {
roots.addFragment(this.getFragment(id));
}
}
return roots;
}
|
diff --git a/source/org/jbubblebreaker/bubbles/Bubble3DCircle.java b/source/org/jbubblebreaker/bubbles/Bubble3DCircle.java
index 612c5d2..fe08dee 100644
--- a/source/org/jbubblebreaker/bubbles/Bubble3DCircle.java
+++ b/source/org/jbubblebreaker/bubbles/Bubble3DCircle.java
@@ -1,92 +1,91 @@
/*
* Copyright 2008 Sven Strickroth <[email protected]>
*
* This file is part of jBubbleBreaker.
*
* jBubbleBreaker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* jBubbleBreaker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with jBubbleBreaker. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jbubblebreaker.bubbles;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Provides 3D Circle Bubbles
* @author Sven Strickroth
*/
@SuppressWarnings("serial")
public class Bubble3DCircle extends BubbleDefault {
/**
* Stores the name of this bubble set
*/
static public String name = "3DCircle";
/**
* Buffer the image
*/
static private Image[] image = {null, null, null, null, null};
/**
* store the last radius
*/
static private int oldradius = 0;
/**
* Create a Bubble on a specific position and size with a random color
* @param radius radius of Bubble
* @param row Row of Bubble
* @param col Column of Bubble
*/
public Bubble3DCircle(int radius, int row, int col) {
super(radius, row, col);
}
/**
* Create a Bubble on a specific position, size and color
* @param radius radius of Bubble
* @param row Row of Bubble
* @param col Column of Bubble
* @param colorIndex color index for new Bubble, if this colorIndex is not valid a random color is used
*/
public Bubble3DCircle(int radius, int row, int col, int colorIndex) {
super(radius, row, col, colorIndex);
}
@Override
public String getName() {
return name;
}
@Override
public void paint(Graphics g) {
- g.clearRect(0, 0, radius, radius);
if (isMarked() == true) {
g.setColor(Color.GRAY);
g.fillRect(0, 0, radius, radius);
}
if (image[0] == null || radius != oldradius) {
String[] filenames = {"bubble-red","bubble-blue","bubble-yellow"
,"bubble-magenta","bubble-green"};
for(int i = 0; i < 5; i++) {
try {
image[i] = ImageIO.read(getClass().getResource("/images/"+filenames[i]+".png")).getScaledInstance(radius, radius, Image.SCALE_SMOOTH);
} catch (IOException e) {
// should not occour
}
}
oldradius = radius;
}
g.drawImage(image[getColorIndex()], 0, 0, this);
}
}
| true | true | public void paint(Graphics g) {
g.clearRect(0, 0, radius, radius);
if (isMarked() == true) {
g.setColor(Color.GRAY);
g.fillRect(0, 0, radius, radius);
}
if (image[0] == null || radius != oldradius) {
String[] filenames = {"bubble-red","bubble-blue","bubble-yellow"
,"bubble-magenta","bubble-green"};
for(int i = 0; i < 5; i++) {
try {
image[i] = ImageIO.read(getClass().getResource("/images/"+filenames[i]+".png")).getScaledInstance(radius, radius, Image.SCALE_SMOOTH);
} catch (IOException e) {
// should not occour
}
}
oldradius = radius;
}
g.drawImage(image[getColorIndex()], 0, 0, this);
}
| public void paint(Graphics g) {
if (isMarked() == true) {
g.setColor(Color.GRAY);
g.fillRect(0, 0, radius, radius);
}
if (image[0] == null || radius != oldradius) {
String[] filenames = {"bubble-red","bubble-blue","bubble-yellow"
,"bubble-magenta","bubble-green"};
for(int i = 0; i < 5; i++) {
try {
image[i] = ImageIO.read(getClass().getResource("/images/"+filenames[i]+".png")).getScaledInstance(radius, radius, Image.SCALE_SMOOTH);
} catch (IOException e) {
// should not occour
}
}
oldradius = radius;
}
g.drawImage(image[getColorIndex()], 0, 0, this);
}
|
diff --git a/IslandCraft-Dynmap/src/main/java/com/github/hoqhuuep/islandcraft/dynmap/IslandListener.java b/IslandCraft-Dynmap/src/main/java/com/github/hoqhuuep/islandcraft/dynmap/IslandListener.java
index 463dd20..396407e 100644
--- a/IslandCraft-Dynmap/src/main/java/com/github/hoqhuuep/islandcraft/dynmap/IslandListener.java
+++ b/IslandCraft-Dynmap/src/main/java/com/github/hoqhuuep/islandcraft/dynmap/IslandListener.java
@@ -1,74 +1,76 @@
package com.github.hoqhuuep.islandcraft.dynmap;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.dynmap.markers.AreaMarker;
import org.dynmap.markers.MarkerSet;
import com.github.hoqhuuep.islandcraft.realestate.IslandDeed;
import com.github.hoqhuuep.islandcraft.realestate.IslandStatus;
import com.github.hoqhuuep.islandcraft.realestate.SerializableLocation;
import com.github.hoqhuuep.islandcraft.realestate.SerializableRegion;
import com.github.hoqhuuep.islandcraft.realestate.event.IslandAbandonEvent;
import com.github.hoqhuuep.islandcraft.realestate.event.IslandLoadEvent;
import com.github.hoqhuuep.islandcraft.realestate.event.IslandPurchaseEvent;
import com.github.hoqhuuep.islandcraft.realestate.event.IslandRepossessEvent;
public class IslandListener implements Listener {
final MarkerSet markerSet;
public IslandListener(MarkerSet markerSet) {
this.markerSet = markerSet;
}
@EventHandler
public void onIslandLoad(final IslandLoadEvent event) {
updateMarker(event.getDeed());
}
@EventHandler
public void onIslandPurchase(final IslandPurchaseEvent event) {
updateMarker(event.getDeed());
}
@EventHandler
public void onIslandAbandon(final IslandAbandonEvent event) {
updateMarker(event.getDeed());
}
@EventHandler
public void onIslandRepossess(final IslandRepossessEvent event) {
updateMarker(event.getDeed());
}
private void updateMarker(final IslandDeed deed) {
final IslandStatus status = deed.getStatus();
final SerializableLocation island = deed.getId();
final String id = island.getWorld() + "'" + island.getX() + "'" + island.getY() + "'" + island.getZ();
final SerializableRegion region = deed.getInnerRegion();
final double[] xs = {region.getMinX(), region.getMinX(), region.getMaxX(), region.getMaxX()};
final double[] zs = {region.getMinZ(), region.getMaxZ(), region.getMaxZ(), region.getMinZ()};
- final String label = "<strong>" + deed.getTitle() + "</strong>\n<br />\nStatus: " + status + "\n<br />\nOwner: " + deed.getOwner() + "\n<br />\nTax: "
+ final String label = deed.getTitle();
+ final String description = "<strong>" + deed.getTitle() + "</strong><br />Status: " + status + "<br />Owner: " + deed.getOwner() + "<br />Tax: "
+ deed.getTax();
AreaMarker areaMarker = markerSet.findAreaMarker(id);
if (areaMarker == null) {
- areaMarker = markerSet.createAreaMarker(id, label, true, island.getWorld(), xs, zs, true);
+ areaMarker = markerSet.createAreaMarker(id, label, false, island.getWorld(), xs, zs, true);
} else {
- areaMarker.setLabel(label, true);
+ areaMarker.setLabel(label, false);
}
+ areaMarker.setDescription(description);
if (status == IslandStatus.PRIVATE) {
areaMarker.setFillStyle(0.25, 0x0000FF);
areaMarker.setLineStyle(2, 0.5, 0x0000FF);
} else if (status == IslandStatus.NEW) {
areaMarker.setFillStyle(0.25, 0xFFFF00);
areaMarker.setLineStyle(2, 0.5, 0xFFFF00);
} else if (status == IslandStatus.RESOURCE) {
areaMarker.setFillStyle(0.25, 0x00FF00);
areaMarker.setLineStyle(2, 0.5, 0x00FF00);
} else {
areaMarker.setFillStyle(0.25, 0xFF0000);
areaMarker.setLineStyle(2, 0.5, 0xFF0000);
}
}
}
| false | true | private void updateMarker(final IslandDeed deed) {
final IslandStatus status = deed.getStatus();
final SerializableLocation island = deed.getId();
final String id = island.getWorld() + "'" + island.getX() + "'" + island.getY() + "'" + island.getZ();
final SerializableRegion region = deed.getInnerRegion();
final double[] xs = {region.getMinX(), region.getMinX(), region.getMaxX(), region.getMaxX()};
final double[] zs = {region.getMinZ(), region.getMaxZ(), region.getMaxZ(), region.getMinZ()};
final String label = "<strong>" + deed.getTitle() + "</strong>\n<br />\nStatus: " + status + "\n<br />\nOwner: " + deed.getOwner() + "\n<br />\nTax: "
+ deed.getTax();
AreaMarker areaMarker = markerSet.findAreaMarker(id);
if (areaMarker == null) {
areaMarker = markerSet.createAreaMarker(id, label, true, island.getWorld(), xs, zs, true);
} else {
areaMarker.setLabel(label, true);
}
if (status == IslandStatus.PRIVATE) {
areaMarker.setFillStyle(0.25, 0x0000FF);
areaMarker.setLineStyle(2, 0.5, 0x0000FF);
} else if (status == IslandStatus.NEW) {
areaMarker.setFillStyle(0.25, 0xFFFF00);
areaMarker.setLineStyle(2, 0.5, 0xFFFF00);
} else if (status == IslandStatus.RESOURCE) {
areaMarker.setFillStyle(0.25, 0x00FF00);
areaMarker.setLineStyle(2, 0.5, 0x00FF00);
} else {
areaMarker.setFillStyle(0.25, 0xFF0000);
areaMarker.setLineStyle(2, 0.5, 0xFF0000);
}
}
| private void updateMarker(final IslandDeed deed) {
final IslandStatus status = deed.getStatus();
final SerializableLocation island = deed.getId();
final String id = island.getWorld() + "'" + island.getX() + "'" + island.getY() + "'" + island.getZ();
final SerializableRegion region = deed.getInnerRegion();
final double[] xs = {region.getMinX(), region.getMinX(), region.getMaxX(), region.getMaxX()};
final double[] zs = {region.getMinZ(), region.getMaxZ(), region.getMaxZ(), region.getMinZ()};
final String label = deed.getTitle();
final String description = "<strong>" + deed.getTitle() + "</strong><br />Status: " + status + "<br />Owner: " + deed.getOwner() + "<br />Tax: "
+ deed.getTax();
AreaMarker areaMarker = markerSet.findAreaMarker(id);
if (areaMarker == null) {
areaMarker = markerSet.createAreaMarker(id, label, false, island.getWorld(), xs, zs, true);
} else {
areaMarker.setLabel(label, false);
}
areaMarker.setDescription(description);
if (status == IslandStatus.PRIVATE) {
areaMarker.setFillStyle(0.25, 0x0000FF);
areaMarker.setLineStyle(2, 0.5, 0x0000FF);
} else if (status == IslandStatus.NEW) {
areaMarker.setFillStyle(0.25, 0xFFFF00);
areaMarker.setLineStyle(2, 0.5, 0xFFFF00);
} else if (status == IslandStatus.RESOURCE) {
areaMarker.setFillStyle(0.25, 0x00FF00);
areaMarker.setLineStyle(2, 0.5, 0x00FF00);
} else {
areaMarker.setFillStyle(0.25, 0xFF0000);
areaMarker.setLineStyle(2, 0.5, 0xFF0000);
}
}
|
diff --git a/src/java/axiom/objectmodel/dom/UrlAnalyzer.java b/src/java/axiom/objectmodel/dom/UrlAnalyzer.java
index 930d7c7..31d126e 100644
--- a/src/java/axiom/objectmodel/dom/UrlAnalyzer.java
+++ b/src/java/axiom/objectmodel/dom/UrlAnalyzer.java
@@ -1,59 +1,61 @@
package axiom.objectmodel.dom;
import java.io.IOException;
import java.io.Reader;
import java.util.regex.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
public class UrlAnalyzer extends Analyzer {
public TokenStream tokenStream(String fieldName, final Reader reader) {
return new TokenStream() {
private final Pattern stripTokens = Pattern.compile("^(http:/|www|com|org|net)");
private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$");
private boolean done = false;
public Token next() throws IOException {
if(!done){
final char[] buffer = new char[1];
StringBuffer sb = new StringBuffer();
int length = 0;
Matcher matcher = endTokens.matcher(sb);
boolean found = matcher.find();
while (!found && (length = reader.read(buffer)) != -1) {
sb.append(buffer, 0, length);
Matcher startMatcher = stripTokens.matcher(sb);
if(startMatcher.matches()){
// strip prefix
String tmp = sb.toString();
sb = new StringBuffer(tmp.replaceFirst("^(http:/|www|com|org|net)", ""));
}
matcher = endTokens.matcher(sb);
found = matcher.find();
if(found){
- final String text = sb.toString().substring(0, matcher.end()-1);
+ final String text = sb.toString().substring(0, matcher.end()-1).toLowerCase();
int len = text.length();
if(len > 0){
// matched a token
+ System.out.println("-- token: ["+text+"]");
return new Token(text, 0, len);
} else {
// only contains a stop token, continue reading
sb = new StringBuffer();
found = false;
}
}
}
// at end of string
done = true;
- final String value = sb.toString();
+ final String value = sb.toString().toLowerCase();
+ System.out.println("-- token: ["+value+"]");
return new Token(value, 0, value.length());
}
return null;
}
};
}
}
| false | true | public TokenStream tokenStream(String fieldName, final Reader reader) {
return new TokenStream() {
private final Pattern stripTokens = Pattern.compile("^(http:/|www|com|org|net)");
private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$");
private boolean done = false;
public Token next() throws IOException {
if(!done){
final char[] buffer = new char[1];
StringBuffer sb = new StringBuffer();
int length = 0;
Matcher matcher = endTokens.matcher(sb);
boolean found = matcher.find();
while (!found && (length = reader.read(buffer)) != -1) {
sb.append(buffer, 0, length);
Matcher startMatcher = stripTokens.matcher(sb);
if(startMatcher.matches()){
// strip prefix
String tmp = sb.toString();
sb = new StringBuffer(tmp.replaceFirst("^(http:/|www|com|org|net)", ""));
}
matcher = endTokens.matcher(sb);
found = matcher.find();
if(found){
final String text = sb.toString().substring(0, matcher.end()-1);
int len = text.length();
if(len > 0){
// matched a token
return new Token(text, 0, len);
} else {
// only contains a stop token, continue reading
sb = new StringBuffer();
found = false;
}
}
}
// at end of string
done = true;
final String value = sb.toString();
return new Token(value, 0, value.length());
}
return null;
}
};
}
| public TokenStream tokenStream(String fieldName, final Reader reader) {
return new TokenStream() {
private final Pattern stripTokens = Pattern.compile("^(http:/|www|com|org|net)");
private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$");
private boolean done = false;
public Token next() throws IOException {
if(!done){
final char[] buffer = new char[1];
StringBuffer sb = new StringBuffer();
int length = 0;
Matcher matcher = endTokens.matcher(sb);
boolean found = matcher.find();
while (!found && (length = reader.read(buffer)) != -1) {
sb.append(buffer, 0, length);
Matcher startMatcher = stripTokens.matcher(sb);
if(startMatcher.matches()){
// strip prefix
String tmp = sb.toString();
sb = new StringBuffer(tmp.replaceFirst("^(http:/|www|com|org|net)", ""));
}
matcher = endTokens.matcher(sb);
found = matcher.find();
if(found){
final String text = sb.toString().substring(0, matcher.end()-1).toLowerCase();
int len = text.length();
if(len > 0){
// matched a token
System.out.println("-- token: ["+text+"]");
return new Token(text, 0, len);
} else {
// only contains a stop token, continue reading
sb = new StringBuffer();
found = false;
}
}
}
// at end of string
done = true;
final String value = sb.toString().toLowerCase();
System.out.println("-- token: ["+value+"]");
return new Token(value, 0, value.length());
}
return null;
}
};
}
|
diff --git a/src/se/mah/kd330a/project/itsl/FragmentITSL.java b/src/se/mah/kd330a/project/itsl/FragmentITSL.java
index 02baa2b..f65b2cc 100644
--- a/src/se/mah/kd330a/project/itsl/FragmentITSL.java
+++ b/src/se/mah/kd330a/project/itsl/FragmentITSL.java
@@ -1,273 +1,278 @@
package se.mah.kd330a.project.itsl;
import se.mah.kd330a.project.R;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
import android.app.FragmentTransaction;
public class FragmentITSL extends Fragment implements
FeedManager.FeedManagerDoneListener,
ActionBar.TabListener
{
private static final String TAG = "FragmentITSL";
private static final long UPDATE_INTERVAL = 600000; // every ten minute
private ActionBar actionBar;
private FeedManager feedManager;
private ProgressDialog dialog;
private PendingIntent backgroundUpdateIntent;
private ViewPager mViewPager;
private ListPagerAdapter listPagerAdapter;
private ViewGroup rootView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/*
* Set up the repeating task of updating data in the background
*/
Context appContext = getActivity().getApplicationContext();
backgroundUpdateIntent = PendingIntent.getService(appContext, 0, new Intent(appContext, TimeAlarm.class), 0);
feedManager = new FeedManager(this, appContext);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_itsl, container, false);
actionBar = getActivity().getActionBar();
/*
* In case there is nothing in the cache, or it doesn't exist
* we have to refresh
*/
if (!feedManager.loadCache())
refresh();
return rootView;
}
public void onResume()
{
super.onResume();
Log.i(TAG, "Resumed: Stopping background updates");
AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarm.cancel(backgroundUpdateIntent);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
public void onPause()
{
super.onPause();
Log.i(TAG, "Paused: Setting up background updates");
AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + UPDATE_INTERVAL, UPDATE_INTERVAL, backgroundUpdateIntent);
/*
* Removes tabs and everything associated with it.
*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
/*
* Remember when we last had this view opened
*/
Date date = new Date(System.currentTimeMillis());
/*
date.setMonth(9); // zero based index (e.g. 0-11)
date.setDate(20);
*/
Util.setLatestUpdate(getActivity().getApplicationContext(), date);
}
public class FeedObject
{
public ArrayList<Article> articles;
public FeedObject()
{
articles = new ArrayList<Article>();
}
}
public HashMap<String, FeedObject> getFeedObjects()
{
HashMap<String, FeedObject> foList = new HashMap<String, FeedObject>();
for (Article a : feedManager.getArticles())
{
FeedObject fo;
if (foList.containsKey(a.getArticleCourseCode()))
{
fo = foList.get(a.getArticleCourseCode());
}
else
{
fo = new FeedObject();
foList.put(a.getArticleCourseCode(), fo);
}
fo.articles.add(a);
}
return foList;
}
/**
* Creates tabs in the actionbar and the fragments associated with them.
*
* @return ArrayList of fragments
*/
private ArrayList<TabFragment> createFragments()
{
ArrayList<TabFragment> fragments = new ArrayList<TabFragment>();
Bundle b = new Bundle();
HashMap<String, FeedObject> foList = getFeedObjects();
actionBar.removeAllTabs();
/*
* The first tab contains everything unfiltered
actionBar.addTab(
actionBar.newTab()
.setText("All")
.setTabListener(this));
fragments.add(new TabFragment(feedManager.getArticles()));
*/
/*
* For all feeds we have downloaded, create a new tab and add the
* corresponding data to a new TabFragment
*/
if (!foList.isEmpty()){
TabFragment fragment;
for (String title : foList.keySet())
{
+ String titleDisp = "course name";
+ try{
String[] parts = title.split("-");
- String titleDisp=parts[2].substring(1, parts[2].length()-1);
+ titleDisp=parts[2].substring(1, parts[2].length()-1);}
+ catch(Exception e){
+ titleDisp=title;
+ }
actionBar.addTab(
actionBar.newTab()
.setText(titleDisp)
.setTabListener(this));
fragment = new TabFragment();
fragment.setArticles(foList.get(title).articles);
b.putBoolean("isEmpty", false);
fragment.setArguments(b);
fragments.add(fragment);
Log.i(TAG, "Filtered map key => tab title is: " + title);
}
}
else{
actionBar.addTab(
actionBar.newTab()
.setText("Set up It's Learning")
.setTabListener(this));
TabFragment fragment = new TabFragment();
fragment.setArticles(null);
b.putBoolean("isEmpty", true);
fragment.setArguments(b);
fragments.add(fragment);
}
return fragments;
}
public void onFeedManagerProgress(FeedManager fm, int progress, int max)
{
/*
* set up progress dialog if there isn't one.
*/
if (dialog == null)
{
dialog = new ProgressDialog(getActivity());
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Downloading...");
dialog.show();
}
dialog.setProgress(progress);
dialog.setMax(max);
}
@Override
public void onFeedManagerDone(FeedManager fm, ArrayList<Article> articles)
{
if (dialog != null)
{
dialog.dismiss();
dialog = null;
}
/*
* Set up tabs in the actionbar
*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
listPagerAdapter = new ListPagerAdapter(getActivity().getSupportFragmentManager(), createFragments());
mViewPager.setAdapter(listPagerAdapter);
//Toast.makeText(getActivity(), "" + articles.size() + " articles", Toast.LENGTH_LONG).show();
}
private void refresh()
{
feedManager.reset();
feedManager.processFeeds();
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
/*
* here we retrieve the tabfragment object that should already have
* been initialized and added to the adapter
*/
if (mViewPager != null)
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
}
}
| false | true | private ArrayList<TabFragment> createFragments()
{
ArrayList<TabFragment> fragments = new ArrayList<TabFragment>();
Bundle b = new Bundle();
HashMap<String, FeedObject> foList = getFeedObjects();
actionBar.removeAllTabs();
/*
* The first tab contains everything unfiltered
actionBar.addTab(
actionBar.newTab()
.setText("All")
.setTabListener(this));
fragments.add(new TabFragment(feedManager.getArticles()));
*/
/*
* For all feeds we have downloaded, create a new tab and add the
* corresponding data to a new TabFragment
*/
if (!foList.isEmpty()){
TabFragment fragment;
for (String title : foList.keySet())
{
String[] parts = title.split("-");
String titleDisp=parts[2].substring(1, parts[2].length()-1);
actionBar.addTab(
actionBar.newTab()
.setText(titleDisp)
.setTabListener(this));
fragment = new TabFragment();
fragment.setArticles(foList.get(title).articles);
b.putBoolean("isEmpty", false);
fragment.setArguments(b);
fragments.add(fragment);
Log.i(TAG, "Filtered map key => tab title is: " + title);
}
}
else{
actionBar.addTab(
actionBar.newTab()
.setText("Set up It's Learning")
.setTabListener(this));
TabFragment fragment = new TabFragment();
fragment.setArticles(null);
b.putBoolean("isEmpty", true);
fragment.setArguments(b);
fragments.add(fragment);
}
return fragments;
}
| private ArrayList<TabFragment> createFragments()
{
ArrayList<TabFragment> fragments = new ArrayList<TabFragment>();
Bundle b = new Bundle();
HashMap<String, FeedObject> foList = getFeedObjects();
actionBar.removeAllTabs();
/*
* The first tab contains everything unfiltered
actionBar.addTab(
actionBar.newTab()
.setText("All")
.setTabListener(this));
fragments.add(new TabFragment(feedManager.getArticles()));
*/
/*
* For all feeds we have downloaded, create a new tab and add the
* corresponding data to a new TabFragment
*/
if (!foList.isEmpty()){
TabFragment fragment;
for (String title : foList.keySet())
{
String titleDisp = "course name";
try{
String[] parts = title.split("-");
titleDisp=parts[2].substring(1, parts[2].length()-1);}
catch(Exception e){
titleDisp=title;
}
actionBar.addTab(
actionBar.newTab()
.setText(titleDisp)
.setTabListener(this));
fragment = new TabFragment();
fragment.setArticles(foList.get(title).articles);
b.putBoolean("isEmpty", false);
fragment.setArguments(b);
fragments.add(fragment);
Log.i(TAG, "Filtered map key => tab title is: " + title);
}
}
else{
actionBar.addTab(
actionBar.newTab()
.setText("Set up It's Learning")
.setTabListener(this));
TabFragment fragment = new TabFragment();
fragment.setArticles(null);
b.putBoolean("isEmpty", true);
fragment.setArguments(b);
fragments.add(fragment);
}
return fragments;
}
|
diff --git a/src/relop/SimpleJoin.java b/src/relop/SimpleJoin.java
index 4598a2f..97b3681 100644
--- a/src/relop/SimpleJoin.java
+++ b/src/relop/SimpleJoin.java
@@ -1,118 +1,119 @@
package relop;
import java.util.Arrays;
/**
* The simplest of all join algorithms: nested loops (see textbook, 3rd edition,
* section 14.4.1, page 454).
*/
public class SimpleJoin extends Iterator {
Iterator left, right;
Predicate[] preds;
Tuple next;
Schema mergedSchema;
/**
* Constructs a join, given the left and right iterators and join predicates
* (relative to the combined schema).
*/
public SimpleJoin(Iterator left, Iterator right, Predicate... preds)
{
this.right = right;
this.left = left;
this.preds = preds;
mergedSchema = Schema.join(left.getSchema(), right.getSchema());
calcNext();
}
/**
* Gives a one-line explaination of the iterator, repeats the call on any
* child iterators, and increases the indent depth along the way.
*/
public void explain(int depth)
{
System.out.println("SimpleJoin : " + Arrays.toString(preds));
left.explain(depth + 1);
right.explain(depth + 1);
}
/**
* Restarts the iterator, i.e. as if it were just constructed.
*/
public void restart()
{
left.restart();
right.restart();
}
/**
* Returns true if the iterator is open; false otherwise.
*/
public boolean isOpen()
{
return left.isOpen() && right.isOpen();
}
/**
* Closes the iterator, releasing any resources (i.e. pinned pages).
*/
public void close()
{
left.close();
right.close();
}
/**
* Returns true if there are more tuples, false otherwise.
*/
public boolean hasNext()
{
return next != null;
}
/**
* Gets the next tuple in the iteration.
*
* @throws IllegalStateException
* if no more tuples
*/
public Tuple getNext()
{
if (next == null || !isOpen())
throw new IllegalStateException("No more tuples");
Tuple ret = next;
calcNext();
return ret;
}
private void calcNext()
{
Tuple candidate = null;
while (left.hasNext())
{
- if (right.hasNext())
+ Tuple leftTuple = left.getNext();
+ while(right.hasNext())
{
// merge right and left tuples
- candidate = Tuple.join(left.getNext(), right.getNext(),
+ candidate = Tuple.join(leftTuple, right.getNext(),
mergedSchema);
boolean valid = true;
// check this candidate with each merge condition (Predicate)
for (Predicate pred : preds)
{
// check this predicate
valid = pred.evaluate(candidate);
if (!valid)
break; // invalid candidate
}
if (!valid)
candidate = null; // invalid candidate
else
break; // valid candidate
- } else
- break; // no more tuples in the right iterator so will break
+ }
+ right.restart();
}
next = candidate;
}
} // public class SimpleJoin extends Iterator
| false | true | private void calcNext()
{
Tuple candidate = null;
while (left.hasNext())
{
if (right.hasNext())
{
// merge right and left tuples
candidate = Tuple.join(left.getNext(), right.getNext(),
mergedSchema);
boolean valid = true;
// check this candidate with each merge condition (Predicate)
for (Predicate pred : preds)
{
// check this predicate
valid = pred.evaluate(candidate);
if (!valid)
break; // invalid candidate
}
if (!valid)
candidate = null; // invalid candidate
else
break; // valid candidate
} else
break; // no more tuples in the right iterator so will break
}
next = candidate;
}
| private void calcNext()
{
Tuple candidate = null;
while (left.hasNext())
{
Tuple leftTuple = left.getNext();
while(right.hasNext())
{
// merge right and left tuples
candidate = Tuple.join(leftTuple, right.getNext(),
mergedSchema);
boolean valid = true;
// check this candidate with each merge condition (Predicate)
for (Predicate pred : preds)
{
// check this predicate
valid = pred.evaluate(candidate);
if (!valid)
break; // invalid candidate
}
if (!valid)
candidate = null; // invalid candidate
else
break; // valid candidate
}
right.restart();
}
next = candidate;
}
|
diff --git a/client/src/main/java/albin/oredev/year2012/server/model/SpeakerDTO.java b/client/src/main/java/albin/oredev/year2012/server/model/SpeakerDTO.java
index 5c249ab..a86204f 100644
--- a/client/src/main/java/albin/oredev/year2012/server/model/SpeakerDTO.java
+++ b/client/src/main/java/albin/oredev/year2012/server/model/SpeakerDTO.java
@@ -1,27 +1,30 @@
package albin.oredev.year2012.server.model;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import albin.oredev.year2012.model.Speaker;
@Root(strict = false, name="speaker")
public class SpeakerDTO {
@Attribute
private String id;
@Attribute
private String name;
@Attribute
private String photoFile;
@Element
private String biography;
public Speaker toSpeaker() {
+ if (biography != null && biography.indexOf("\n") >= 0) {
+ biography = biography.replace("\n", " ");
+ }
return new Speaker(id, name, photoFile, biography);
}
}
| true | true | public Speaker toSpeaker() {
return new Speaker(id, name, photoFile, biography);
}
| public Speaker toSpeaker() {
if (biography != null && biography.indexOf("\n") >= 0) {
biography = biography.replace("\n", " ");
}
return new Speaker(id, name, photoFile, biography);
}
|
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index 52bf3662d..891d7727a 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -1,749 +1,750 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.wifi;
import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
import com.android.settings.ProgressCategoryBase;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsResult;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WpsConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings.Secure;
import android.provider.Settings;
import android.security.Credentials;
import android.security.KeyStore;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This currently provides three types of UI.
*
* Two are for phones with relatively small screens: "for SetupWizard" and "for usual Settings".
* Users just need to launch WifiSettings Activity as usual. The request will be appropriately
* handled by ActivityManager, and they will have appropriate look-and-feel with this fragment.
*
* Third type is for Setup Wizard with X-Large, landscape UI. Users need to launch
* {@link WifiSettingsForSetupWizardXL} Activity, which contains this fragment but also has
* other decorations specific to that screen.
*/
public class WifiSettings extends SettingsPreferenceFragment
implements DialogInterface.OnClickListener, Preference.OnPreferenceChangeListener {
private static final int MENU_ID_SCAN = Menu.FIRST;
private static final int MENU_ID_ADVANCED = Menu.FIRST + 1;
private static final int MENU_ID_CONNECT = Menu.FIRST + 2;
private static final int MENU_ID_FORGET = Menu.FIRST + 3;
private static final int MENU_ID_MODIFY = Menu.FIRST + 4;
private static final String KEY_SLEEP_POLICY = "sleep_policy";
private final IntentFilter mFilter;
private final BroadcastReceiver mReceiver;
private final Scanner mScanner;
private WifiManager mWifiManager;
private WifiEnabler mWifiEnabler;
private CheckBoxPreference mNotifyOpenNetworks;
private ProgressCategoryBase mAccessPoints;
private Preference mAddNetwork;
// An access point being editted is stored here.
private AccessPoint mSelectedAccessPoint;
private boolean mEdit;
private DetailedState mLastState;
private WifiInfo mLastInfo;
private AtomicBoolean mConnected = new AtomicBoolean(false);
private int mKeyStoreNetworkId = INVALID_NETWORK_ID;
private WifiDialog mDialog;
/* Used in Wifi Setup context */
// this boolean extra specifies whether to disable the Next button when not connected
private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
// should Next button only be enabled when we have a connection?
private boolean mEnableNextOnConnection;
private boolean mInXlSetupWizard;
/* End of "used in Wifi Setup context" */
public WifiSettings() {
mFilter = new IntentFilter();
mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mFilter.addAction(WifiManager.ERROR_ACTION);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
handleEvent(context, intent);
}
};
mScanner = new Scanner();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mInXlSetupWizard = (activity instanceof WifiSettingsForSetupWizardXL);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mInXlSetupWizard) {
return inflater.inflate(R.layout.custom_preference_list_fragment, container, false);
} else {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// We don't call super.onActivityCreated() here, since it assumes we already set up
// Preference (probably in onCreate()), while WifiSettings exceptionally set it up in
// this method.
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final Activity activity = getActivity();
final Intent intent = activity.getIntent();
// if we're supposed to enable/disable the Next button based on our current connection
// state, start it off in the right state
mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
// Avoid re-adding on returning from an overlapping activity/fragment.
if (getPreferenceScreen() == null || getPreferenceScreen().getPreferenceCount() < 2) {
if (mEnableNextOnConnection) {
if (hasNextButton()) {
final ConnectivityManager connectivity = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getNetworkInfo(
ConnectivityManager.TYPE_WIFI);
changeNextButtonState(info.isConnected());
}
}
}
if (mInXlSetupWizard) {
addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl);
} else if (intent.getBooleanExtra("only_access_points", false)) {
addPreferencesFromResource(R.xml.wifi_access_points);
} else {
addPreferencesFromResource(R.xml.wifi_settings);
mWifiEnabler = new WifiEnabler(activity,
(CheckBoxPreference) findPreference("enable_wifi"));
mNotifyOpenNetworks =
(CheckBoxPreference) findPreference("notify_open_networks");
mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
}
// This may be either ProgressCategory or AccessPointCategoryForXL.
final ProgressCategoryBase preference =
(ProgressCategoryBase) findPreference("access_points");
mAccessPoints = preference;
mAccessPoints.setOrderingAsAdded(false);
mAddNetwork = findPreference("add_network");
ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
if (pref != null) {
if (Utils.isWifiOnly()) {
pref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
+ pref.setSummary(R.string.wifi_setting_sleep_policy_summary_wifi_only);
}
pref.setOnPreferenceChangeListener(this);
int value = Settings.System.getInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
pref.setValue(String.valueOf(value));
}
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
// After confirming PreferenceScreen is available, we call super.
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
if (mWifiEnabler != null) {
mWifiEnabler.resume();
}
getActivity().registerReceiver(mReceiver, mFilter);
if (mKeyStoreNetworkId != INVALID_NETWORK_ID &&
KeyStore.getInstance().test() == KeyStore.NO_ERROR) {
mWifiManager.connectNetwork(mKeyStoreNetworkId);
}
mKeyStoreNetworkId = INVALID_NETWORK_ID;
updateAccessPoints();
}
@Override
public void onPause() {
super.onPause();
if (mWifiEnabler != null) {
mWifiEnabler.pause();
}
getActivity().unregisterReceiver(mReceiver);
mScanner.pause();
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// We don't want menus in Setup Wizard XL.
if (!mInXlSetupWizard) {
menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
.setIcon(R.drawable.ic_menu_scan_network);
menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
.setIcon(android.R.drawable.ic_menu_manage);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ID_SCAN:
if (mWifiManager.isWifiEnabled()) {
mScanner.forceScan();
}
return true;
case MENU_ID_ADVANCED:
if (getActivity() instanceof PreferenceActivity) {
((PreferenceActivity) getActivity()).startPreferencePanel(
AdvancedSettings.class.getCanonicalName(),
null,
R.string.wifi_advanced_titlebar, null,
this, 0);
} else {
startFragment(this, AdvancedSettings.class.getCanonicalName(), -1, null);
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).onCreateContextMenu(menu, view, info);
} else if (info instanceof AdapterContextMenuInfo) {
Preference preference = (Preference) getListView().getItemAtPosition(
((AdapterContextMenuInfo) info).position);
if (preference instanceof AccessPoint) {
mSelectedAccessPoint = (AccessPoint) preference;
menu.setHeaderTitle(mSelectedAccessPoint.ssid);
if (mSelectedAccessPoint.getLevel() != -1
&& mSelectedAccessPoint.getState() == null) {
menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
}
if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
}
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (mSelectedAccessPoint == null) {
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case MENU_ID_CONNECT: {
if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
if (!requireKeyStore(mSelectedAccessPoint.getConfig())) {
mWifiManager.connectNetwork(mSelectedAccessPoint.networkId);
}
} else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) {
// Shortcut for open networks.
WifiConfiguration config = new WifiConfiguration();
config.SSID = AccessPoint.convertToQuotedString(mSelectedAccessPoint.ssid);
config.allowedKeyManagement.set(KeyMgmt.NONE);
mWifiManager.connectNetwork(config);
} else {
showConfigUi(mSelectedAccessPoint, true);
}
return true;
}
case MENU_ID_FORGET: {
mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId);
return true;
}
case MENU_ID_MODIFY: {
showConfigUi(mSelectedAccessPoint, true);
return true;
}
}
return super.onContextItemSelected(item);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
if (preference instanceof AccessPoint) {
mSelectedAccessPoint = (AccessPoint) preference;
showConfigUi(mSelectedAccessPoint, false);
} else if (preference == mAddNetwork) {
onAddNetworkPressed();
} else if (preference == mNotifyOpenNetworks) {
Secure.putInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
mNotifyOpenNetworks.isChecked() ? 1 : 0);
} else {
return super.onPreferenceTreeClick(screen, preference);
}
return true;
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key == null) return true;
if (key.equals(KEY_SLEEP_POLICY)) {
try {
Settings.System.putInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY, Integer.parseInt(((String) newValue)));
} catch (NumberFormatException e) {
Toast.makeText(getActivity(), R.string.wifi_setting_sleep_policy_error,
Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
/**
* Shows an appropriate Wifi configuration component.
* Called when a user clicks "Add network" preference or one of available networks is selected.
*/
private void showConfigUi(AccessPoint accessPoint, boolean edit) {
mEdit = edit;
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).showConfigUi(accessPoint, edit);
} else {
showDialog(accessPoint, edit);
}
}
private void showDialog(AccessPoint accessPoint, boolean edit) {
if (mDialog != null) {
mDialog.dismiss();
}
mDialog = new WifiDialog(getActivity(), this, accessPoint, edit);
mDialog.show();
}
private boolean requireKeyStore(WifiConfiguration config) {
if (WifiConfigController.requireKeyStore(config) &&
KeyStore.getInstance().test() != KeyStore.NO_ERROR) {
mKeyStoreNetworkId = config.networkId;
Credentials.getInstance().unlock(getActivity());
return true;
}
return false;
}
/**
* Shows the latest access points available with supplimental information like
* the strength of network and the security for it.
*/
private void updateAccessPoints() {
mAccessPoints.removeAll();
// AccessPoints are automatically sorted with TreeSet.
final Collection<AccessPoint> accessPoints = constructAccessPoints();
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).onAccessPointsUpdated(
mAccessPoints, accessPoints);
} else {
for (AccessPoint accessPoint : accessPoints) {
mAccessPoints.addPreference(accessPoint);
}
}
}
private Collection<AccessPoint> constructAccessPoints() {
Collection<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
if (configs != null) {
for (WifiConfiguration config : configs) {
AccessPoint accessPoint = new AccessPoint(getActivity(), config);
accessPoint.update(mLastInfo, mLastState);
accessPoints.add(accessPoint);
}
}
final List<ScanResult> results = mWifiManager.getScanResults();
if (results != null) {
for (ScanResult result : results) {
// Ignore hidden and ad-hoc networks.
if (result.SSID == null || result.SSID.length() == 0 ||
result.capabilities.contains("[IBSS]")) {
continue;
}
boolean found = false;
for (AccessPoint accessPoint : accessPoints) {
if (accessPoint.update(result)) {
found = true;
}
}
if (!found) {
accessPoints.add(new AccessPoint(getActivity(), result));
}
}
}
return accessPoints;
}
private void handleEvent(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN));
} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) ||
WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) {
updateAccessPoints();
} else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
//Ignore supplicant state changes when network is connected
//TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and
//introduce a broadcast that combines the supplicant and network
//network state change events so the apps dont have to worry about
//ignoring supplicant state change when network is connected
//to get more fine grained information.
if (!mConnected.get()) {
updateConnectionState(WifiInfo.getDetailedStateOf((SupplicantState)
intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE)));
}
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).onSupplicantStateChanged(intent);
}
} else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
WifiManager.EXTRA_NETWORK_INFO);
mConnected.set(info.isConnected());
changeNextButtonState(info.isConnected());
updateConnectionState(info.getDetailedState());
} else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
updateConnectionState(null);
} else if (WifiManager.ERROR_ACTION.equals(action)) {
int errorCode = intent.getIntExtra(WifiManager.EXTRA_ERROR_CODE, 0);
switch (errorCode) {
case WifiManager.WPS_OVERLAP_ERROR:
Toast.makeText(context, R.string.wifi_wps_overlap_error,
Toast.LENGTH_SHORT).show();
break;
}
}
}
private void updateConnectionState(DetailedState state) {
/* sticky broadcasts can call this when wifi is disabled */
if (!mWifiManager.isWifiEnabled()) {
mScanner.pause();
return;
}
if (state == DetailedState.OBTAINING_IPADDR) {
mScanner.pause();
} else {
mScanner.resume();
}
mLastInfo = mWifiManager.getConnectionInfo();
if (state != null) {
mLastState = state;
}
for (int i = mAccessPoints.getPreferenceCount() - 1; i >= 0; --i) {
// Maybe there's a WifiConfigPreference
Preference preference = mAccessPoints.getPreference(i);
if (preference instanceof AccessPoint) {
final AccessPoint accessPoint = (AccessPoint) preference;
accessPoint.update(mLastInfo, mLastState);
}
}
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).updateConnectionState(mLastState);
}
}
private void updateWifiState(int state) {
if (state == WifiManager.WIFI_STATE_ENABLED) {
mScanner.resume();
} else {
mScanner.pause();
mAccessPoints.removeAll();
}
}
private class Scanner extends Handler {
private int mRetry = 0;
void resume() {
if (!hasMessages(0)) {
sendEmptyMessage(0);
}
}
void forceScan() {
sendEmptyMessage(0);
}
void pause() {
mRetry = 0;
mAccessPoints.setProgress(false);
removeMessages(0);
}
@Override
public void handleMessage(Message message) {
if (mWifiManager.startScanActive()) {
mRetry = 0;
} else if (++mRetry >= 3) {
mRetry = 0;
Toast.makeText(getActivity(), R.string.wifi_fail_to_scan,
Toast.LENGTH_LONG).show();
return;
}
mAccessPoints.setProgress(mRetry != 0);
// Combo scans can take 5-6s to complete. Increase interval to 10s.
sendEmptyMessageDelayed(0, 10000);
}
}
/**
* Renames/replaces "Next" button when appropriate. "Next" button usually exists in
* Wifi setup screens, not in usual wifi settings screen.
*
* @param connected true when the device is connected to a wifi network.
*/
private void changeNextButtonState(boolean connected) {
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).changeNextButtonState(connected);
} else if (mEnableNextOnConnection && hasNextButton()) {
getNextButton().setEnabled(connected);
}
}
public void onClick(DialogInterface dialogInterface, int button) {
if (mInXlSetupWizard) {
if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
forget();
} else if (button == WifiDialog.BUTTON_SUBMIT) {
((WifiSettingsForSetupWizardXL)getActivity()).onConnectButtonPressed();
}
} else {
if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
forget();
} else if (button == WifiDialog.BUTTON_SUBMIT) {
submit(mDialog.getController());
}
}
}
/* package */ void submit(WifiConfigController configController) {
int networkSetup = configController.chosenNetworkSetupMethod();
switch(networkSetup) {
case WifiConfigController.WPS_PBC:
case WifiConfigController.WPS_PIN_FROM_ACCESS_POINT:
case WifiConfigController.WPS_PIN_FROM_DEVICE:
WpsResult result = mWifiManager.startWps(configController.getWpsConfig());
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity())
.setTitle(R.string.wifi_wps_setup_title)
.setPositiveButton(android.R.string.ok, null);
switch (result.status) {
case FAILURE:
dialog.setMessage(R.string.wifi_wps_failed);
dialog.show();
break;
case IN_PROGRESS:
dialog.setMessage(R.string.wifi_wps_in_progress);
dialog.show();
break;
default:
if (networkSetup == WifiConfigController.WPS_PIN_FROM_DEVICE) {
dialog.setMessage(getResources().getString(R.string.wifi_wps_pin_output,
result.pin));
dialog.show();
}
break;
}
break;
case WifiConfigController.MANUAL:
final WifiConfiguration config = configController.getConfig();
if (config == null) {
if (mSelectedAccessPoint != null
&& !requireKeyStore(mSelectedAccessPoint.getConfig())
&& mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
mWifiManager.connectNetwork(mSelectedAccessPoint.networkId);
}
} else if (config.networkId != INVALID_NETWORK_ID) {
if (mSelectedAccessPoint != null) {
saveNetwork(config);
}
} else {
if (configController.isEdit() || requireKeyStore(config)) {
saveNetwork(config);
} else {
mWifiManager.connectNetwork(config);
}
}
break;
}
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
updateAccessPoints();
}
private void saveNetwork(WifiConfiguration config) {
if (mInXlSetupWizard) {
((WifiSettingsForSetupWizardXL)getActivity()).onSaveNetwork(config);
} else {
mWifiManager.saveNetwork(config);
}
}
/* package */ void forget() {
mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId);
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
updateAccessPoints();
// We need to rename/replace "Next" button in wifi setup context.
changeNextButtonState(false);
}
/**
* Refreshes acccess points and ask Wifi module to scan networks again.
*/
/* package */ void refreshAccessPoints() {
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
mAccessPoints.removeAll();
}
/**
* Called when "add network" button is pressed.
*/
/* package */ void onAddNetworkPressed() {
// No exact access point is selected.
mSelectedAccessPoint = null;
showConfigUi(null, true);
}
/* package */ int getAccessPointsCount() {
if (mAccessPoints != null) {
return mAccessPoints.getPreferenceCount();
} else {
return 0;
}
}
/**
* Requests wifi module to pause wifi scan. May be ignored when the module is disabled.
*/
/* package */ void pauseWifiScan() {
if (mWifiManager.isWifiEnabled()) {
mScanner.pause();
}
}
/**
* Requests wifi module to resume wifi scan. May be ignored when the module is disabled.
*/
/* package */ void resumeWifiScan() {
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
}
}
| true | true | public void onActivityCreated(Bundle savedInstanceState) {
// We don't call super.onActivityCreated() here, since it assumes we already set up
// Preference (probably in onCreate()), while WifiSettings exceptionally set it up in
// this method.
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final Activity activity = getActivity();
final Intent intent = activity.getIntent();
// if we're supposed to enable/disable the Next button based on our current connection
// state, start it off in the right state
mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
// Avoid re-adding on returning from an overlapping activity/fragment.
if (getPreferenceScreen() == null || getPreferenceScreen().getPreferenceCount() < 2) {
if (mEnableNextOnConnection) {
if (hasNextButton()) {
final ConnectivityManager connectivity = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getNetworkInfo(
ConnectivityManager.TYPE_WIFI);
changeNextButtonState(info.isConnected());
}
}
}
if (mInXlSetupWizard) {
addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl);
} else if (intent.getBooleanExtra("only_access_points", false)) {
addPreferencesFromResource(R.xml.wifi_access_points);
} else {
addPreferencesFromResource(R.xml.wifi_settings);
mWifiEnabler = new WifiEnabler(activity,
(CheckBoxPreference) findPreference("enable_wifi"));
mNotifyOpenNetworks =
(CheckBoxPreference) findPreference("notify_open_networks");
mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
}
// This may be either ProgressCategory or AccessPointCategoryForXL.
final ProgressCategoryBase preference =
(ProgressCategoryBase) findPreference("access_points");
mAccessPoints = preference;
mAccessPoints.setOrderingAsAdded(false);
mAddNetwork = findPreference("add_network");
ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
if (pref != null) {
if (Utils.isWifiOnly()) {
pref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
}
pref.setOnPreferenceChangeListener(this);
int value = Settings.System.getInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
pref.setValue(String.valueOf(value));
}
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
// After confirming PreferenceScreen is available, we call super.
super.onActivityCreated(savedInstanceState);
}
| public void onActivityCreated(Bundle savedInstanceState) {
// We don't call super.onActivityCreated() here, since it assumes we already set up
// Preference (probably in onCreate()), while WifiSettings exceptionally set it up in
// this method.
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final Activity activity = getActivity();
final Intent intent = activity.getIntent();
// if we're supposed to enable/disable the Next button based on our current connection
// state, start it off in the right state
mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
// Avoid re-adding on returning from an overlapping activity/fragment.
if (getPreferenceScreen() == null || getPreferenceScreen().getPreferenceCount() < 2) {
if (mEnableNextOnConnection) {
if (hasNextButton()) {
final ConnectivityManager connectivity = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getNetworkInfo(
ConnectivityManager.TYPE_WIFI);
changeNextButtonState(info.isConnected());
}
}
}
if (mInXlSetupWizard) {
addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl);
} else if (intent.getBooleanExtra("only_access_points", false)) {
addPreferencesFromResource(R.xml.wifi_access_points);
} else {
addPreferencesFromResource(R.xml.wifi_settings);
mWifiEnabler = new WifiEnabler(activity,
(CheckBoxPreference) findPreference("enable_wifi"));
mNotifyOpenNetworks =
(CheckBoxPreference) findPreference("notify_open_networks");
mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
}
// This may be either ProgressCategory or AccessPointCategoryForXL.
final ProgressCategoryBase preference =
(ProgressCategoryBase) findPreference("access_points");
mAccessPoints = preference;
mAccessPoints.setOrderingAsAdded(false);
mAddNetwork = findPreference("add_network");
ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
if (pref != null) {
if (Utils.isWifiOnly()) {
pref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
pref.setSummary(R.string.wifi_setting_sleep_policy_summary_wifi_only);
}
pref.setOnPreferenceChangeListener(this);
int value = Settings.System.getInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
pref.setValue(String.valueOf(value));
}
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
// After confirming PreferenceScreen is available, we call super.
super.onActivityCreated(savedInstanceState);
}
|
diff --git a/modules/world/kmzloader/src/classes/org/jdesktop/wonderland/modules/kmzloader/client/KmzLoader.java b/modules/world/kmzloader/src/classes/org/jdesktop/wonderland/modules/kmzloader/client/KmzLoader.java
index e1f4ae74d..6506717a3 100644
--- a/modules/world/kmzloader/src/classes/org/jdesktop/wonderland/modules/kmzloader/client/KmzLoader.java
+++ b/modules/world/kmzloader/src/classes/org/jdesktop/wonderland/modules/kmzloader/client/KmzLoader.java
@@ -1,447 +1,453 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.kmzloader.client;
import com.jme.math.Quaternion;
import com.jme.scene.Node;
import com.jme.util.resource.ResourceLocator;
import com.jme.util.resource.ResourceLocatorTool;
import com.jmex.model.collada.ThreadSafeColladaImporter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.jdesktop.wonderland.client.cell.asset.AssetUtils;
import org.jdesktop.wonderland.modules.jmecolladaloader.client.JmeColladaLoader;
import org.jdesktop.wonderland.client.jme.artimport.DeployedModel;
import org.jdesktop.wonderland.client.jme.artimport.ImportSettings;
import org.jdesktop.wonderland.client.jme.artimport.ImportedModel;
import org.jdesktop.wonderland.client.protocols.wlzip.WlzipManager;
import org.jdesktop.wonderland.common.cell.state.ModelCellComponentServerState;
/**
*
* Loader for SketchUp .kmz files
*
* @author paulby
*/
class KmzLoader extends JmeColladaLoader {
private static final Logger logger = Logger.getLogger(KmzLoader.class.getName());
private HashMap<URL, ZipEntry> textureFiles = new HashMap();
private ArrayList<String> modelFiles = new ArrayList();
/**
* Load a SketchUP KMZ file and return the ImportedModel object
* @param file
* @return
*/
@Override
public ImportedModel importModel(ImportSettings settings) throws IOException {
ImportedModel importedModel;
URL modelURL = settings.getModelURL();
if (!modelURL.getProtocol().equalsIgnoreCase("file")) {
final String modelURLStr = modelURL.toExternalForm();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showConfirmDialog(null,
"Unable to load KMZ from this url "+modelURLStr+
"\nPlease use a local kmz file.",
"Deploy Error", JOptionPane.OK_OPTION);
}
});
return null;
}
try {
+ logger.warning("kmzloader.importModel() "+modelURL.toExternalForm());
File f = new File(modelURL.getFile());
+ if (f==null) {
+ logger.warning("Unable to get file for model "+modelURL.toExternalForm());
+ JOptionPane.showMessageDialog(null, "Unable to get file for model "+modelURL.toExternalForm(), "Error", JOptionPane.ERROR_MESSAGE);
+ return null;
+ }
ZipFile zipFile = new ZipFile(f);
ZipEntry docKmlEntry = zipFile.getEntry("doc.kml");
KmlParser parser = new KmlParser();
InputStream in = zipFile.getInputStream(docKmlEntry);
try {
parser.decodeKML(in);
} catch (Exception ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
}
List<KmlParser.KmlModel> models = parser.getModels();
HashMap<URL, String> textureFilesMapping = new HashMap();
importedModel = new KmzImportedModel(modelURL, models.get(0).getHref(), textureFilesMapping);
String zipHost = WlzipManager.getWlzipManager().addZip(zipFile);
ZipResourceLocator zipResource = new ZipResourceLocator(zipHost, zipFile, textureFilesMapping);
ResourceLocatorTool.addThreadResourceLocator(
ResourceLocatorTool.TYPE_TEXTURE,
zipResource);
if (models.size()==1) {
importedModel.setModelBG(load(zipFile, models.get(0)));
} else {
Node modelBG = new Node();
for(KmlParser.KmlModel model : models) {
modelBG.attachChild(load(zipFile, model));
}
importedModel.setModelBG(modelBG);
}
ResourceLocatorTool.removeThreadResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, zipResource);
WlzipManager.getWlzipManager().removeZip(zipHost, zipFile);
} catch (ZipException ex) {
logger.log(Level.SEVERE, null, ex);
throw new IOException("Zip Error");
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
throw ex;
}
importedModel.setModelLoader(this);
importedModel.setImportSettings(settings);
return importedModel;
}
private Node load(ZipFile zipFile, KmlParser.KmlModel model) throws IOException {
String filename = model.getHref();
logger.info("Loading MODEL " + filename);
modelFiles.add(filename);
ZipEntry modelEntry = zipFile.getEntry(filename);
BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(modelEntry));
ThreadSafeColladaImporter importer = new ThreadSafeColladaImporter(filename);
importer.load(in);
Node modelNode = importer.getModel();
// Adjust the scene transform to match the scale and axis specified in
// the collada file
float unitMeter = importer.getInstance().getUnitMeter();
modelNode.setLocalScale(unitMeter);
String upAxis = importer.getInstance().getUpAxis();
if (upAxis.equals("Z_UP")) {
modelNode.setLocalRotation(new Quaternion(new float[] {-(float)Math.PI/2, 0f, 0f}));
} else if (upAxis.equals("X_UP")) {
modelNode.setLocalRotation(new Quaternion(new float[] {0f, 0f, (float)Math.PI/2}));
} // Y_UP is the Wonderland default
importer.cleanUp();
setupBounds(modelNode);
return modelNode;
}
@Override
protected ResourceLocator getDeployedResourceLocator(Map<String, String> deployedTextures, String baseURL) {
return new RelativeResourceLocator(baseURL);
}
/**
* KMZ files keep all the models in the /models directory, copy all the
* models into the module
* @param moduleArtRootDir
*/
private void deployZipModels(ZipFile zipFile, File targetDir) {
try {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getName().endsWith(".dae")) {
File target = new File(targetDir, "/"+entry.getName()+".gz");
target.getParentFile().mkdirs();
// System.err.println("Creating file "+target.getAbsolutePath());
target.createNewFile();
copyAsset(zipFile, entry, target, true);
}
}
} catch (ZipException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
@Override
protected void deployModels(File targetDir,
String moduleName,
DeployedModel deployedModel,
ImportedModel importedModel,
HashMap<String, String> deploymentMapping,
ModelCellComponentServerState state) {
URL modelURL = importedModel.getImportSettings().getModelURL();
if (!modelURL.getProtocol().equalsIgnoreCase("file")) {
final String modelURLStr = modelURL.toExternalForm();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showConfirmDialog(null,
"Unable to deploy KMZ from this url "+modelURLStr+
"\nPlease use a local kmz file.",
"Deploy Error", JOptionPane.OK_OPTION);
}
});
return;
}
try {
ZipFile zipFile = new ZipFile(new File(modelURL.toURI()));
deployZipModels(zipFile, targetDir);
String kmzFilename = modelURL.toExternalForm();
kmzFilename = kmzFilename.substring(kmzFilename.lastIndexOf('/')+1);
deployedModel.setModelURL(importedModel.getDeploymentBaseURL()+kmzFilename+"/"+((KmzImportedModel)importedModel).getPrimaryModel()+".gz");
deployedModel.setLoaderDataURL(importedModel.getDeploymentBaseURL()+kmzFilename+"/"+kmzFilename+".ldr");
deployDeploymentData(targetDir, deployedModel, kmzFilename);
state.setDeployedModelURL(importedModel.getDeploymentBaseURL()+kmzFilename+"/"+kmzFilename+".dep");
} catch (ZipException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void deployTextures(File targetDir, Map<String, String> deploymentMapping, ImportedModel importedModel) {
URL modelURL = importedModel.getImportSettings().getModelURL();
if (!modelURL.getProtocol().equalsIgnoreCase("file")) {
final String modelURLStr = modelURL.toExternalForm();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showConfirmDialog(null,
"Unable to deploy KMZ from this url "+modelURLStr+
"\nPlease use a local kmz file.",
"Deploy Error", JOptionPane.OK_OPTION);
}
});
return;
}
try {
ZipFile zipFile = new ZipFile(new File(modelURL.toURI()));
deployZipTextures(zipFile, targetDir);
} catch (ZipException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Deploys the textures into the art directory, placing them in a directory
* with the name of the original model.
* @param moduleArtRootDir
*/
private void deployZipTextures(ZipFile zipFile, File targetDir) {
try {
// TODO generate checksums to check for image duplication
// String targetDirName = targetDir.getAbsolutePath();
for (Map.Entry<URL, ZipEntry> t : textureFiles.entrySet()) {
File target = new File(targetDir, "/"+t.getKey().getPath());
target.getParentFile().mkdirs();
target.createNewFile();
// logger.fine("Texture file " + target.getAbsolutePath());
copyAsset(zipFile, t.getValue(), target, false);
}
} catch (ZipException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
/**
* Copy the asset from the zipEntry to the target file
* @param zipFile the zipFile that contains the zipEntry
* @param zipEntry entry to copy from
* @param target file to copy to
*/
private void copyAsset(ZipFile zipFile, ZipEntry zipEntry, File target, boolean compress) {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(zipFile.getInputStream(zipEntry));
if (compress)
out = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(target)));
else
out = new BufferedOutputStream(new FileOutputStream(target));
org.jdesktop.wonderland.common.FileUtils.copyFile(in, out);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
} finally {
try {
if (in!=null)
in.close();
if (out!=null)
out.close();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
class ZipResourceLocator implements ResourceLocator {
private String zipHost;
private ZipFile zipFile;
private Map<URL, String> resourceSet;
public ZipResourceLocator(String zipHost, ZipFile zipFile, Map<URL, String> resourceSet) {
this.zipHost = zipHost;
this.zipFile = zipFile;
this.resourceSet = resourceSet;
}
public URL locateResource(String resourceName) {
// Texture paths seem to be relative to the model directory....
if (resourceName.startsWith("../")) {
resourceName = resourceName.substring(3);
}
if (resourceName.startsWith("/")) {
resourceName = resourceName.substring(1);
}
ZipEntry entry = zipFile.getEntry(resourceName);
if (entry==null) {
logger.severe("Unable to locate texture "+resourceName);
return null;
}
try {
URL url = new URL("wlzip", zipHost, "/"+resourceName);
try {
url.openStream();
} catch (IOException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
textureFiles.put(url, entry);
if (!resourceSet.containsKey(url)) {
resourceSet.put(url, resourceName);
}
return url;
} catch (MalformedURLException ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
class RelativeResourceLocator implements ResourceLocator {
private String baseURL;
private HashMap<String, URL> processed = new HashMap();
/**
* Locate resources for the given file
* @param url
*/
public RelativeResourceLocator(String baseURL) {
this.baseURL = baseURL;
}
public URL locateResource(String resource) {
try {
URL url = processed.get(resource);
if (url!=null)
return url;
String urlStr = trimUrlStr(baseURL+"/" + resource);
url = AssetUtils.getAssetURL(urlStr);
processed.put(url.getPath(), url);
return url;
} catch (MalformedURLException ex) {
logger.log(Level.SEVERE, "Unable to locateResource "+resource, ex);
return null;
}
}
/**
* Trim ../ from url
* @param urlStr
*/
private String trimUrlStr(String urlStr) {
// replace /dir/../ with /
return urlStr.replaceAll("/[^/]*/\\.\\./", "/");
}
}
class KmzImportedModel extends ImportedModel {
private String primaryModel;
/**
*
* @param originalFile
* @param primaryModel the name of the primary dae file in the kmz.
* @param textureFilesMapping
*/
public KmzImportedModel(URL originalFile, String primaryModel, Map<URL, String> textureFilesMapping) {
super(originalFile, textureFilesMapping);
this.primaryModel = primaryModel;
}
/**
* @return the primaryModel
*/
public String getPrimaryModel() {
return primaryModel;
}
}
}
| false | true | public ImportedModel importModel(ImportSettings settings) throws IOException {
ImportedModel importedModel;
URL modelURL = settings.getModelURL();
if (!modelURL.getProtocol().equalsIgnoreCase("file")) {
final String modelURLStr = modelURL.toExternalForm();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showConfirmDialog(null,
"Unable to load KMZ from this url "+modelURLStr+
"\nPlease use a local kmz file.",
"Deploy Error", JOptionPane.OK_OPTION);
}
});
return null;
}
try {
File f = new File(modelURL.getFile());
ZipFile zipFile = new ZipFile(f);
ZipEntry docKmlEntry = zipFile.getEntry("doc.kml");
KmlParser parser = new KmlParser();
InputStream in = zipFile.getInputStream(docKmlEntry);
try {
parser.decodeKML(in);
} catch (Exception ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
}
List<KmlParser.KmlModel> models = parser.getModels();
HashMap<URL, String> textureFilesMapping = new HashMap();
importedModel = new KmzImportedModel(modelURL, models.get(0).getHref(), textureFilesMapping);
String zipHost = WlzipManager.getWlzipManager().addZip(zipFile);
ZipResourceLocator zipResource = new ZipResourceLocator(zipHost, zipFile, textureFilesMapping);
ResourceLocatorTool.addThreadResourceLocator(
ResourceLocatorTool.TYPE_TEXTURE,
zipResource);
if (models.size()==1) {
importedModel.setModelBG(load(zipFile, models.get(0)));
} else {
Node modelBG = new Node();
for(KmlParser.KmlModel model : models) {
modelBG.attachChild(load(zipFile, model));
}
importedModel.setModelBG(modelBG);
}
ResourceLocatorTool.removeThreadResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, zipResource);
WlzipManager.getWlzipManager().removeZip(zipHost, zipFile);
} catch (ZipException ex) {
logger.log(Level.SEVERE, null, ex);
throw new IOException("Zip Error");
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
throw ex;
}
importedModel.setModelLoader(this);
importedModel.setImportSettings(settings);
return importedModel;
}
| public ImportedModel importModel(ImportSettings settings) throws IOException {
ImportedModel importedModel;
URL modelURL = settings.getModelURL();
if (!modelURL.getProtocol().equalsIgnoreCase("file")) {
final String modelURLStr = modelURL.toExternalForm();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showConfirmDialog(null,
"Unable to load KMZ from this url "+modelURLStr+
"\nPlease use a local kmz file.",
"Deploy Error", JOptionPane.OK_OPTION);
}
});
return null;
}
try {
logger.warning("kmzloader.importModel() "+modelURL.toExternalForm());
File f = new File(modelURL.getFile());
if (f==null) {
logger.warning("Unable to get file for model "+modelURL.toExternalForm());
JOptionPane.showMessageDialog(null, "Unable to get file for model "+modelURL.toExternalForm(), "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
ZipFile zipFile = new ZipFile(f);
ZipEntry docKmlEntry = zipFile.getEntry("doc.kml");
KmlParser parser = new KmlParser();
InputStream in = zipFile.getInputStream(docKmlEntry);
try {
parser.decodeKML(in);
} catch (Exception ex) {
Logger.getLogger(KmzLoader.class.getName()).log(Level.SEVERE, null, ex);
}
List<KmlParser.KmlModel> models = parser.getModels();
HashMap<URL, String> textureFilesMapping = new HashMap();
importedModel = new KmzImportedModel(modelURL, models.get(0).getHref(), textureFilesMapping);
String zipHost = WlzipManager.getWlzipManager().addZip(zipFile);
ZipResourceLocator zipResource = new ZipResourceLocator(zipHost, zipFile, textureFilesMapping);
ResourceLocatorTool.addThreadResourceLocator(
ResourceLocatorTool.TYPE_TEXTURE,
zipResource);
if (models.size()==1) {
importedModel.setModelBG(load(zipFile, models.get(0)));
} else {
Node modelBG = new Node();
for(KmlParser.KmlModel model : models) {
modelBG.attachChild(load(zipFile, model));
}
importedModel.setModelBG(modelBG);
}
ResourceLocatorTool.removeThreadResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, zipResource);
WlzipManager.getWlzipManager().removeZip(zipHost, zipFile);
} catch (ZipException ex) {
logger.log(Level.SEVERE, null, ex);
throw new IOException("Zip Error");
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
throw ex;
}
importedModel.setModelLoader(this);
importedModel.setImportSettings(settings);
return importedModel;
}
|
diff --git a/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/uiModel/DiscussionTableModel.java b/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/uiModel/DiscussionTableModel.java
index df75ea8..1251e4c 100644
--- a/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/uiModel/DiscussionTableModel.java
+++ b/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/uiModel/DiscussionTableModel.java
@@ -1,150 +1,152 @@
package org.computer.knauss.reqtDiscussion.ui.uiModel;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import org.computer.knauss.reqtDiscussion.model.Discussion;
import org.computer.knauss.reqtDiscussion.model.IDiscussionFilter;
public class DiscussionTableModel implements TableModel {
private static final String[] COLUMNS = new String[] { "ID", "Summary" };
private Discussion[] discussions;
private List<TableModelListener> listeners = new LinkedList<TableModelListener>();
private JTable table;
@Override
public void addTableModelListener(TableModelListener arg0) {
this.listeners.add(arg0);
}
@Override
public Class<?> getColumnClass(int col) {
if (col == 0)
return Integer.class;
return String.class;
}
@Override
public int getColumnCount() {
return COLUMNS.length;
}
@Override
public String getColumnName(int col) {
if (col >= getColumnCount())
return null;
return COLUMNS[col];
}
@Override
public int getRowCount() {
if (this.discussions == null)
return 0;
return this.discussions.length;
}
@Override
public Object getValueAt(int row, int col) {
if (this.discussions == null || row >= this.getRowCount())
return null;
Discussion d = this.discussions[row];
switch (col) {
case 0:
return d.getID();
case 1:
return d.getSummary();
}
return null;
}
@Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}
@Override
public void removeTableModelListener(TableModelListener arg0) {
this.listeners.remove(arg0);
}
@Override
public void setValueAt(Object arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void setDiscussions(Discussion[] discussions) {
this.discussions = filterDiscussions(discussions);
fireTabledataChanged();
}
private Discussion[] filterDiscussions(Discussion[] discussions) {
IDiscussionFilter filter = new IDiscussionFilter() {
@Override
public boolean accept(Discussion d) {
+ if (d == null || d.getSummary() == null)
+ return false;
String summary = d.getSummary().trim().toLowerCase();
return !summary.equals("test") && !summary.equals("there")
&& !summary.equals("mine")
&& !summary.equals("test story");
}
};
List<Discussion> tmp = new LinkedList<Discussion>();
for (Discussion d : discussions)
if (filter.accept(d))
tmp.add(d);
return tmp.toArray(new Discussion[0]);
}
public void addDiscussions(Discussion[] discussions) {
Discussion[] temp = new Discussion[this.discussions.length
+ discussions.length];
for (int i = 0; i < this.discussions.length; i++) {
temp[i] = this.discussions[i];
}
for (int i = 0; i < discussions.length; i++) {
temp[i + this.discussions.length] = discussions[i];
}
this.discussions = temp;
}
public Discussion[] getDiscussions() {
return this.discussions;
}
void fireTabledataChanged() {
for (TableModelListener l : this.listeners) {
l.tableChanged(new TableModelEvent(this));
}
}
public Discussion[] getSelectedDiscussions() {
int[] ind = this.table.getSelectedRows();
Discussion[] ret = new Discussion[ind.length];
for (int i = 0; i < ind.length; i++) {
if (ind[i] > getRowCount())
// invalid selection!
return new Discussion[0];
ret[i] = this.discussions[this.table.getRowSorter()
.convertRowIndexToModel(ind[i])];
}
return ret;
}
public JTable getTable() {
return this.table;
}
public void setTable(JTable table) {
this.table = table;
}
}
| true | true | private Discussion[] filterDiscussions(Discussion[] discussions) {
IDiscussionFilter filter = new IDiscussionFilter() {
@Override
public boolean accept(Discussion d) {
String summary = d.getSummary().trim().toLowerCase();
return !summary.equals("test") && !summary.equals("there")
&& !summary.equals("mine")
&& !summary.equals("test story");
}
};
List<Discussion> tmp = new LinkedList<Discussion>();
for (Discussion d : discussions)
if (filter.accept(d))
tmp.add(d);
return tmp.toArray(new Discussion[0]);
}
| private Discussion[] filterDiscussions(Discussion[] discussions) {
IDiscussionFilter filter = new IDiscussionFilter() {
@Override
public boolean accept(Discussion d) {
if (d == null || d.getSummary() == null)
return false;
String summary = d.getSummary().trim().toLowerCase();
return !summary.equals("test") && !summary.equals("there")
&& !summary.equals("mine")
&& !summary.equals("test story");
}
};
List<Discussion> tmp = new LinkedList<Discussion>();
for (Discussion d : discussions)
if (filter.accept(d))
tmp.add(d);
return tmp.toArray(new Discussion[0]);
}
|
diff --git a/tool/src/java/org/sakaiproject/assignment2/tool/producers/evolvers/AttachmentInputEvolver.java b/tool/src/java/org/sakaiproject/assignment2/tool/producers/evolvers/AttachmentInputEvolver.java
index edcf5509..8ad4eadf 100644
--- a/tool/src/java/org/sakaiproject/assignment2/tool/producers/evolvers/AttachmentInputEvolver.java
+++ b/tool/src/java/org/sakaiproject/assignment2/tool/producers/evolvers/AttachmentInputEvolver.java
@@ -1,142 +1,143 @@
package org.sakaiproject.assignment2.tool.producers.evolvers;
import org.sakaiproject.assignment2.logic.AttachmentInformation;
import org.sakaiproject.assignment2.logic.ExternalContentLogic;
import uk.org.ponder.beanutil.BeanGetter;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.components.UIBasicListMember;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UIInputMany;
import uk.org.ponder.rsf.components.UIJointContainer;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
import uk.org.ponder.rsf.uitype.UITypes;
/**
* This evolver renders the list of attachments on the Student Submission Editor
* and previewer. This includes teh name of the attachment, it's size, and an
* optional remove link.
*
* @author rjlowe
* @author sgithens
*
*/
public class AttachmentInputEvolver {
public static final String COMPONENT_ID = "attachment-list:";
public static final String CORE_ID = "attachment-list-core:";
private ExternalContentLogic contentLogic;
public void setExternalContentLogic(ExternalContentLogic contentLogic) {
this.contentLogic = contentLogic;
}
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
private BeanGetter rbg;
public void setRequestBeanGetter(BeanGetter rbg) {
this.rbg = rbg;
}
/**
* Renders the attachments. There will be an option to remove them.
*
* @param toevolve
* @return
*/
public UIJointContainer evolveAttachment(UIInputMany toevolve) {
return evolveAttachment(toevolve, true);
}
/**
* Renders the list of Attachments. If removable is true, then a link for
* removing the attachment is rendered as well.
*
* @param toevolve
* @param removable
* @return
*/
public UIJointContainer evolveAttachment(UIInputMany toevolve, boolean removable) {
UIJointContainer togo = new UIJointContainer(toevolve.parent, toevolve.ID, COMPONENT_ID);
toevolve.parent.remove(toevolve);
toevolve.ID = "attachments-input";
togo.addComponent(toevolve);
String[] value = toevolve.getValue();
// Note that a bound value is NEVER null, an unset value is detected via
// this standard call
if (UITypes.isPlaceholder(value)) {
value = (String[]) rbg.getBean(toevolve.valuebinding.value);
// May as well save on later fixups
toevolve.setValue(value);
}
UIBranchContainer core = UIBranchContainer.make(togo, CORE_ID);
int limit = Math.max(0, value.length);
for (int i=0; i < limit; ++i) {
UIBranchContainer row = UIBranchContainer.make(core, "attachment-list-row:", Integer.toString(i));
String thisvalue = i < value.length ? value[i] : "";
AttachmentInformation attach = contentLogic.getAttachmentInformation(thisvalue);
if (attach != null) {
String fileSizeDisplay = "(" + attach.getContentLength() + ")";
UILink.make(row, "attachment_image", attach.getContentTypeImagePath());
UILink.make(row, "attachment_link", attach.getDisplayName(), attach.getUrl());
UIOutput.make(row, "attachment_size", fileSizeDisplay);
UIBasicListMember.makeBasic(row, "attachment_item", toevolve.getFullID(), i);
//Add remove link
if (removable) {
UIVerbatim.make(row, "attachment_remove",
"<a href=\"#\" " +
"onclick=\"" +
"asnn2.removeAttachment(this);" +
"\">" +
messageLocator.getMessage("assignment2.remove") +
"</a>");
}
}
}
// A few notes about this attachment functionality. Currently all
// the demo items are added in the javascript/html in AttachmentEvolver.html
// and asnn2.updateAttachments javascript. It's a bit odd and fragile,
// especially if the input names ever change.
//if (limit == 0) {
//output "demo" row, with styleClass of skip
- UIBranchContainer row = UIBranchContainer.make(togo, "attachment-list-demo:", Integer.toString(0));
+ //UIBranchContainer row = UIBranchContainer.make(togo, "attachment-list-demo:", Integer.toString(0));
//UILink.make(row, "attachment_image", "image.jpg");
//UILink.make(row, "attachment_link", "demo", "demo.html");
//UIOutput.make(row, "attachment_item", "demo");
- //UIBasicListMember.makeBasic(row, "attachment_item", toevolve.getFullID(), 0);
+ //UIBasicListMember.makeBasic(togo, "attachment_item_demo", toevolve.getFullID(), 0);
+ UIOutput.make(togo, "attachments-binding-id", toevolve.getFullID());
//UIOutput.make(row, "attachment_size", "demo");
//Add remove link
/*
UIVerbatim.make(row, "attachment_remove",
"<a href=\"#\" " +
"onclick=\"" +
"asnn2.removeAttachment(this);" +
"\">" +
messageLocator.getMessage("assignment2.remove") +
"</a>");
row.decorators = new DecoratorList(new UIStyleDecorator("skip"));
*/
//}
return togo;
}
}
| false | true | public UIJointContainer evolveAttachment(UIInputMany toevolve, boolean removable) {
UIJointContainer togo = new UIJointContainer(toevolve.parent, toevolve.ID, COMPONENT_ID);
toevolve.parent.remove(toevolve);
toevolve.ID = "attachments-input";
togo.addComponent(toevolve);
String[] value = toevolve.getValue();
// Note that a bound value is NEVER null, an unset value is detected via
// this standard call
if (UITypes.isPlaceholder(value)) {
value = (String[]) rbg.getBean(toevolve.valuebinding.value);
// May as well save on later fixups
toevolve.setValue(value);
}
UIBranchContainer core = UIBranchContainer.make(togo, CORE_ID);
int limit = Math.max(0, value.length);
for (int i=0; i < limit; ++i) {
UIBranchContainer row = UIBranchContainer.make(core, "attachment-list-row:", Integer.toString(i));
String thisvalue = i < value.length ? value[i] : "";
AttachmentInformation attach = contentLogic.getAttachmentInformation(thisvalue);
if (attach != null) {
String fileSizeDisplay = "(" + attach.getContentLength() + ")";
UILink.make(row, "attachment_image", attach.getContentTypeImagePath());
UILink.make(row, "attachment_link", attach.getDisplayName(), attach.getUrl());
UIOutput.make(row, "attachment_size", fileSizeDisplay);
UIBasicListMember.makeBasic(row, "attachment_item", toevolve.getFullID(), i);
//Add remove link
if (removable) {
UIVerbatim.make(row, "attachment_remove",
"<a href=\"#\" " +
"onclick=\"" +
"asnn2.removeAttachment(this);" +
"\">" +
messageLocator.getMessage("assignment2.remove") +
"</a>");
}
}
}
// A few notes about this attachment functionality. Currently all
// the demo items are added in the javascript/html in AttachmentEvolver.html
// and asnn2.updateAttachments javascript. It's a bit odd and fragile,
// especially if the input names ever change.
//if (limit == 0) {
//output "demo" row, with styleClass of skip
UIBranchContainer row = UIBranchContainer.make(togo, "attachment-list-demo:", Integer.toString(0));
//UILink.make(row, "attachment_image", "image.jpg");
//UILink.make(row, "attachment_link", "demo", "demo.html");
//UIOutput.make(row, "attachment_item", "demo");
//UIBasicListMember.makeBasic(row, "attachment_item", toevolve.getFullID(), 0);
//UIOutput.make(row, "attachment_size", "demo");
//Add remove link
/*
UIVerbatim.make(row, "attachment_remove",
"<a href=\"#\" " +
"onclick=\"" +
"asnn2.removeAttachment(this);" +
"\">" +
messageLocator.getMessage("assignment2.remove") +
"</a>");
row.decorators = new DecoratorList(new UIStyleDecorator("skip"));
*/
//}
return togo;
}
| public UIJointContainer evolveAttachment(UIInputMany toevolve, boolean removable) {
UIJointContainer togo = new UIJointContainer(toevolve.parent, toevolve.ID, COMPONENT_ID);
toevolve.parent.remove(toevolve);
toevolve.ID = "attachments-input";
togo.addComponent(toevolve);
String[] value = toevolve.getValue();
// Note that a bound value is NEVER null, an unset value is detected via
// this standard call
if (UITypes.isPlaceholder(value)) {
value = (String[]) rbg.getBean(toevolve.valuebinding.value);
// May as well save on later fixups
toevolve.setValue(value);
}
UIBranchContainer core = UIBranchContainer.make(togo, CORE_ID);
int limit = Math.max(0, value.length);
for (int i=0; i < limit; ++i) {
UIBranchContainer row = UIBranchContainer.make(core, "attachment-list-row:", Integer.toString(i));
String thisvalue = i < value.length ? value[i] : "";
AttachmentInformation attach = contentLogic.getAttachmentInformation(thisvalue);
if (attach != null) {
String fileSizeDisplay = "(" + attach.getContentLength() + ")";
UILink.make(row, "attachment_image", attach.getContentTypeImagePath());
UILink.make(row, "attachment_link", attach.getDisplayName(), attach.getUrl());
UIOutput.make(row, "attachment_size", fileSizeDisplay);
UIBasicListMember.makeBasic(row, "attachment_item", toevolve.getFullID(), i);
//Add remove link
if (removable) {
UIVerbatim.make(row, "attachment_remove",
"<a href=\"#\" " +
"onclick=\"" +
"asnn2.removeAttachment(this);" +
"\">" +
messageLocator.getMessage("assignment2.remove") +
"</a>");
}
}
}
// A few notes about this attachment functionality. Currently all
// the demo items are added in the javascript/html in AttachmentEvolver.html
// and asnn2.updateAttachments javascript. It's a bit odd and fragile,
// especially if the input names ever change.
//if (limit == 0) {
//output "demo" row, with styleClass of skip
//UIBranchContainer row = UIBranchContainer.make(togo, "attachment-list-demo:", Integer.toString(0));
//UILink.make(row, "attachment_image", "image.jpg");
//UILink.make(row, "attachment_link", "demo", "demo.html");
//UIOutput.make(row, "attachment_item", "demo");
//UIBasicListMember.makeBasic(togo, "attachment_item_demo", toevolve.getFullID(), 0);
UIOutput.make(togo, "attachments-binding-id", toevolve.getFullID());
//UIOutput.make(row, "attachment_size", "demo");
//Add remove link
/*
UIVerbatim.make(row, "attachment_remove",
"<a href=\"#\" " +
"onclick=\"" +
"asnn2.removeAttachment(this);" +
"\">" +
messageLocator.getMessage("assignment2.remove") +
"</a>");
row.decorators = new DecoratorList(new UIStyleDecorator("skip"));
*/
//}
return togo;
}
|
diff --git a/tests/src/org/nerdcircus/android/hiveminder/tests/parser/HmXmlParserTest.java b/tests/src/org/nerdcircus/android/hiveminder/tests/parser/HmXmlParserTest.java
index 50109ba..d9eba7e 100644
--- a/tests/src/org/nerdcircus/android/hiveminder/tests/parser/HmXmlParserTest.java
+++ b/tests/src/org/nerdcircus/android/hiveminder/tests/parser/HmXmlParserTest.java
@@ -1,79 +1,79 @@
package org.nerdcircus.android.hiveminder.tests.parser;
import junit.framework.TestCase;
import org.nerdcircus.android.hiveminder.parser.HmXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.StringReader;
import org.nerdcircus.android.hiveminder.HmAuthException;
import org.nerdcircus.android.hiveminder.HmParseException;
import org.nerdcircus.android.hiveminder.model.*;
import android.test.InstrumentationTestRunner;
import android.util.Log;
public class HmXmlParserTest extends TestCase{
private String TAG = "HmXmlParserTest";
public void testCreate() throws HmParseException, XmlPullParserException, IOException {
HmXmlParser x = new HmXmlParser();
assertNotNull(x);
}
public void testTaskParse() throws HmParseException, XmlPullParserException, IOException {
String task1 = "<task><id>1</id><summary>some content</summary></task>";
HmXmlParser x = new HmXmlParser(new StringReader(task1));
assertNotNull(x);
x.xpp.next(); //skip the START_DOCUMENT event.
Task t1 = x.parseTask();
assertEquals("task ids equal", new Long("1").longValue(), t1.id);
assertEquals("task content equal", "some content", t1.summary);
}
public void testParseBraindump() throws HmAuthException, HmParseException, XmlPullParserException, IOException {
- String task1 = "<data><content>"
+ String task1 = "<data>"
+ "<action_class>BTDT::Action::ParseTasksMagically</action_class>"
- + "<created><id>1</id><summary>some content</summary></created>"
+ + "<content><created><id>1</id><summary>some content</summary></created></content>"
+ "<success>1</success>"
+ "<message>this is a message</message>"
- + "</content><data>";
+ + "<data>";
HmXmlParser x = new HmXmlParser(new StringReader(task1));
assertNotNull(x);
HmResponse r = x.parse();
assertNotNull(r);
assertTrue("success true", r.getSuccess());
assertEquals("message set properly", "this is a message", r.getMessage());
assertEquals("action set properly", "BTDT::Action::ParseTasksMagically", r.getAction());
Task t1 = (Task)(r.getTasks()).get(0);
assertEquals("task ids equal", new Long("1").longValue(), t1.id);
assertEquals("task content equal", "some content", t1.summary);
}
public void testParseTaskSearch() throws HmAuthException, HmParseException, XmlPullParserException, IOException {
String task1 = "<data><content>"
+ "<action_class>BTDT::Action::TaskSearch</action_class>"
+ "<tasks><id>1</id><summary>some content</summary></tasks>"
+ "<success>1</success>"
+ "<message>this is a message</message>"
+ "</content><data>";
HmXmlParser x = new HmXmlParser(new StringReader(task1));
assertNotNull(x);
HmResponse r = x.parse();
assertNotNull(r);
assertTrue("success true", r.getSuccess());
assertEquals("message set properly", "this is a message", r.getMessage());
assertEquals("action set properly", "BTDT::Action::TaskSearch", r.getAction());
Task t1 = (Task)(r.getTasks()).get(0);
assertEquals("task ids equal", new Long("1").longValue(), t1.id);
assertEquals("task content equal", "some content", t1.summary);
}
}
| false | true | public void testParseBraindump() throws HmAuthException, HmParseException, XmlPullParserException, IOException {
String task1 = "<data><content>"
+ "<action_class>BTDT::Action::ParseTasksMagically</action_class>"
+ "<created><id>1</id><summary>some content</summary></created>"
+ "<success>1</success>"
+ "<message>this is a message</message>"
+ "</content><data>";
HmXmlParser x = new HmXmlParser(new StringReader(task1));
assertNotNull(x);
HmResponse r = x.parse();
assertNotNull(r);
assertTrue("success true", r.getSuccess());
assertEquals("message set properly", "this is a message", r.getMessage());
assertEquals("action set properly", "BTDT::Action::ParseTasksMagically", r.getAction());
Task t1 = (Task)(r.getTasks()).get(0);
assertEquals("task ids equal", new Long("1").longValue(), t1.id);
assertEquals("task content equal", "some content", t1.summary);
}
| public void testParseBraindump() throws HmAuthException, HmParseException, XmlPullParserException, IOException {
String task1 = "<data>"
+ "<action_class>BTDT::Action::ParseTasksMagically</action_class>"
+ "<content><created><id>1</id><summary>some content</summary></created></content>"
+ "<success>1</success>"
+ "<message>this is a message</message>"
+ "<data>";
HmXmlParser x = new HmXmlParser(new StringReader(task1));
assertNotNull(x);
HmResponse r = x.parse();
assertNotNull(r);
assertTrue("success true", r.getSuccess());
assertEquals("message set properly", "this is a message", r.getMessage());
assertEquals("action set properly", "BTDT::Action::ParseTasksMagically", r.getAction());
Task t1 = (Task)(r.getTasks()).get(0);
assertEquals("task ids equal", new Long("1").longValue(), t1.id);
assertEquals("task content equal", "some content", t1.summary);
}
|
diff --git a/bundles/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/page/SelectDatabaseOutputTypeWizardPage.java b/bundles/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/page/SelectDatabaseOutputTypeWizardPage.java
index ea2a21c492..d3b24174b9 100644
--- a/bundles/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/page/SelectDatabaseOutputTypeWizardPage.java
+++ b/bundles/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/page/SelectDatabaseOutputTypeWizardPage.java
@@ -1,489 +1,488 @@
/**
* Copyright (C) 2013 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.connectors.ui.wizard.page;
import org.bonitasoft.studio.common.jface.BonitaStudioFontRegistry;
import org.bonitasoft.studio.connector.model.definition.wizard.AbstractConnectorConfigurationWizardPage;
import org.bonitasoft.studio.connectors.ConnectorPlugin;
import org.bonitasoft.studio.connectors.i18n.Messages;
import org.bonitasoft.studio.connectors.ui.wizard.page.sqlutil.SQLQueryUtil;
import org.bonitasoft.studio.model.expression.Expression;
import org.bonitasoft.studio.model.expression.ExpressionPackage;
import org.bonitasoft.studio.pics.Pics;
import org.bonitasoft.studio.pics.PicsConstants;
import org.bonitasoft.studio.preferences.BonitaPreferenceConstants;
import org.bonitasoft.studio.preferences.BonitaStudioPreferencesPlugin;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.conversion.Converter;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.IValueChangeListener;
import org.eclipse.core.databinding.observable.value.SelectObservableValue;
import org.eclipse.core.databinding.observable.value.ValueChangeEvent;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.databinding.EMFObservables;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
/**
* @author Romain Bioteau
*
*/
public class SelectDatabaseOutputTypeWizardPage extends AbstractConnectorConfigurationWizardPage implements DatabaseConnectorConstants, IValueChangeListener{
protected Expression outputTypeExpression;
protected IPreferenceStore preferenceStore;
protected Expression scriptExpression;
protected Button gModeRadio;
protected Button alwaysUseScriptCheckbox;
protected SelectObservableValue radioGroupObservable;
protected ISWTObservableValue graphicalModeSelectionValue;
protected boolean editing;
protected ISWTObservableValue singleModeRadioObserveEnabled;
protected ISWTObservableValue nRowsOneColModeRadioObserveEnabled;
protected ISWTObservableValue oneRowNColModeRadioObserveEnabled;
protected IWizardPage previousPageBackup;
private ISWTObservableValue scriptValue;
private ISWTObservableValue tableObserveEnabled;
public SelectDatabaseOutputTypeWizardPage(boolean editing) {
super(SelectDatabaseOutputTypeWizardPage.class.getName());
setTitle(Messages.outputOperationsDefinitionTitle);
setDescription(Messages.outputOperationsDefinitionDesc);
this.editing = editing;
preferenceStore = BonitaStudioPreferencesPlugin.getDefault().getPreferenceStore();
}
@Override
protected Control doCreateControl(Composite parent, EMFDataBindingContext context) {
final Composite mainComposite = new Composite(parent, SWT.NONE);
- mainComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
- mainComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).margins(0, 0).extendedMargins(10, 10, 5, -50).create());
+ mainComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).margins(0, 0).extendedMargins(10, 10, 5, 0).create());
createSelectModeLabelControl(mainComposite);
scriptExpression = (Expression) getConnectorParameter(getInput(SCRIPT_KEY)).getExpression();
IObservableValue scriptContentValue = EMFObservables.observeValue(scriptExpression, ExpressionPackage.Literals.EXPRESSION__CONTENT);
scriptContentValue.addValueChangeListener(this);
outputTypeExpression = (Expression) getConnectorParameter(getInput(OUTPUT_TYPE_KEY)).getExpression();
outputTypeExpression.setName(OUTPUT_TYPE_KEY);
final Composite choicesComposite = createGraphicalModeControl(mainComposite,context);
final Button singleModeRadio = createSingleChoice(choicesComposite,context);
final Button oneRowModeRadio = createOneRowNColsChoice(choicesComposite,context);
final Button nRowModeRadio = createNRowsOneColChoice(choicesComposite,context);
final Button tableModeRadio = createTableChoice(choicesComposite,context);
final Button scriptModeRadio = createScriptModeControl(mainComposite);
final IObservableValue singleValue = SWTObservables.observeSelection(singleModeRadio);
final IObservableValue oneRowValue = SWTObservables.observeSelection(oneRowModeRadio);
final IObservableValue oneColValue = SWTObservables.observeSelection(nRowModeRadio);
final IObservableValue tableValue = SWTObservables.observeSelection(tableModeRadio);
scriptValue = SWTObservables.observeSelection(scriptModeRadio);
graphicalModeSelectionValue = SWTObservables.observeSelection(gModeRadio);
radioGroupObservable = new SelectObservableValue(String.class);
radioGroupObservable.addOption(SINGLE, singleValue);
radioGroupObservable.addOption(ONE_ROW, oneRowValue);
radioGroupObservable.addOption(N_ROW, oneColValue);
radioGroupObservable.addOption(TABLE, tableValue);
radioGroupObservable.addOption(null, scriptValue);
context.bindValue(SWTObservables.observeEnabled(alwaysUseScriptCheckbox),scriptValue);
final UpdateValueStrategy deselectStrategy = new UpdateValueStrategy();
deselectStrategy.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
return false;
}
});
context.bindValue(graphicalModeSelectionValue,SWTObservables.observeSelection(alwaysUseScriptCheckbox),deselectStrategy, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER));
context.bindValue(graphicalModeSelectionValue,SWTObservables.observeEnabled(choicesComposite));
final UpdateValueStrategy disabledStrategy = new UpdateValueStrategy();
disabledStrategy.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
if((outputTypeExpression.getContent() == null && !(Boolean)fromObject) || SQLQueryUtil.getSelectedColumns(scriptExpression).size() != 1 && !SQLQueryUtil.useWildcard(scriptExpression)){
return false;
}
return fromObject;
}
});
final UpdateValueStrategy disabledStrategy2 = new UpdateValueStrategy();
disabledStrategy2.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
if((outputTypeExpression.getContent() == null && !(Boolean)fromObject) || SQLQueryUtil.useWildcard(scriptExpression)){
return false;
}
return fromObject;
}
});
radioGroupObservable.addValueChangeListener(new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
IWizardPage p = getNextPage();
if(p instanceof DatabaseConnectorOutputWizardPage){
((DatabaseConnectorOutputWizardPage)p).updateOutputs((String) event.getObservableValue().getValue());
}
}
});
context.bindValue(radioGroupObservable, EMFObservables.observeValue(outputTypeExpression, ExpressionPackage.Literals.EXPRESSION__CONTENT));
graphicalModeSelectionValue.addValueChangeListener(new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
if((Boolean)event.getObservableValue().getValue()){
if(singleModeRadio.getSelection()){
radioGroupObservable.setValue(SINGLE);
}else if(oneRowModeRadio.getSelection()){
radioGroupObservable.setValue(ONE_ROW);
}else if(nRowModeRadio.getSelection()){
radioGroupObservable.setValue(N_ROW);
}else{
radioGroupObservable.setValue(TABLE);
}
updateEnabledChoices();
}else{
singleModeRadioObserveEnabled.setValue(false);
nRowsOneColModeRadioObserveEnabled.setValue(false);
oneRowNColModeRadioObserveEnabled.setValue(false);
tableObserveEnabled.setValue(false);
}
}
});
parseQuery();
return mainComposite;
}
protected void createSelectModeLabelControl(final Composite mainComposite) {
final Label selectLabel = new Label(mainComposite, SWT.NONE);
selectLabel.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
selectLabel.setText(Messages.selectConnectorOutputMode);
selectLabel.setFont(BonitaStudioFontRegistry.getHighlightedFont());
}
protected void parseQuery() {
if(graphicalModeSelectionValue != null){
IObservableValue enableGraphicalMode = SWTObservables.observeEnabled(gModeRadio);
if(SQLQueryUtil.isGraphicalModeSupportedFor(scriptExpression)){
enableGraphicalMode.setValue(true);
if(!editing){
graphicalModeSelectionValue.setValue(true);
if(outputTypeExpression.getContent() != null){
radioGroupObservable.setValue(outputTypeExpression.getContent());
}else{
radioGroupObservable.setValue(TABLE);
}
}else if(outputTypeExpression.getContent() == null){
graphicalModeSelectionValue.setValue(false);
}
updateEnabledChoices();
}else{
enableGraphicalMode.setValue(false);
graphicalModeSelectionValue.setValue(false);
scriptValue.setValue(true);
radioGroupObservable.setValue(null);
}
}
}
protected void updateEnabledChoices() {
String content = outputTypeExpression.getContent();
if(content != null){
if(SQLQueryUtil.getSelectedColumns(scriptExpression).size() != 1 && !SQLQueryUtil.useWildcard(scriptExpression)){
singleModeRadioObserveEnabled.setValue(false);
nRowsOneColModeRadioObserveEnabled.setValue(false);
tableObserveEnabled.setValue(true);
oneRowNColModeRadioObserveEnabled.setValue(true);
if(SINGLE.equals(content)
|| N_ROW.equals(content)){
radioGroupObservable.setValue(TABLE);
}
}else if(SQLQueryUtil.useWildcard(scriptExpression)){
singleModeRadioObserveEnabled.setValue(false);
nRowsOneColModeRadioObserveEnabled.setValue(false);
oneRowNColModeRadioObserveEnabled.setValue(false);
tableObserveEnabled.setValue(true);
if(SINGLE.equals(content)
|| N_ROW.equals(content)
|| ONE_ROW.equals(content)){
radioGroupObservable.setValue(TABLE);
}
}else{
oneRowNColModeRadioObserveEnabled.setValue(true);
singleModeRadioObserveEnabled.setValue(true);
nRowsOneColModeRadioObserveEnabled.setValue(true);
tableObserveEnabled.setValue(true);
}
}
}
protected void updateQuery() {
if(graphicalModeSelectionValue != null){
IObservableValue enableGraphicalMode = SWTObservables.observeEnabled(gModeRadio);
if(SQLQueryUtil.isGraphicalModeSupportedFor(scriptExpression)){
enableGraphicalMode.setValue(true);
updateEnabledChoices();
}else{
enableGraphicalMode.setValue(false);
graphicalModeSelectionValue.setValue(false);
scriptValue.setValue(true);
radioGroupObservable.setValue(null);
}
}
}
protected Button createScriptModeControl(Composite parent) {
final Button scriptModeRadio = new Button(parent, SWT.RADIO);
scriptModeRadio.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).indent(15, 20).create());
scriptModeRadio.setText(Messages.scriptMode);
scriptModeRadio.setFont(BonitaStudioFontRegistry.getActiveFont());
final Composite descriptionComposite = new Composite(parent, SWT.NONE);
descriptionComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).indent(45, -5).create());
descriptionComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).margins(0, 0).create());
final Label scriptingDescriptionLabel = new Label(descriptionComposite, SWT.WRAP);
scriptingDescriptionLabel.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
scriptingDescriptionLabel.setText(Messages.scriptModeDescription);
alwaysUseScriptCheckbox = new Button(descriptionComposite, SWT.CHECK);
alwaysUseScriptCheckbox.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
alwaysUseScriptCheckbox.setText(Messages.alwaysUseScriptingMode);
alwaysUseScriptCheckbox.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
preferenceStore.setValue(BonitaPreferenceConstants.ALWAYS_USE_SCRIPTING_MODE, alwaysUseScriptCheckbox.getSelection());
}
});
return scriptModeRadio;
}
protected Composite createGraphicalModeControl(Composite parent,
EMFDataBindingContext context) {
gModeRadio = new Button(parent, SWT.RADIO);
gModeRadio.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).indent(15, 0).create());
gModeRadio.setText(getAdvancedModeLabel());
gModeRadio.setFont(BonitaStudioFontRegistry.getActiveFont());
final Composite choicesComposite = new Composite(parent, SWT.NONE);
choicesComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).indent(45, -5).create());
choicesComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).margins(0, 0).create());
createAdvancedModeDescriptionControl(choicesComposite);
return choicesComposite;
}
protected void createAdvancedModeDescriptionControl(
final Composite choicesComposite) {
final Label choiceDescriptionLabel = new Label(choicesComposite, SWT.WRAP);
choiceDescriptionLabel.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).span(2, 1).create());
choiceDescriptionLabel.setText(Messages.graphicalModeDescription);
}
protected String getAdvancedModeLabel() {
return Messages.graphicalMode;
}
protected Button createSingleChoice(final Composite choicesComposite, EMFDataBindingContext context) {
final Button singleRadio = new Button(choicesComposite, SWT.RADIO);
singleRadio.setLayoutData(GridDataFactory.fillDefaults().grab(false, false).create());
singleRadio.setText(Messages.singleValue);
final Label singleIcon = new Label(choicesComposite, SWT.NONE);
singleIcon.setLayoutData(GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).indent(15, 0).grab(true, false).create());
final UpdateValueStrategy selectImageStrategy = new UpdateValueStrategy();
selectImageStrategy.setConverter(new Converter(Boolean.class,Image.class){
@Override
public Object convert(Object fromObject) {
if((Boolean)fromObject){
return Pics.getImage("single_placeholder.png",ConnectorPlugin.getDefault());
}else{
return Pics.getImage("single_placeholder_disabled.png",ConnectorPlugin.getDefault());
}
}
});
singleModeRadioObserveEnabled = SWTObservables.observeEnabled(singleRadio);
context.bindValue(SWTObservables.observeImage(singleIcon), singleModeRadioObserveEnabled,null,selectImageStrategy);
return singleRadio;
}
protected Button createOneRowNColsChoice(final Composite choicesComposite, EMFDataBindingContext context) {
final Button oneRowRadio = new Button(choicesComposite, SWT.RADIO);
oneRowRadio.setLayoutData(GridDataFactory.fillDefaults().grab(false, false).create());
oneRowRadio.setText(Messages.oneRowNCol);
final ControlDecoration oneRowDeco = new ControlDecoration(oneRowRadio, SWT.RIGHT);
oneRowDeco.setImage(Pics.getImage(PicsConstants.hint));
oneRowDeco.setDescriptionText(Messages.oneRowHint);
final Label oneRowIcon = new Label(choicesComposite, SWT.NONE);
oneRowIcon.setLayoutData(GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).indent(15, 0).grab(true, false).create());
final UpdateValueStrategy selectImageStrategy = new UpdateValueStrategy();
selectImageStrategy.setConverter(new Converter(Boolean.class,Image.class){
@Override
public Object convert(Object fromObject) {
if((Boolean)fromObject){
return Pics.getImage("row_placeholder.png",ConnectorPlugin.getDefault());
}else{
return Pics.getImage("row_placeholder_disabled.png",ConnectorPlugin.getDefault());
}
}
});
oneRowNColModeRadioObserveEnabled = SWTObservables.observeEnabled(oneRowRadio);
context.bindValue(SWTObservables.observeImage(oneRowIcon), oneRowNColModeRadioObserveEnabled,null,selectImageStrategy);
return oneRowRadio;
}
protected Button createNRowsOneColChoice(final Composite choicesComposite, EMFDataBindingContext context) {
final Button oneColRadio = new Button(choicesComposite, SWT.RADIO);
oneColRadio.setLayoutData(GridDataFactory.fillDefaults().grab(false, false).create());
oneColRadio.setText(Messages.nRowOneCol);
final ControlDecoration oneColDeco = new ControlDecoration(oneColRadio, SWT.RIGHT);
oneColDeco.setImage(Pics.getImage(PicsConstants.hint));
oneColDeco.setDescriptionText(Messages.oneColHint);
final Label oneColIcon = new Label(choicesComposite, SWT.NONE);
oneColIcon.setLayoutData(GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).indent(15, 0).grab(true, false).create());
final UpdateValueStrategy selectImageStrategy = new UpdateValueStrategy();
selectImageStrategy.setConverter(new Converter(Boolean.class,Image.class){
@Override
public Object convert(Object fromObject) {
if((Boolean)fromObject){
return Pics.getImage("column_placeholder.png",ConnectorPlugin.getDefault());
}else{
return Pics.getImage("column_placeholder_disabled.png",ConnectorPlugin.getDefault());
}
}
});
nRowsOneColModeRadioObserveEnabled = SWTObservables.observeEnabled(oneColRadio);
context.bindValue(SWTObservables.observeImage(oneColIcon), nRowsOneColModeRadioObserveEnabled,null,selectImageStrategy);
return oneColRadio;
}
protected Button createTableChoice(final Composite choicesComposite, EMFDataBindingContext context) {
final Button tableRadio = new Button(choicesComposite, SWT.RADIO);
tableRadio.setLayoutData(GridDataFactory.fillDefaults().grab(false, false).create());
tableRadio.setText(Messages.nRowsNcolumns);
final ControlDecoration tableDeco = new ControlDecoration(tableRadio, SWT.RIGHT);
tableDeco.setImage(Pics.getImage(PicsConstants.hint));
tableDeco.setDescriptionText(Messages.tableHint);
final Label tableIcon = new Label(choicesComposite, SWT.NONE);
tableIcon.setLayoutData(GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).indent(15, 0).grab(true, false).create());
final UpdateValueStrategy selectImageStrategy = new UpdateValueStrategy();
selectImageStrategy.setConverter(new Converter(Boolean.class,Image.class){
@Override
public Object convert(Object fromObject) {
if((Boolean)fromObject){
return Pics.getImage("table_placeholder.png",ConnectorPlugin.getDefault());
}else{
return Pics.getImage("table_placeholder_disabled.png",ConnectorPlugin.getDefault());
}
}
});
tableObserveEnabled = SWTObservables.observeEnabled(tableRadio);
context.bindValue(SWTObservables.observeImage(tableIcon), tableObserveEnabled,null,selectImageStrategy);
return tableRadio;
}
@Override
public void handleValueChange(ValueChangeEvent event) {
updateQuery();
}
@Override
public void setPreviousPage(IWizardPage page) {
this.previousPageBackup = page;
super.setPreviousPage(page);
}
@Override
public IWizardPage getPreviousPage() {
if(previousPageBackup != null){
return previousPageBackup;
}
IWizard wizard = getWizard();
if(wizard != null){
return wizard.getPreviousPage(this);
}
return super.getPreviousPage();
}
}
| true | true | protected Control doCreateControl(Composite parent, EMFDataBindingContext context) {
final Composite mainComposite = new Composite(parent, SWT.NONE);
mainComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
mainComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).margins(0, 0).extendedMargins(10, 10, 5, -50).create());
createSelectModeLabelControl(mainComposite);
scriptExpression = (Expression) getConnectorParameter(getInput(SCRIPT_KEY)).getExpression();
IObservableValue scriptContentValue = EMFObservables.observeValue(scriptExpression, ExpressionPackage.Literals.EXPRESSION__CONTENT);
scriptContentValue.addValueChangeListener(this);
outputTypeExpression = (Expression) getConnectorParameter(getInput(OUTPUT_TYPE_KEY)).getExpression();
outputTypeExpression.setName(OUTPUT_TYPE_KEY);
final Composite choicesComposite = createGraphicalModeControl(mainComposite,context);
final Button singleModeRadio = createSingleChoice(choicesComposite,context);
final Button oneRowModeRadio = createOneRowNColsChoice(choicesComposite,context);
final Button nRowModeRadio = createNRowsOneColChoice(choicesComposite,context);
final Button tableModeRadio = createTableChoice(choicesComposite,context);
final Button scriptModeRadio = createScriptModeControl(mainComposite);
final IObservableValue singleValue = SWTObservables.observeSelection(singleModeRadio);
final IObservableValue oneRowValue = SWTObservables.observeSelection(oneRowModeRadio);
final IObservableValue oneColValue = SWTObservables.observeSelection(nRowModeRadio);
final IObservableValue tableValue = SWTObservables.observeSelection(tableModeRadio);
scriptValue = SWTObservables.observeSelection(scriptModeRadio);
graphicalModeSelectionValue = SWTObservables.observeSelection(gModeRadio);
radioGroupObservable = new SelectObservableValue(String.class);
radioGroupObservable.addOption(SINGLE, singleValue);
radioGroupObservable.addOption(ONE_ROW, oneRowValue);
radioGroupObservable.addOption(N_ROW, oneColValue);
radioGroupObservable.addOption(TABLE, tableValue);
radioGroupObservable.addOption(null, scriptValue);
context.bindValue(SWTObservables.observeEnabled(alwaysUseScriptCheckbox),scriptValue);
final UpdateValueStrategy deselectStrategy = new UpdateValueStrategy();
deselectStrategy.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
return false;
}
});
context.bindValue(graphicalModeSelectionValue,SWTObservables.observeSelection(alwaysUseScriptCheckbox),deselectStrategy, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER));
context.bindValue(graphicalModeSelectionValue,SWTObservables.observeEnabled(choicesComposite));
final UpdateValueStrategy disabledStrategy = new UpdateValueStrategy();
disabledStrategy.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
if((outputTypeExpression.getContent() == null && !(Boolean)fromObject) || SQLQueryUtil.getSelectedColumns(scriptExpression).size() != 1 && !SQLQueryUtil.useWildcard(scriptExpression)){
return false;
}
return fromObject;
}
});
final UpdateValueStrategy disabledStrategy2 = new UpdateValueStrategy();
disabledStrategy2.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
if((outputTypeExpression.getContent() == null && !(Boolean)fromObject) || SQLQueryUtil.useWildcard(scriptExpression)){
return false;
}
return fromObject;
}
});
radioGroupObservable.addValueChangeListener(new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
IWizardPage p = getNextPage();
if(p instanceof DatabaseConnectorOutputWizardPage){
((DatabaseConnectorOutputWizardPage)p).updateOutputs((String) event.getObservableValue().getValue());
}
}
});
context.bindValue(radioGroupObservable, EMFObservables.observeValue(outputTypeExpression, ExpressionPackage.Literals.EXPRESSION__CONTENT));
graphicalModeSelectionValue.addValueChangeListener(new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
if((Boolean)event.getObservableValue().getValue()){
if(singleModeRadio.getSelection()){
radioGroupObservable.setValue(SINGLE);
}else if(oneRowModeRadio.getSelection()){
radioGroupObservable.setValue(ONE_ROW);
}else if(nRowModeRadio.getSelection()){
radioGroupObservable.setValue(N_ROW);
}else{
radioGroupObservable.setValue(TABLE);
}
updateEnabledChoices();
}else{
singleModeRadioObserveEnabled.setValue(false);
nRowsOneColModeRadioObserveEnabled.setValue(false);
oneRowNColModeRadioObserveEnabled.setValue(false);
tableObserveEnabled.setValue(false);
}
}
});
parseQuery();
return mainComposite;
}
| protected Control doCreateControl(Composite parent, EMFDataBindingContext context) {
final Composite mainComposite = new Composite(parent, SWT.NONE);
mainComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).margins(0, 0).extendedMargins(10, 10, 5, 0).create());
createSelectModeLabelControl(mainComposite);
scriptExpression = (Expression) getConnectorParameter(getInput(SCRIPT_KEY)).getExpression();
IObservableValue scriptContentValue = EMFObservables.observeValue(scriptExpression, ExpressionPackage.Literals.EXPRESSION__CONTENT);
scriptContentValue.addValueChangeListener(this);
outputTypeExpression = (Expression) getConnectorParameter(getInput(OUTPUT_TYPE_KEY)).getExpression();
outputTypeExpression.setName(OUTPUT_TYPE_KEY);
final Composite choicesComposite = createGraphicalModeControl(mainComposite,context);
final Button singleModeRadio = createSingleChoice(choicesComposite,context);
final Button oneRowModeRadio = createOneRowNColsChoice(choicesComposite,context);
final Button nRowModeRadio = createNRowsOneColChoice(choicesComposite,context);
final Button tableModeRadio = createTableChoice(choicesComposite,context);
final Button scriptModeRadio = createScriptModeControl(mainComposite);
final IObservableValue singleValue = SWTObservables.observeSelection(singleModeRadio);
final IObservableValue oneRowValue = SWTObservables.observeSelection(oneRowModeRadio);
final IObservableValue oneColValue = SWTObservables.observeSelection(nRowModeRadio);
final IObservableValue tableValue = SWTObservables.observeSelection(tableModeRadio);
scriptValue = SWTObservables.observeSelection(scriptModeRadio);
graphicalModeSelectionValue = SWTObservables.observeSelection(gModeRadio);
radioGroupObservable = new SelectObservableValue(String.class);
radioGroupObservable.addOption(SINGLE, singleValue);
radioGroupObservable.addOption(ONE_ROW, oneRowValue);
radioGroupObservable.addOption(N_ROW, oneColValue);
radioGroupObservable.addOption(TABLE, tableValue);
radioGroupObservable.addOption(null, scriptValue);
context.bindValue(SWTObservables.observeEnabled(alwaysUseScriptCheckbox),scriptValue);
final UpdateValueStrategy deselectStrategy = new UpdateValueStrategy();
deselectStrategy.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
return false;
}
});
context.bindValue(graphicalModeSelectionValue,SWTObservables.observeSelection(alwaysUseScriptCheckbox),deselectStrategy, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER));
context.bindValue(graphicalModeSelectionValue,SWTObservables.observeEnabled(choicesComposite));
final UpdateValueStrategy disabledStrategy = new UpdateValueStrategy();
disabledStrategy.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
if((outputTypeExpression.getContent() == null && !(Boolean)fromObject) || SQLQueryUtil.getSelectedColumns(scriptExpression).size() != 1 && !SQLQueryUtil.useWildcard(scriptExpression)){
return false;
}
return fromObject;
}
});
final UpdateValueStrategy disabledStrategy2 = new UpdateValueStrategy();
disabledStrategy2.setConverter(new Converter(Boolean.class,Boolean.class) {
@Override
public Object convert(Object fromObject) {
if((outputTypeExpression.getContent() == null && !(Boolean)fromObject) || SQLQueryUtil.useWildcard(scriptExpression)){
return false;
}
return fromObject;
}
});
radioGroupObservable.addValueChangeListener(new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
IWizardPage p = getNextPage();
if(p instanceof DatabaseConnectorOutputWizardPage){
((DatabaseConnectorOutputWizardPage)p).updateOutputs((String) event.getObservableValue().getValue());
}
}
});
context.bindValue(radioGroupObservable, EMFObservables.observeValue(outputTypeExpression, ExpressionPackage.Literals.EXPRESSION__CONTENT));
graphicalModeSelectionValue.addValueChangeListener(new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
if((Boolean)event.getObservableValue().getValue()){
if(singleModeRadio.getSelection()){
radioGroupObservable.setValue(SINGLE);
}else if(oneRowModeRadio.getSelection()){
radioGroupObservable.setValue(ONE_ROW);
}else if(nRowModeRadio.getSelection()){
radioGroupObservable.setValue(N_ROW);
}else{
radioGroupObservable.setValue(TABLE);
}
updateEnabledChoices();
}else{
singleModeRadioObserveEnabled.setValue(false);
nRowsOneColModeRadioObserveEnabled.setValue(false);
oneRowNColModeRadioObserveEnabled.setValue(false);
tableObserveEnabled.setValue(false);
}
}
});
parseQuery();
return mainComposite;
}
|
diff --git a/src/main/java/org/atlasapi/remotesite/talktalk/TalkTalkVodContentListUpdateTask.java b/src/main/java/org/atlasapi/remotesite/talktalk/TalkTalkVodContentListUpdateTask.java
index d8105d398..479d25ce6 100644
--- a/src/main/java/org/atlasapi/remotesite/talktalk/TalkTalkVodContentListUpdateTask.java
+++ b/src/main/java/org/atlasapi/remotesite/talktalk/TalkTalkVodContentListUpdateTask.java
@@ -1,122 +1,127 @@
package org.atlasapi.remotesite.talktalk;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.atlasapi.media.entity.ChildRef;
import org.atlasapi.media.entity.Content;
import org.atlasapi.media.entity.ContentGroup;
import org.atlasapi.media.entity.Identified;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.persistence.content.ContentGroupResolver;
import org.atlasapi.persistence.content.ContentGroupWriter;
import org.atlasapi.persistence.content.ContentResolver;
import org.atlasapi.persistence.content.ResolvedContent;
import org.atlasapi.remotesite.talktalk.TalkTalkClient.TalkTalkVodListCallback;
import org.atlasapi.remotesite.talktalk.vod.bindings.ChannelType;
import org.atlasapi.remotesite.talktalk.vod.bindings.VODEntityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.metabroadcast.common.base.Maybe;
import com.metabroadcast.common.scheduling.ScheduledTask;
import com.metabroadcast.common.scheduling.UpdateProgress;
/**
* {@link ScheduledTask} which retrieves the TV Structure via the provided
* {@link TalkTalkClient} and processes each {@link ChannelType} in turn using
* the provided {@link TalkTalkChannelProcessor}.
*/
public class TalkTalkVodContentListUpdateTask extends ScheduledTask {
private final String TALK_TALK_URI_PART = "http://talktalk.net/groups";
private final Logger log = LoggerFactory.getLogger(getClass());
private final TalkTalkClient client;
private final ContentGroupWriter groupWriter;
private final ContentGroupResolver groupResolver;
private final ContentResolver contentResolver;
private final GroupType type;
private final String identifier;
private final TalkTalkUriCompiler uriCompiler = new TalkTalkUriCompiler();
private final AtomicReference<UpdateProgress> progress
= new AtomicReference<UpdateProgress>();
public TalkTalkVodContentListUpdateTask(TalkTalkClient talkTalkClient,
ContentGroupResolver resolver, ContentGroupWriter writer,
ContentResolver contentResolver,
GroupType type, String identifier) {
this.client = checkNotNull(talkTalkClient);
this.groupResolver = checkNotNull(resolver);
this.groupWriter = checkNotNull(writer);
this.contentResolver = checkNotNull(contentResolver);
this.type = type;
this.identifier = identifier;
}
@Override
protected void runTask() {
try {
progress.set(UpdateProgress.START);
ContentGroup group = resolveOrCreateContentGroup();
List<ChildRef> refs = client.processVodList(type, identifier, new TalkTalkVodListCallback<List<ChildRef>>() {
private ImmutableList.Builder<ChildRef> refs = ImmutableList.builder();
@Override
public List<ChildRef> getResult() {
return refs.build();
}
@Override
public void process(VODEntityType entity) {
log.debug("processing entity {}", entity.getId());
- String uri = uriCompiler.uriFor(entity);
- Content content = resolve(uri);
- if (content != null) {
- refs.add(content.childRef());
- progress.set(progress.get().reduce(UpdateProgress.SUCCESS));
- } else {
+ try {
+ String uri = uriCompiler.uriFor(entity);
+ Content content = resolve(uri);
+ if (content != null) {
+ refs.add(content.childRef());
+ progress.set(progress.get().reduce(UpdateProgress.SUCCESS));
+ } else {
+ progress.set(progress.get().reduce(UpdateProgress.FAILURE));
+ }
+ reportStatus(progress.toString());
+ } catch (Exception e) {
+ log.warn(String.format("%s %s", entity.getItemType(), entity.getId()), e);
progress.set(progress.get().reduce(UpdateProgress.FAILURE));
}
- reportStatus(progress.toString());
}
});
group.setContents(refs);
groupWriter.createOrUpdate(group);
if (progress.get().hasFailures()) {
throw new RuntimeException(progress.get().toString());
}
} catch (TalkTalkException tte) {
log.error("content update failed", tte);
// ensure task is marked failed
throw new RuntimeException(tte);
}
}
private Content resolve(String uri) {
ResolvedContent resolved = contentResolver.findByCanonicalUris(ImmutableList.of(uri));
Maybe<Identified> possibleContent = resolved.get(uri);
if (possibleContent.hasValue() && possibleContent.requireValue() instanceof Content) {
return (Content) possibleContent.requireValue();
}
return null;
}
private ContentGroup resolveOrCreateContentGroup() {
String uri = String.format("%s/%s/%s", TALK_TALK_URI_PART, type.toString().toLowerCase(), identifier);
ResolvedContent resolvedContent = groupResolver.findByCanonicalUris(ImmutableList.of(uri));
Maybe<Identified> possibleGroup = resolvedContent.get(uri);
return possibleGroup.hasValue() ? (ContentGroup) resolvedContent.get(uri).requireValue()
: new ContentGroup(uri, Publisher.TALK_TALK);
}
}
| false | true | protected void runTask() {
try {
progress.set(UpdateProgress.START);
ContentGroup group = resolveOrCreateContentGroup();
List<ChildRef> refs = client.processVodList(type, identifier, new TalkTalkVodListCallback<List<ChildRef>>() {
private ImmutableList.Builder<ChildRef> refs = ImmutableList.builder();
@Override
public List<ChildRef> getResult() {
return refs.build();
}
@Override
public void process(VODEntityType entity) {
log.debug("processing entity {}", entity.getId());
String uri = uriCompiler.uriFor(entity);
Content content = resolve(uri);
if (content != null) {
refs.add(content.childRef());
progress.set(progress.get().reduce(UpdateProgress.SUCCESS));
} else {
progress.set(progress.get().reduce(UpdateProgress.FAILURE));
}
reportStatus(progress.toString());
}
});
group.setContents(refs);
groupWriter.createOrUpdate(group);
if (progress.get().hasFailures()) {
throw new RuntimeException(progress.get().toString());
}
} catch (TalkTalkException tte) {
log.error("content update failed", tte);
// ensure task is marked failed
throw new RuntimeException(tte);
}
}
| protected void runTask() {
try {
progress.set(UpdateProgress.START);
ContentGroup group = resolveOrCreateContentGroup();
List<ChildRef> refs = client.processVodList(type, identifier, new TalkTalkVodListCallback<List<ChildRef>>() {
private ImmutableList.Builder<ChildRef> refs = ImmutableList.builder();
@Override
public List<ChildRef> getResult() {
return refs.build();
}
@Override
public void process(VODEntityType entity) {
log.debug("processing entity {}", entity.getId());
try {
String uri = uriCompiler.uriFor(entity);
Content content = resolve(uri);
if (content != null) {
refs.add(content.childRef());
progress.set(progress.get().reduce(UpdateProgress.SUCCESS));
} else {
progress.set(progress.get().reduce(UpdateProgress.FAILURE));
}
reportStatus(progress.toString());
} catch (Exception e) {
log.warn(String.format("%s %s", entity.getItemType(), entity.getId()), e);
progress.set(progress.get().reduce(UpdateProgress.FAILURE));
}
}
});
group.setContents(refs);
groupWriter.createOrUpdate(group);
if (progress.get().hasFailures()) {
throw new RuntimeException(progress.get().toString());
}
} catch (TalkTalkException tte) {
log.error("content update failed", tte);
// ensure task is marked failed
throw new RuntimeException(tte);
}
}
|
diff --git a/src/com/android/camera/panorama/PanoramaActivity.java b/src/com/android/camera/panorama/PanoramaActivity.java
index 2bb9f6c1..8126a1b5 100644
--- a/src/com/android/camera/panorama/PanoramaActivity.java
+++ b/src/com/android/camera/panorama/PanoramaActivity.java
@@ -1,1005 +1,1009 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.panorama;
import com.android.camera.CameraDisabledException;
import com.android.camera.CameraHardwareException;
import com.android.camera.CameraHolder;
import com.android.camera.Exif;
import com.android.camera.MenuHelper;
import com.android.camera.ModePicker;
import com.android.camera.OnClickAttr;
import com.android.camera.R;
import com.android.camera.ShutterButton;
import com.android.camera.Storage;
import com.android.camera.Thumbnail;
import com.android.camera.Util;
import com.android.camera.ui.RotateImageView;
import com.android.camera.ui.SharePopup;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.util.List;
/**
* Activity to handle panorama capturing.
*/
public class PanoramaActivity extends Activity implements
ModePicker.OnModeChangeListener, SurfaceTexture.OnFrameAvailableListener,
ShutterButton.OnShutterButtonListener,
MosaicRendererSurfaceViewRenderer.MosaicSurfaceCreateListener {
public static final int DEFAULT_SWEEP_ANGLE = 160;
public static final int DEFAULT_BLEND_MODE = Mosaic.BLENDTYPE_HORIZONTAL;
public static final int DEFAULT_CAPTURE_PIXELS = 960 * 720;
private static final int MSG_LOW_RES_FINAL_MOSAIC_READY = 1;
private static final int MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL = 2;
private static final int MSG_GENERATE_FINAL_MOSAIC_ERROR = 3;
private static final int MSG_RESET_TO_PREVIEW = 4;
private static final String TAG = "PanoramaActivity";
private static final int PREVIEW_STOPPED = 0;
private static final int PREVIEW_ACTIVE = 1;
private static final int CAPTURE_STATE_VIEWFINDER = 0;
private static final int CAPTURE_STATE_MOSAIC = 1;
// Speed is in unit of deg/sec
private static final float PANNING_SPEED_THRESHOLD = 20f;
// Ratio of nanosecond to second
private static final float NS2S = 1.0f / 1000000000.0f;
private boolean mPausing;
private View mPanoLayout;
private View mCaptureLayout;
private View mReviewLayout;
private ImageView mReview;
private TextView mCaptureIndicator;
private PanoProgressBar mPanoProgressBar;
private PanoProgressBar mSavingProgressBar;
private View mFastIndicationBorder;
private View mLeftIndicator;
private View mRightIndicator;
private MosaicRendererSurfaceView mMosaicView;
private TextView mTooFastPrompt;
private ShutterButton mShutterButton;
private Object mWaitObject = new Object();
private String mPreparePreviewString;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mDialogTitle;
private String mDialogOk;
private int mIndicatorColor;
private int mIndicatorColorFast;
private float mCompassValueX;
private float mCompassValueY;
private float mCompassValueXStart;
private float mCompassValueYStart;
private float mCompassValueXStartBuffer;
private float mCompassValueYStartBuffer;
private int mCompassThreshold;
private int mTraversedAngleX;
private int mTraversedAngleY;
private long mTimestamp;
// Control variables for the terminate condition.
private int mMinAngleX;
private int mMaxAngleX;
private int mMinAngleY;
private int mMaxAngleY;
private RotateImageView mThumbnailView;
private Thumbnail mThumbnail;
private SharePopup mSharePopup;
private AnimatorSet mThumbnailViewAndModePickerOut;
private AnimatorSet mThumbnailViewAndModePickerIn;
private int mPreviewWidth;
private int mPreviewHeight;
private Camera mCameraDevice;
private int mCameraState;
private int mCaptureState;
private SensorManager mSensorManager;
private Sensor mSensor;
private ModePicker mModePicker;
private MosaicFrameProcessor mMosaicFrameProcessor;
private long mTimeTaken;
private Handler mMainHandler;
private SurfaceTexture mSurfaceTexture;
private boolean mThreadRunning;
private boolean mCancelComputation;
private float[] mTransformMatrix;
private float mHorizontalViewAngle;
// Prefer FOCUS_MODE_INFINITY to FOCUS_MODE_CONTINUOUS_VIDEO because of
// getting a better image quality by the former.
private String mTargetFocusMode = Parameters.FOCUS_MODE_INFINITY;
private PanoOrientationEventListener mOrientationEventListener;
// The value could be 0, 1, 2, 3 for the 4 different orientations measured in clockwise
// respectively.
private int mDeviceOrientation;
private class MosaicJpeg {
public MosaicJpeg(byte[] data, int width, int height) {
this.data = data;
this.width = width;
this.height = height;
this.isValid = true;
}
public MosaicJpeg() {
this.data = null;
this.width = 0;
this.height = 0;
this.isValid = false;
}
public final byte[] data;
public final int width;
public final int height;
public final boolean isValid;
}
private class PanoOrientationEventListener extends OrientationEventListener {
public PanoOrientationEventListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
// Default to the last known orientation.
if (orientation == ORIENTATION_UNKNOWN) return;
mDeviceOrientation = ((orientation + 45) / 90) % 4;
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Util.enterLightsOutMode(window);
Util.initializeScreenBrightness(window, getContentResolver());
createContentView();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (mSensor == null) {
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
mOrientationEventListener = new PanoOrientationEventListener(this);
mTransformMatrix = new float[16];
mPreparePreviewString =
getResources().getString(R.string.pano_dialog_prepare_preview);
mDialogTitle = getResources().getString(R.string.pano_dialog_title);
mDialogOk = getResources().getString(R.string.dialog_ok);
mMainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOW_RES_FINAL_MOSAIC_READY:
onBackgroundThreadFinished();
showFinalMosaic((Bitmap) msg.obj);
saveHighResMosaic();
break;
case MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL:
onBackgroundThreadFinished();
// Set the thumbnail bitmap here because mThumbnailView must be accessed
// from the UI thread.
if (mThumbnail != null) {
mThumbnailView.setBitmap(mThumbnail.getBitmap());
}
resetToPreview();
break;
case MSG_GENERATE_FINAL_MOSAIC_ERROR:
onBackgroundThreadFinished();
- mAlertDialog.show();
+ if (mPausing) {
+ resetToPreview();
+ } else {
+ mAlertDialog.show();
+ }
break;
case MSG_RESET_TO_PREVIEW:
onBackgroundThreadFinished();
resetToPreview();
}
clearMosaicFrameProcessorIfNeeded();
}
};
mAlertDialog = (new AlertDialog.Builder(this))
.setTitle(mDialogTitle)
.setMessage(R.string.pano_dialog_panorama_failed)
.create();
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, mDialogOk,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
resetToPreview();
}
});
}
private void setupCamera() {
openCamera();
Parameters parameters = mCameraDevice.getParameters();
setupCaptureParams(parameters);
configureCamera(parameters);
}
private void releaseCamera() {
if (mCameraDevice != null) {
mCameraDevice.setPreviewCallbackWithBuffer(null);
CameraHolder.instance().release();
mCameraDevice = null;
mCameraState = PREVIEW_STOPPED;
}
}
private void openCamera() {
try {
mCameraDevice = Util.openCamera(this, CameraHolder.instance().getBackCameraId());
} catch (CameraHardwareException e) {
Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
return;
} catch (CameraDisabledException e) {
Util.showErrorAndFinish(this, R.string.camera_disabled);
return;
}
}
private boolean findBestPreviewSize(List<Size> supportedSizes, boolean need4To3,
boolean needSmaller) {
int pixelsDiff = DEFAULT_CAPTURE_PIXELS;
boolean hasFound = false;
for (Size size : supportedSizes) {
int h = size.height;
int w = size.width;
// we only want 4:3 format.
int d = DEFAULT_CAPTURE_PIXELS - h * w;
if (needSmaller && d < 0) { // no bigger preview than 960x720.
continue;
}
if (need4To3 && (h * 4 != w * 3)) {
continue;
}
d = Math.abs(d);
if (d < pixelsDiff) {
mPreviewWidth = w;
mPreviewHeight = h;
pixelsDiff = d;
hasFound = true;
}
}
return hasFound;
}
private void setupCaptureParams(Parameters parameters) {
List<Size> supportedSizes = parameters.getSupportedPreviewSizes();
if (!findBestPreviewSize(supportedSizes, true, true)) {
Log.w(TAG, "No 4:3 ratio preview size supported.");
if (!findBestPreviewSize(supportedSizes, false, true)) {
Log.w(TAG, "Can't find a supported preview size smaller than 960x720.");
findBestPreviewSize(supportedSizes, false, false);
}
}
Log.v(TAG, "preview h = " + mPreviewHeight + " , w = " + mPreviewWidth);
parameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
List<int[]> frameRates = parameters.getSupportedPreviewFpsRange();
int last = frameRates.size() - 1;
int minFps = (frameRates.get(last))[Parameters.PREVIEW_FPS_MIN_INDEX];
int maxFps = (frameRates.get(last))[Parameters.PREVIEW_FPS_MAX_INDEX];
parameters.setPreviewFpsRange(minFps, maxFps);
Log.v(TAG, "preview fps: " + minFps + ", " + maxFps);
List<String> supportedFocusModes = parameters.getSupportedFocusModes();
if (supportedFocusModes.indexOf(mTargetFocusMode) >= 0) {
parameters.setFocusMode(mTargetFocusMode);
} else {
// Use the default focus mode and log a message
Log.w(TAG, "Cannot set the focus mode to " + mTargetFocusMode +
" becuase the mode is not supported.");
}
parameters.setRecordingHint(false);
mHorizontalViewAngle = ((mDeviceOrientation % 2) == 0) ?
parameters.getHorizontalViewAngle() : parameters.getVerticalViewAngle();
}
public int getPreviewBufSize() {
PixelFormat pixelInfo = new PixelFormat();
PixelFormat.getPixelFormatInfo(mCameraDevice.getParameters().getPreviewFormat(), pixelInfo);
// TODO: remove this extra 32 byte after the driver bug is fixed.
return (mPreviewWidth * mPreviewHeight * pixelInfo.bitsPerPixel / 8) + 32;
}
private void configureCamera(Parameters parameters) {
mCameraDevice.setParameters(parameters);
int orientation = Util.getDisplayOrientation(Util.getDisplayRotation(this),
CameraHolder.instance().getBackCameraId());
mCameraDevice.setDisplayOrientation(orientation);
}
private boolean switchToOtherMode(int mode) {
if (isFinishing()) {
return false;
}
MenuHelper.gotoMode(mode, this);
finish();
return true;
}
public boolean onModeChanged(int mode) {
if (mode != ModePicker.MODE_PANORAMA) {
return switchToOtherMode(mode);
} else {
return true;
}
}
@Override
public void onMosaicSurfaceCreated(final int textureID) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mSurfaceTexture != null) {
mSurfaceTexture.release();
}
mSurfaceTexture = new SurfaceTexture(textureID);
if (!mPausing) {
mSurfaceTexture.setOnFrameAvailableListener(PanoramaActivity.this);
startCameraPreview();
}
}
});
}
public void runViewFinder() {
mMosaicView.setWarping(false);
// Call preprocess to render it to low-res and high-res RGB textures.
mMosaicView.preprocess(mTransformMatrix);
mMosaicView.setReady();
mMosaicView.requestRender();
}
public void runMosaicCapture() {
mMosaicView.setWarping(true);
// Call preprocess to render it to low-res and high-res RGB textures.
mMosaicView.preprocess(mTransformMatrix);
// Lock the conditional variable to ensure the order of transferGPUtoCPU and
// mMosaicFrame.processFrame().
mMosaicView.lockPreviewReadyFlag();
// Now, transfer the textures from GPU to CPU memory for processing
mMosaicView.transferGPUtoCPU();
// Wait on the condition variable (will be opened when GPU->CPU transfer is done).
mMosaicView.waitUntilPreviewReady();
mMosaicFrameProcessor.processFrame();
}
public synchronized void onFrameAvailable(SurfaceTexture surface) {
/* This function may be called by some random thread,
* so let's be safe and use synchronize. No OpenGL calls can be done here.
*/
// Updating the texture should be done in the GL thread which mMosaicView is attached.
mMosaicView.queueEvent(new Runnable() {
@Override
public void run() {
mSurfaceTexture.updateTexImage();
mSurfaceTexture.getTransformMatrix(mTransformMatrix);
}
});
// Update the transformation matrix for mosaic pre-process.
if (mCaptureState == CAPTURE_STATE_VIEWFINDER) {
runViewFinder();
} else {
runMosaicCapture();
}
}
private void hideDirectionIndicators() {
mLeftIndicator.setVisibility(View.GONE);
mRightIndicator.setVisibility(View.GONE);
}
private void showDirectionIndicators(int direction) {
switch (direction) {
case PanoProgressBar.DIRECTION_NONE:
mLeftIndicator.setVisibility(View.VISIBLE);
mRightIndicator.setVisibility(View.VISIBLE);
break;
case PanoProgressBar.DIRECTION_LEFT:
mLeftIndicator.setVisibility(View.VISIBLE);
mRightIndicator.setVisibility(View.GONE);
break;
case PanoProgressBar.DIRECTION_RIGHT:
mLeftIndicator.setVisibility(View.GONE);
mRightIndicator.setVisibility(View.VISIBLE);
break;
}
}
public void startCapture() {
// Reset values so we can do this again.
mCancelComputation = false;
mTimeTaken = System.currentTimeMillis();
mCaptureState = CAPTURE_STATE_MOSAIC;
mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan_recording);
mCaptureIndicator.setVisibility(View.VISIBLE);
showDirectionIndicators(PanoProgressBar.DIRECTION_NONE);
// XML-style animations can not be used here. The Y position has to be calculated runtime.
float ystart = mThumbnailView.getY();
ValueAnimator va1 = ObjectAnimator.ofFloat(
mThumbnailView, "y", ystart, -mThumbnailView.getHeight());
ValueAnimator va1Reverse = ObjectAnimator.ofFloat(
mThumbnailView, "y", -mThumbnailView.getHeight(), ystart);
ystart = mModePicker.getY();
float height = mCaptureLayout.getHeight();
ValueAnimator va2 = ObjectAnimator.ofFloat(
mModePicker, "y", ystart, height + 1);
ValueAnimator va2Reverse = ObjectAnimator.ofFloat(
mModePicker, "y", height + 1, ystart);
LinearInterpolator li = new LinearInterpolator();
mThumbnailViewAndModePickerOut = new AnimatorSet();
mThumbnailViewAndModePickerOut.play(va1).with(va2);
mThumbnailViewAndModePickerOut.setDuration(500);
mThumbnailViewAndModePickerOut.setInterpolator(li);
mThumbnailViewAndModePickerIn = new AnimatorSet();
mThumbnailViewAndModePickerIn.play(va1Reverse).with(va2Reverse);
mThumbnailViewAndModePickerIn.setDuration(500);
mThumbnailViewAndModePickerIn.setInterpolator(li);
mThumbnailViewAndModePickerOut.start();
mCompassValueXStart = mCompassValueXStartBuffer;
mCompassValueYStart = mCompassValueYStartBuffer;
mMinAngleX = 0;
mMaxAngleX = 0;
mMinAngleY = 0;
mMaxAngleY = 0;
mTimestamp = 0;
mMosaicFrameProcessor.setProgressListener(new MosaicFrameProcessor.ProgressListener() {
@Override
public void onProgress(boolean isFinished, float panningRateX, float panningRateY) {
if (isFinished
|| (mMaxAngleX - mMinAngleX >= DEFAULT_SWEEP_ANGLE)
|| (mMaxAngleY - mMinAngleY >= DEFAULT_SWEEP_ANGLE)) {
stopCapture(false);
} else {
updateProgress(panningRateX);
}
}
});
mPanoProgressBar.reset();
// TODO: calculate the indicator width according to different devices to reflect the actual
// angle of view of the camera device.
mPanoProgressBar.setIndicatorWidth(20);
mPanoProgressBar.setMaxProgress(DEFAULT_SWEEP_ANGLE);
mPanoProgressBar.setVisibility(View.VISIBLE);
}
private void stopCapture(boolean aborted) {
mCaptureState = CAPTURE_STATE_VIEWFINDER;
mCaptureIndicator.setVisibility(View.GONE);
hideTooFastIndication();
hideDirectionIndicators();
mMosaicFrameProcessor.setProgressListener(null);
stopCameraPreview();
mSurfaceTexture.setOnFrameAvailableListener(null);
if (!aborted && !mThreadRunning) {
showDialog(mPreparePreviewString);
runBackgroundThread(new Thread() {
@Override
public void run() {
MosaicJpeg jpeg = generateFinalMosaic(false);
if (jpeg != null && jpeg.isValid) {
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeByteArray(jpeg.data, 0, jpeg.data.length);
mMainHandler.sendMessage(mMainHandler.obtainMessage(
MSG_LOW_RES_FINAL_MOSAIC_READY, bitmap));
} else {
mMainHandler.sendMessage(mMainHandler.obtainMessage(
MSG_RESET_TO_PREVIEW));
}
}
});
}
mThumbnailViewAndModePickerIn.start();
}
private void showTooFastIndication() {
mTooFastPrompt.setVisibility(View.VISIBLE);
mFastIndicationBorder.setVisibility(View.VISIBLE);
mPanoProgressBar.setIndicatorColor(mIndicatorColorFast);
mLeftIndicator.setEnabled(true);
mRightIndicator.setEnabled(true);
}
private void hideTooFastIndication() {
mTooFastPrompt.setVisibility(View.GONE);
mFastIndicationBorder.setVisibility(View.GONE);
mPanoProgressBar.setIndicatorColor(mIndicatorColor);
mLeftIndicator.setEnabled(false);
mRightIndicator.setEnabled(false);
}
private void updateProgress(float panningRate) {
mMosaicView.setReady();
mMosaicView.requestRender();
// TODO: Now we just display warning message by the panning speed.
// Since we only support horizontal panning, we should display a warning message
// in UI when there're significant vertical movements.
if (Math.abs(panningRate * mHorizontalViewAngle) > PANNING_SPEED_THRESHOLD) {
showTooFastIndication();
} else {
hideTooFastIndication();
}
}
private void createContentView() {
setContentView(R.layout.panorama);
mCaptureState = CAPTURE_STATE_VIEWFINDER;
Resources appRes = getResources();
mCaptureLayout = (View) findViewById(R.id.pano_capture_layout);
mPanoProgressBar = (PanoProgressBar) findViewById(R.id.pano_pan_progress_bar);
mPanoProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty));
mPanoProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_done));
mIndicatorColor = appRes.getColor(R.color.pano_progress_indication);
mIndicatorColorFast = appRes.getColor(R.color.pano_progress_indication_fast);
mPanoProgressBar.setIndicatorColor(mIndicatorColor);
mPanoProgressBar.setOnDirectionChangeListener(
new PanoProgressBar.OnDirectionChangeListener () {
@Override
public void onDirectionChange(int direction) {
if (mCaptureState == CAPTURE_STATE_MOSAIC) {
showDirectionIndicators(direction);
}
}
});
mLeftIndicator = (ImageView) findViewById(R.id.pano_pan_left_indicator);
mRightIndicator = (ImageView) findViewById(R.id.pano_pan_right_indicator);
mLeftIndicator.setEnabled(false);
mRightIndicator.setEnabled(false);
mTooFastPrompt = (TextView) findViewById(R.id.pano_capture_too_fast_textview);
mFastIndicationBorder = (View) findViewById(R.id.pano_speed_indication_border);
mSavingProgressBar = (PanoProgressBar) findViewById(R.id.pano_saving_progress_bar);
mSavingProgressBar.setIndicatorWidth(0);
mSavingProgressBar.setMaxProgress(100);
mSavingProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty));
mSavingProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_indication));
mCaptureIndicator = (TextView) findViewById(R.id.pano_capture_indicator);
mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
mReviewLayout = (View) findViewById(R.id.pano_review_layout);
mReview = (ImageView) findViewById(R.id.pano_reviewarea);
mMosaicView = (MosaicRendererSurfaceView) findViewById(R.id.pano_renderer);
mMosaicView.getRenderer().setMosaicSurfaceCreateListener(this);
mModePicker = (ModePicker) findViewById(R.id.mode_picker);
mModePicker.setVisibility(View.VISIBLE);
mModePicker.setOnModeChangeListener(this);
mModePicker.setCurrentMode(ModePicker.MODE_PANORAMA);
mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan);
mShutterButton.setOnShutterButtonListener(this);
mPanoLayout = findViewById(R.id.pano_layout);
}
@Override
public void onShutterButtonClick(ShutterButton b) {
// If mSurfaceTexture == null then GL setup is not finished yet.
// No buttons can be pressed.
if (mPausing || mThreadRunning || mSurfaceTexture == null) return;
// Since this button will stay on the screen when capturing, we need to check the state
// right now.
switch (mCaptureState) {
case CAPTURE_STATE_VIEWFINDER:
startCapture();
break;
case CAPTURE_STATE_MOSAIC:
stopCapture(false);
}
}
@Override
public void onShutterButtonFocus(ShutterButton b, boolean pressed) {
}
public void reportProgress() {
mSavingProgressBar.reset();
mSavingProgressBar.setRightIncreasing(true);
Thread t = new Thread() {
@Override
public void run() {
while (mThreadRunning) {
final int progress = mMosaicFrameProcessor.reportProgress(
true, mCancelComputation);
try {
synchronized (mWaitObject) {
mWaitObject.wait(50);
}
} catch (InterruptedException e) {
throw new RuntimeException("Panorama reportProgress failed", e);
}
// Update the progress bar
runOnUiThread(new Runnable() {
public void run() {
mSavingProgressBar.setProgress(progress);
}
});
}
}
};
t.start();
}
public void saveHighResMosaic() {
runBackgroundThread(new Thread() {
@Override
public void run() {
MosaicJpeg jpeg = generateFinalMosaic(true);
if (jpeg == null) { // Cancelled by user.
mMainHandler.sendEmptyMessage(MSG_RESET_TO_PREVIEW);
} else if (!jpeg.isValid) { // Error when generating mosaic.
mMainHandler.sendEmptyMessage(MSG_GENERATE_FINAL_MOSAIC_ERROR);
} else {
int orientation = Exif.getOrientation(jpeg.data);
Uri uri = savePanorama(jpeg.data, orientation);
if (uri != null) {
// Create a thumbnail whose width is equal or bigger
// than the entire screen.
int ratio = (int) Math.ceil((double) jpeg.width /
mPanoLayout.getWidth());
int inSampleSize = Integer.highestOneBit(ratio);
mThumbnail = Thumbnail.createThumbnail(
jpeg.data, orientation, inSampleSize, uri);
}
mMainHandler.sendMessage(
mMainHandler.obtainMessage(MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL));
}
}
});
reportProgress();
}
private void showDialog(String str) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(str);
mProgressDialog.show();
}
private void runBackgroundThread(Thread thread) {
mThreadRunning = true;
thread.start();
}
private void onBackgroundThreadFinished() {
mThreadRunning = false;
if (mProgressDialog != null ) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
@OnClickAttr
public void onCancelButtonClicked(View v) {
if (mPausing || mSurfaceTexture == null) return;
mCancelComputation = true;
synchronized (mWaitObject) {
mWaitObject.notify();
}
}
@OnClickAttr
public void onThumbnailClicked(View v) {
if (mPausing || mThreadRunning || mSurfaceTexture == null) return;
showSharePopup();
}
private void showSharePopup() {
if (mThumbnail == null) return;
Uri uri = mThumbnail.getUri();
if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
// The orientation compensation is set to 0 here because we only support landscape.
mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(), 0,
findViewById(R.id.frame_layout));
}
mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
}
private void reset() {
mCaptureState = CAPTURE_STATE_VIEWFINDER;
mReviewLayout.setVisibility(View.GONE);
mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan);
mPanoProgressBar.setVisibility(View.GONE);
mCaptureLayout.setVisibility(View.VISIBLE);
mMosaicFrameProcessor.reset();
mSurfaceTexture.setOnFrameAvailableListener(this);
}
private void resetToPreview() {
reset();
if (!mPausing) startCameraPreview();
}
private void showFinalMosaic(Bitmap bitmap) {
if (bitmap != null) {
mReview.setImageBitmap(bitmap);
}
mCaptureLayout.setVisibility(View.GONE);
mReviewLayout.setVisibility(View.VISIBLE);
}
private Uri savePanorama(byte[] jpegData, int orientation) {
if (jpegData != null) {
String imagePath = PanoUtil.createName(
getResources().getString(R.string.pano_file_name_format), mTimeTaken);
return Storage.addImage(getContentResolver(), imagePath, mTimeTaken, null,
orientation, jpegData);
}
return null;
}
private void clearMosaicFrameProcessorIfNeeded() {
if (!mPausing || mThreadRunning) return;
mMosaicFrameProcessor.clear();
}
private void initMosaicFrameProcessorIfNeeded() {
if (mPausing || mThreadRunning) return;
if (mMosaicFrameProcessor == null) {
// Start the activity for the first time.
mMosaicFrameProcessor = new MosaicFrameProcessor(
mPreviewWidth, mPreviewHeight, getPreviewBufSize());
}
mMosaicFrameProcessor.initialize();
}
@Override
protected void onPause() {
super.onPause();
mPausing = true;
// Stop the capturing first.
if (mCaptureState == CAPTURE_STATE_MOSAIC) {
stopCapture(true);
reset();
}
releaseCamera();
mMosaicView.onPause();
clearMosaicFrameProcessorIfNeeded();
mSensorManager.unregisterListener(mListener);
mOrientationEventListener.disable();
System.gc();
}
@Override
protected void onResume() {
super.onResume();
mPausing = false;
mOrientationEventListener.enable();
/*
* It is not necessary to get accelerometer events at a very high rate,
* by using a game rate (SENSOR_DELAY_UI), we get an automatic
* low-pass filter, which "extracts" the gravity component of the
* acceleration. As an added benefit, we use less power and CPU
* resources.
*/
mSensorManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_UI);
mCaptureState = CAPTURE_STATE_VIEWFINDER;
setupCamera();
if (mSurfaceTexture != null) {
mSurfaceTexture.setOnFrameAvailableListener(this);
startCameraPreview();
}
// Camera must be initialized before MosaicFrameProcessor is initialized. The preview size
// has to be decided by camera device.
initMosaicFrameProcessorIfNeeded();
mMosaicView.onResume();
}
private void updateCompassValue() {
if (mCaptureState == CAPTURE_STATE_VIEWFINDER) return;
// By what angle has the camera moved since start of capture?
mTraversedAngleX = (int) (mCompassValueX - mCompassValueXStart);
mTraversedAngleY = (int) (mCompassValueY - mCompassValueYStart);
mMinAngleX = Math.min(mMinAngleX, mTraversedAngleX);
mMaxAngleX = Math.max(mMaxAngleX, mTraversedAngleX);
mMinAngleY = Math.min(mMinAngleY, mTraversedAngleY);
mMaxAngleY = Math.max(mMaxAngleY, mTraversedAngleY);
// Use orientation to identify if the user is panning to the right or the left.
switch (mDeviceOrientation) {
case 0:
mPanoProgressBar.setProgress(-mTraversedAngleX);
break;
case 1:
mPanoProgressBar.setProgress(mTraversedAngleY);
break;
case 2:
mPanoProgressBar.setProgress(mTraversedAngleX);
break;
case 3:
mPanoProgressBar.setProgress(-mTraversedAngleY);
break;
}
mPanoProgressBar.invalidate();
}
private final SensorEventListener mListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
if (mTimestamp != 0) {
final float dT = (event.timestamp - mTimestamp) * NS2S;
mCompassValueX += event.values[1] * dT * 180.0f / Math.PI;
mCompassValueY += event.values[0] * dT * 180.0f / Math.PI;
mCompassValueXStartBuffer = mCompassValueX;
mCompassValueYStartBuffer = mCompassValueY;
updateCompassValue();
}
mTimestamp = event.timestamp;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
public MosaicJpeg generateFinalMosaic(boolean highRes) {
if (mMosaicFrameProcessor.createMosaic(highRes) == Mosaic.MOSAIC_RET_CANCELLED) {
return null;
}
byte[] imageData = mMosaicFrameProcessor.getFinalMosaicNV21();
if (imageData == null) {
Log.e(TAG, "getFinalMosaicNV21() returned null.");
return new MosaicJpeg();
}
int len = imageData.length - 8;
int width = (imageData[len + 0] << 24) + ((imageData[len + 1] & 0xFF) << 16)
+ ((imageData[len + 2] & 0xFF) << 8) + (imageData[len + 3] & 0xFF);
int height = (imageData[len + 4] << 24) + ((imageData[len + 5] & 0xFF) << 16)
+ ((imageData[len + 6] & 0xFF) << 8) + (imageData[len + 7] & 0xFF);
Log.v(TAG, "ImLength = " + (len) + ", W = " + width + ", H = " + height);
if (width <= 0 || height <= 0) {
// TODO: pop up a error meesage indicating that the final result is not generated.
Log.e(TAG, "width|height <= 0!!, len = " + (len) + ", W = " + width + ", H = " +
height);
return new MosaicJpeg();
}
YuvImage yuvimage = new YuvImage(imageData, ImageFormat.NV21, width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, width, height), 100, out);
try {
out.close();
} catch (Exception e) {
Log.e(TAG, "Exception in storing final mosaic", e);
return new MosaicJpeg();
}
return new MosaicJpeg(out.toByteArray(), width, height);
}
private void setPreviewTexture(SurfaceTexture surface) {
try {
mCameraDevice.setPreviewTexture(surface);
} catch (Throwable ex) {
releaseCamera();
throw new RuntimeException("setPreviewTexture failed", ex);
}
}
private void startCameraPreview() {
// If we're previewing already, stop the preview first (this will blank
// the screen).
if (mCameraState != PREVIEW_STOPPED) stopCameraPreview();
setPreviewTexture(mSurfaceTexture);
try {
Log.v(TAG, "startPreview");
mCameraDevice.startPreview();
} catch (Throwable ex) {
releaseCamera();
throw new RuntimeException("startPreview failed", ex);
}
mCameraState = PREVIEW_ACTIVE;
}
private void stopCameraPreview() {
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
Log.v(TAG, "stopPreview");
mCameraDevice.stopPreview();
}
mCameraState = PREVIEW_STOPPED;
}
}
| true | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Util.enterLightsOutMode(window);
Util.initializeScreenBrightness(window, getContentResolver());
createContentView();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (mSensor == null) {
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
mOrientationEventListener = new PanoOrientationEventListener(this);
mTransformMatrix = new float[16];
mPreparePreviewString =
getResources().getString(R.string.pano_dialog_prepare_preview);
mDialogTitle = getResources().getString(R.string.pano_dialog_title);
mDialogOk = getResources().getString(R.string.dialog_ok);
mMainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOW_RES_FINAL_MOSAIC_READY:
onBackgroundThreadFinished();
showFinalMosaic((Bitmap) msg.obj);
saveHighResMosaic();
break;
case MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL:
onBackgroundThreadFinished();
// Set the thumbnail bitmap here because mThumbnailView must be accessed
// from the UI thread.
if (mThumbnail != null) {
mThumbnailView.setBitmap(mThumbnail.getBitmap());
}
resetToPreview();
break;
case MSG_GENERATE_FINAL_MOSAIC_ERROR:
onBackgroundThreadFinished();
mAlertDialog.show();
break;
case MSG_RESET_TO_PREVIEW:
onBackgroundThreadFinished();
resetToPreview();
}
clearMosaicFrameProcessorIfNeeded();
}
};
mAlertDialog = (new AlertDialog.Builder(this))
.setTitle(mDialogTitle)
.setMessage(R.string.pano_dialog_panorama_failed)
.create();
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, mDialogOk,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
resetToPreview();
}
});
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Util.enterLightsOutMode(window);
Util.initializeScreenBrightness(window, getContentResolver());
createContentView();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (mSensor == null) {
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
mOrientationEventListener = new PanoOrientationEventListener(this);
mTransformMatrix = new float[16];
mPreparePreviewString =
getResources().getString(R.string.pano_dialog_prepare_preview);
mDialogTitle = getResources().getString(R.string.pano_dialog_title);
mDialogOk = getResources().getString(R.string.dialog_ok);
mMainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOW_RES_FINAL_MOSAIC_READY:
onBackgroundThreadFinished();
showFinalMosaic((Bitmap) msg.obj);
saveHighResMosaic();
break;
case MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL:
onBackgroundThreadFinished();
// Set the thumbnail bitmap here because mThumbnailView must be accessed
// from the UI thread.
if (mThumbnail != null) {
mThumbnailView.setBitmap(mThumbnail.getBitmap());
}
resetToPreview();
break;
case MSG_GENERATE_FINAL_MOSAIC_ERROR:
onBackgroundThreadFinished();
if (mPausing) {
resetToPreview();
} else {
mAlertDialog.show();
}
break;
case MSG_RESET_TO_PREVIEW:
onBackgroundThreadFinished();
resetToPreview();
}
clearMosaicFrameProcessorIfNeeded();
}
};
mAlertDialog = (new AlertDialog.Builder(this))
.setTitle(mDialogTitle)
.setMessage(R.string.pano_dialog_panorama_failed)
.create();
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, mDialogOk,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
resetToPreview();
}
});
}
|
diff --git a/src/main/java/org/jboss/ejb/client/EJBHomeInterceptor.java b/src/main/java/org/jboss/ejb/client/EJBHomeInterceptor.java
index a543a5a..1576fe7 100644
--- a/src/main/java/org/jboss/ejb/client/EJBHomeInterceptor.java
+++ b/src/main/java/org/jboss/ejb/client/EJBHomeInterceptor.java
@@ -1,193 +1,198 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ejb.client;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* A {@link EJBClientInterceptor} which is responsible for intercepting the returning value of "create"/"finder" methods
* on a {@link javax.ejb.EJBHome} proxy. This interceptor just lets the invocation proceed in its {@link #handleInvocation(EJBClientInvocationContext)}
* method. However, in its {@link #handleInvocationResult(EJBClientInvocationContext)} method it does the following:
* <ol>
* <li>Check to see if the invocation is happening on a EJBHome proxy. It does this by checking the {@link EJBLocator}
* type of the {@link EJBClientInvocationContext invocation context}. If it finds that the invocation is not
* on a EJBHome proxy, then the {@link #handleInvocationResult(EJBClientInvocationContext)} just returns back the
* original result.
* </li>
* <li>
* Check to see if the invoked method is a "create"/"finder" method. The EJB spec states that each EJBHome interface
* can have any number of "create"/"finder" methods, but the method name should begin with "create"/"find". This is what the
* interceptor checks for. If the invocation is not for a "create"/"find" method, then the {@link #handleInvocationResult(EJBClientInvocationContext)}
* just returns back the original result.
* </li>
* <li>
* Check to see if the original returned instance is a {@link EJBClient#isEJBProxy(Object) EJB proxy} or a {@link Collection} of {@link EJBClient#isEJBProxy(Object) EJB proxies}.
* If it isn't, then the {@link #handleInvocationResult(EJBClientInvocationContext)} method just returns back the
* original result. If it finds that it's an EJB proxy or a Collection of EJB proxies, then the {@link #handleInvocationResult(EJBClientInvocationContext)}
* recreates the proxy/proxies by using the {@link org.jboss.ejb.client.EJBInvocationHandler#getEjbClientContextIdentifier() EJB client context identifier}
* that's applicable to the EJBHome proxy on which this invocation was done. This way, the EJB proxies returned
* by calls to "create"/"finder" methods on the EJBHome proxy will always be associated with the EJB client context identifier
* that's applicable to the EJBHome proxy
* </li>
* </ol>
* An example of where this interceptor plays a role is as follows:
* <code>
* final Properties jndiProps = new Properties();
* // create a scoped EJB client context
* jndiProps.put("org.jboss.ejb.client.scoped.context",true);
* // other jndi props
* ...
* final Context ctx = new InitialContext(jndiProps);
* final SomeEJBRemoteHome remoteHome = (SomeEJBRemoteHome) ctx.lookup("ejb:/foo/bar/dist/bean!remotehomeinterface");
* // now create the EJB remote object.
* // this returned "SomeEJBRemote" proxy MUST have the same EJB client context identifier that was
* // applicable for the "remoteHome" proxy that we created a few lines above. That way any subsequent
* // invocation on this "remoteBean" will always use the correct EJB client context
* final SomeEJBRemote remoteBean = remoteHome.create();
* // now invoke on the bean
* remoteBean.doSomething();
* <p/>
* </code>
*
* @author Jaikiran Pai
* @see https://issues.jboss.org/browse/EJBCLIENT-51
*/
final class EJBHomeInterceptor implements EJBClientInterceptor {
@Override
public void handleInvocation(final EJBClientInvocationContext invocationContext) throws Exception {
// we just pass along the request
invocationContext.sendRequest();
}
@Override
public Object handleInvocationResult(final EJBClientInvocationContext invocationContext) throws Exception {
final Object originalResult = invocationContext.getResult();
if (originalResult == null) {
return originalResult;
}
// if it's not an invocation on a EJB home view, then just return back the original result
if (!isEJBHomeInvocation(invocationContext)) {
return originalResult;
}
final boolean isCreateMethod = isCreateMethodInvocation(invocationContext);
final boolean isFinderMethod = isFinderMethod(invocationContext);
boolean finderReturnTypeCollection = false;
// if it's not a "createXXX" method invocation nor an entity home "finder" method invocation, then just return back the original result
if (!isCreateMethod && !isFinderMethod) {
return originalResult;
}
// if it's a create method then the return type of the method isn't expected to be a Collection, unlike ceratin finder methods (on entity beans)
if (isCreateMethod) {
// if the original result isn't a EJB proxy, then we just return back the original result
if (!EJBClient.isEJBProxy(originalResult)) {
return originalResult;
}
} else if (isFinderMethod) {
// a finder method can return a single result or a collection, so check the type and if the return type is neither a Collection
// nor a (single) EJB proxy, then just return back the original result
if (!(originalResult instanceof Collection) && !EJBClient.isEJBProxy(originalResult)) {
return originalResult;
}
if (originalResult instanceof Collection) {
// we have identified this to be a finder method returning a Collection. Now ensure that the Collection contains
// all EJB proxies. If it doesn't, then just return back the original result
for (Object finderResult : (Collection) originalResult) {
if (finderResult != null && !EJBClient.isEJBProxy(finderResult)) {
return originalResult;
}
}
// make a note that this is a finder method returning a collection of EJB proxies
finderReturnTypeCollection = true;
}
}
// at this point we have identified the invocation to be a "createXXX" or a "findXXX" method invocation on a EJB
// home view and the return object being a EJB proxy or a Collection of EJB proxies. So we now update that proxy/proxies to use
// the EJB client context identifier that's applicable for the EJB home proxy on which this invocation was done
if (finderReturnTypeCollection) {
final Collection ejbProxies = (Collection) originalResult;
final List recreatedEJBProxies = new ArrayList();
// recreate each proxy in the Collection, to use the context identifier
- for (Object ejbProxy : ejbProxies) {
+ for (final Object ejbProxy : ejbProxies) {
+ if (ejbProxy == null) {
+ // nothing to recreate, just add null to the collection to be returned
+ recreatedEJBProxies.add(null);
+ continue;
+ }
// we *don't* change the locator of the original proxy
final EJBLocator ejbLocator = EJBClient.getLocatorFor(ejbProxy);
// get the EJB client context identifier (if any) that's applicable for the home view on which this
// invocation happened
final EJBClientContextIdentifier ejbClientContextIdentifier = invocationContext.getInvocationHandler().getEjbClientContextIdentifier();
// now recreate the proxy with the EJB client context identifier
final Object recreatedProxy = EJBClient.createProxy(ejbLocator, ejbClientContextIdentifier);
// add it to the collection to be returned
recreatedEJBProxies.add(recreatedProxy);
}
// return the Collection containing the recreated proxies
return recreatedEJBProxies;
} else {
final Object ejbProxy = originalResult;
// we *don't* change the locator of the original proxy
final EJBLocator ejbLocator = EJBClient.getLocatorFor(ejbProxy);
// get the EJB client context identifier (if any) that's applicable for the home view on which this
// invocation happened
final EJBClientContextIdentifier ejbClientContextIdentifier = invocationContext.getInvocationHandler().getEjbClientContextIdentifier();
// now recreate the proxy with the EJB client context identifier
return EJBClient.createProxy(ejbLocator, ejbClientContextIdentifier);
}
}
/**
* Returns true if the invocation happened on a EJB home view. Else returns false.
*
* @param invocationContext
* @return
*/
private boolean isEJBHomeInvocation(final EJBClientInvocationContext invocationContext) {
final EJBLocator locator = invocationContext.getLocator();
return locator instanceof EJBHomeLocator;
}
/**
* Returns true if the invocation is for a "create<...>" method. Else returns false.
*
* @param invocationContext The invocation context
* @return
*/
private boolean isCreateMethodInvocation(final EJBClientInvocationContext invocationContext) {
final Method invokedMethod = invocationContext.getInvokedMethod();
return invokedMethod.getName().startsWith("create");
}
/**
* Returns true if the invocation is for a finder method of an entity bean home. Else returns false.
* Finder methods on entity bean remote home interface are expected to start with the name <code>"find"</code>
* and one such method <code>findByPrimaryKey</code> is mandatory.
*
* @param invocationContext The invocation context
* @return
*/
private boolean isFinderMethod(final EJBClientInvocationContext invocationContext) {
final Method invokedMethod = invocationContext.getInvokedMethod();
return invokedMethod.getName().equals("findByPrimaryKey") || invokedMethod.getName().startsWith("find");
}
}
| true | true | public Object handleInvocationResult(final EJBClientInvocationContext invocationContext) throws Exception {
final Object originalResult = invocationContext.getResult();
if (originalResult == null) {
return originalResult;
}
// if it's not an invocation on a EJB home view, then just return back the original result
if (!isEJBHomeInvocation(invocationContext)) {
return originalResult;
}
final boolean isCreateMethod = isCreateMethodInvocation(invocationContext);
final boolean isFinderMethod = isFinderMethod(invocationContext);
boolean finderReturnTypeCollection = false;
// if it's not a "createXXX" method invocation nor an entity home "finder" method invocation, then just return back the original result
if (!isCreateMethod && !isFinderMethod) {
return originalResult;
}
// if it's a create method then the return type of the method isn't expected to be a Collection, unlike ceratin finder methods (on entity beans)
if (isCreateMethod) {
// if the original result isn't a EJB proxy, then we just return back the original result
if (!EJBClient.isEJBProxy(originalResult)) {
return originalResult;
}
} else if (isFinderMethod) {
// a finder method can return a single result or a collection, so check the type and if the return type is neither a Collection
// nor a (single) EJB proxy, then just return back the original result
if (!(originalResult instanceof Collection) && !EJBClient.isEJBProxy(originalResult)) {
return originalResult;
}
if (originalResult instanceof Collection) {
// we have identified this to be a finder method returning a Collection. Now ensure that the Collection contains
// all EJB proxies. If it doesn't, then just return back the original result
for (Object finderResult : (Collection) originalResult) {
if (finderResult != null && !EJBClient.isEJBProxy(finderResult)) {
return originalResult;
}
}
// make a note that this is a finder method returning a collection of EJB proxies
finderReturnTypeCollection = true;
}
}
// at this point we have identified the invocation to be a "createXXX" or a "findXXX" method invocation on a EJB
// home view and the return object being a EJB proxy or a Collection of EJB proxies. So we now update that proxy/proxies to use
// the EJB client context identifier that's applicable for the EJB home proxy on which this invocation was done
if (finderReturnTypeCollection) {
final Collection ejbProxies = (Collection) originalResult;
final List recreatedEJBProxies = new ArrayList();
// recreate each proxy in the Collection, to use the context identifier
for (Object ejbProxy : ejbProxies) {
// we *don't* change the locator of the original proxy
final EJBLocator ejbLocator = EJBClient.getLocatorFor(ejbProxy);
// get the EJB client context identifier (if any) that's applicable for the home view on which this
// invocation happened
final EJBClientContextIdentifier ejbClientContextIdentifier = invocationContext.getInvocationHandler().getEjbClientContextIdentifier();
// now recreate the proxy with the EJB client context identifier
final Object recreatedProxy = EJBClient.createProxy(ejbLocator, ejbClientContextIdentifier);
// add it to the collection to be returned
recreatedEJBProxies.add(recreatedProxy);
}
// return the Collection containing the recreated proxies
return recreatedEJBProxies;
} else {
final Object ejbProxy = originalResult;
// we *don't* change the locator of the original proxy
final EJBLocator ejbLocator = EJBClient.getLocatorFor(ejbProxy);
// get the EJB client context identifier (if any) that's applicable for the home view on which this
// invocation happened
final EJBClientContextIdentifier ejbClientContextIdentifier = invocationContext.getInvocationHandler().getEjbClientContextIdentifier();
// now recreate the proxy with the EJB client context identifier
return EJBClient.createProxy(ejbLocator, ejbClientContextIdentifier);
}
}
| public Object handleInvocationResult(final EJBClientInvocationContext invocationContext) throws Exception {
final Object originalResult = invocationContext.getResult();
if (originalResult == null) {
return originalResult;
}
// if it's not an invocation on a EJB home view, then just return back the original result
if (!isEJBHomeInvocation(invocationContext)) {
return originalResult;
}
final boolean isCreateMethod = isCreateMethodInvocation(invocationContext);
final boolean isFinderMethod = isFinderMethod(invocationContext);
boolean finderReturnTypeCollection = false;
// if it's not a "createXXX" method invocation nor an entity home "finder" method invocation, then just return back the original result
if (!isCreateMethod && !isFinderMethod) {
return originalResult;
}
// if it's a create method then the return type of the method isn't expected to be a Collection, unlike ceratin finder methods (on entity beans)
if (isCreateMethod) {
// if the original result isn't a EJB proxy, then we just return back the original result
if (!EJBClient.isEJBProxy(originalResult)) {
return originalResult;
}
} else if (isFinderMethod) {
// a finder method can return a single result or a collection, so check the type and if the return type is neither a Collection
// nor a (single) EJB proxy, then just return back the original result
if (!(originalResult instanceof Collection) && !EJBClient.isEJBProxy(originalResult)) {
return originalResult;
}
if (originalResult instanceof Collection) {
// we have identified this to be a finder method returning a Collection. Now ensure that the Collection contains
// all EJB proxies. If it doesn't, then just return back the original result
for (Object finderResult : (Collection) originalResult) {
if (finderResult != null && !EJBClient.isEJBProxy(finderResult)) {
return originalResult;
}
}
// make a note that this is a finder method returning a collection of EJB proxies
finderReturnTypeCollection = true;
}
}
// at this point we have identified the invocation to be a "createXXX" or a "findXXX" method invocation on a EJB
// home view and the return object being a EJB proxy or a Collection of EJB proxies. So we now update that proxy/proxies to use
// the EJB client context identifier that's applicable for the EJB home proxy on which this invocation was done
if (finderReturnTypeCollection) {
final Collection ejbProxies = (Collection) originalResult;
final List recreatedEJBProxies = new ArrayList();
// recreate each proxy in the Collection, to use the context identifier
for (final Object ejbProxy : ejbProxies) {
if (ejbProxy == null) {
// nothing to recreate, just add null to the collection to be returned
recreatedEJBProxies.add(null);
continue;
}
// we *don't* change the locator of the original proxy
final EJBLocator ejbLocator = EJBClient.getLocatorFor(ejbProxy);
// get the EJB client context identifier (if any) that's applicable for the home view on which this
// invocation happened
final EJBClientContextIdentifier ejbClientContextIdentifier = invocationContext.getInvocationHandler().getEjbClientContextIdentifier();
// now recreate the proxy with the EJB client context identifier
final Object recreatedProxy = EJBClient.createProxy(ejbLocator, ejbClientContextIdentifier);
// add it to the collection to be returned
recreatedEJBProxies.add(recreatedProxy);
}
// return the Collection containing the recreated proxies
return recreatedEJBProxies;
} else {
final Object ejbProxy = originalResult;
// we *don't* change the locator of the original proxy
final EJBLocator ejbLocator = EJBClient.getLocatorFor(ejbProxy);
// get the EJB client context identifier (if any) that's applicable for the home view on which this
// invocation happened
final EJBClientContextIdentifier ejbClientContextIdentifier = invocationContext.getInvocationHandler().getEjbClientContextIdentifier();
// now recreate the proxy with the EJB client context identifier
return EJBClient.createProxy(ejbLocator, ejbClientContextIdentifier);
}
}
|
diff --git a/examples/tesb/cxf-jmx/client/src/main/java/org/talend/esb/examples/SimpleClient.java b/examples/tesb/cxf-jmx/client/src/main/java/org/talend/esb/examples/SimpleClient.java
index 016323ce7..5b51f0eee 100644
--- a/examples/tesb/cxf-jmx/client/src/main/java/org/talend/esb/examples/SimpleClient.java
+++ b/examples/tesb/cxf-jmx/client/src/main/java/org/talend/esb/examples/SimpleClient.java
@@ -1,60 +1,62 @@
/*
* #%L
* CXF :: Example :: SimpleService :: TESB container
* %%
* Copyright (C) 2011 - 2012 Talend Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.talend.esb.examples;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class SimpleClient {
public SimpleClient() {
}
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = null;
if (args[0].equals("war")) {
context = new ClassPathXmlApplicationContext(
new String[] { "META-INF/spring/client-beans-war.xml" });
} else {
context = new ClassPathXmlApplicationContext(
new String[] { "META-INF/spring/client-beans-osgi.xml" });
}
SimpleService client = (SimpleService) context.getBean("simpleClient");
for (int i = 0; i < 100; i++) {
String response = client.sayHi("Alex");
System.out.println(response);
}
for (int i = 1; i < 6; i++) {
int result = client.doubleIt(i);
System.out.println(result);
}
// "Incorrect name" exception would be thrown
- String response = client.sayHi("Joe");
- System.out.println(response);
+ try {
+ String response = client.sayHi("Joe");
+ }catch(RuntimeException e) {
+ e.printStackTrace();
+ }
- System.exit(0);
}
}
| false | true | public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = null;
if (args[0].equals("war")) {
context = new ClassPathXmlApplicationContext(
new String[] { "META-INF/spring/client-beans-war.xml" });
} else {
context = new ClassPathXmlApplicationContext(
new String[] { "META-INF/spring/client-beans-osgi.xml" });
}
SimpleService client = (SimpleService) context.getBean("simpleClient");
for (int i = 0; i < 100; i++) {
String response = client.sayHi("Alex");
System.out.println(response);
}
for (int i = 1; i < 6; i++) {
int result = client.doubleIt(i);
System.out.println(result);
}
// "Incorrect name" exception would be thrown
String response = client.sayHi("Joe");
System.out.println(response);
System.exit(0);
}
| public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = null;
if (args[0].equals("war")) {
context = new ClassPathXmlApplicationContext(
new String[] { "META-INF/spring/client-beans-war.xml" });
} else {
context = new ClassPathXmlApplicationContext(
new String[] { "META-INF/spring/client-beans-osgi.xml" });
}
SimpleService client = (SimpleService) context.getBean("simpleClient");
for (int i = 0; i < 100; i++) {
String response = client.sayHi("Alex");
System.out.println(response);
}
for (int i = 1; i < 6; i++) {
int result = client.doubleIt(i);
System.out.println(result);
}
// "Incorrect name" exception would be thrown
try {
String response = client.sayHi("Joe");
}catch(RuntimeException e) {
e.printStackTrace();
}
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/properties/ClusterDescriptionProperty.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/properties/ClusterDescriptionProperty.java
index 2708c0fb..331ac80e 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/properties/ClusterDescriptionProperty.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/properties/ClusterDescriptionProperty.java
@@ -1,344 +1,344 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical.properties;
import java.io.Serializable;
import java.util.LinkedList;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.properties.AbstractProperty;
import de.tuilmenau.ics.fog.packets.hierarchical.DiscoveryEntry;
import de.tuilmenau.ics.fog.routing.hierarchical.election.BullyPriority;
import de.tuilmenau.ics.fog.routing.hierarchical.management.ClusterName;
import de.tuilmenau.ics.fog.routing.hierarchical.management.HierarchyLevel;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMName;
import de.tuilmenau.ics.fog.ui.Logging;
/**
* This class is used for describing a cluster, which both the connection source and the destination should
* have in common (the connection destination should join the described cluster).
*/
public class ClusterDescriptionProperty extends AbstractProperty
{
/**
* Stores the hierarchy level of the cluster
*/
private HierarchyLevel mHierarchyLevel = null;
/**
* Stores the unique clusterID
*/
private Long mClusterID = null;
/**
* Stores the unique coordinator ID
*/
private int mCoordinatorID = 0;
/**
* Stores all registered cluster member descriptions
*/
private LinkedList<ClusterMemberDescription> mClusterMemberDescriptions = new LinkedList<ClusterMemberDescription>();
private Name mSourceName;
private HRMName mSourceAddress;
private static final long serialVersionUID = 7561293731302599090L;
/**
* Constructor
*
* @param pClusterID the already created unique ID for the cluster the sender and the receiver should be part of
* @param pHierarchyLevel the hierarchy level of the cluster
* @param pCoordinatorID the unique ID of the coordinator (or 0 if none exists)
*/
public ClusterDescriptionProperty(Long pClusterID, HierarchyLevel pHierarchyLevel, int pCoordinatorID)
{
Logging.log(this, "Setting target cluster ID " + pClusterID);
mClusterID = pClusterID;
mHierarchyLevel = pHierarchyLevel;
mCoordinatorID = pCoordinatorID;
Logging.log(this, "Setting cluster hierarchy level: " + pHierarchyLevel.getValue());
}
/**
* Returns the unique coordinator ID
*
* @return the coordinator ID
*/
public int getCoordinatorID()
{
return mCoordinatorID;
}
/**
* Returns the unique cluster ID
*
* @return the unique cluster ID
*/
public Long getClusterID()
{
return mClusterID;
}
/**
* Returns the hierarchy level
*
* @return the hierarchy level
*/
public HierarchyLevel getHierarchyLevel()
{
return mHierarchyLevel;
}
/**
* Adds a description of a cluster member to the internal database
*
* @param pClusterID the unique cluster ID
* @param pToken the unique coordinator ID
* @param pPriority the Bully priority of this cluster member
*/
public ClusterMemberDescription addClusterMember(Long pClusterID, int pToken, BullyPriority pPriority)
{
// create the new member
ClusterMemberDescription tResult = new ClusterMemberDescription(pClusterID, pToken, pPriority);
// add the cluster member to the database
Logging.log(this, "Adding cluster member description: " + tResult);
synchronized (mClusterMemberDescriptions) {
mClusterMemberDescriptions.add(tResult);
}
return tResult;
}
/**
* Returns a list of descriptions about known cluster members
*
* @return the list of registered cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterMemberDescription> getClusterMemberDescriptions()
{
LinkedList<ClusterMemberDescription> tResult = null;
synchronized (mClusterMemberDescriptions) {
tResult = (LinkedList<ClusterMemberDescription>) mClusterMemberDescriptions.clone();
}
return tResult;
}
/**
* Generates a descriptive string about the object
*
* @return the descriptive string
*/
public String toString()
{
- String tResult = getClass().getSimpleName() + " with ";
+ String tResult = getClass().getSimpleName() + "(";
synchronized (mClusterMemberDescriptions) {
- tResult += mClusterMemberDescriptions.size() + " cluster member descriptions";
+ tResult += mClusterMemberDescriptions.size() + " member descriptions)";
- int i = 0;
- for (ClusterMemberDescription tEntry : mClusterMemberDescriptions){
- tResult += "\n ..[" + i + "]: " + tEntry.toString();
- i++;
- }
+// int i = 0;
+// for (ClusterMemberDescription tEntry : mClusterMemberDescriptions){
+// tResult += "\n ..[" + i + "]: " + tEntry.toString();
+// i++;
+// }
}
return tResult;
}
/**
* This class is used to describe a cluster member of the cluster, which is described by the parent ClusterDescriptionProperty.
*/
public class ClusterMemberDescription implements Serializable
{
private static final long serialVersionUID = -6712697028015706544L;
/**
* Stores the unique ID of the cluster
*/
private Long mClusterID;
/**
* Stores the unique ID of the coordinator
*/
private int mCoordinatorID;
private ClusterName mPredecessor;
private LinkedList<DiscoveryEntry> mDiscoveries;
private HierarchyLevel mHierarchyLevel = null;
private BullyPriority mPriority = null;
/**
* Constructor
*
* @param pClusterID the unique ID of the cluster
* @param pCoordinatorID the unique ID of the coordinator
*/
public ClusterMemberDescription(Long pClusterID, int pCoordinatorID, BullyPriority pPriority)
{
mClusterID = pClusterID;
mCoordinatorID = pCoordinatorID;
mPriority = pPriority;
}
/**
*
* @return This is the priority of the cluster member. It is already here transmitted to
* decrease communication complexity.
*/
public BullyPriority getPriority()
{
return mPriority;
}
/**
*
* @param pLevel Set the level of the source cluster here. In general this is one level below the level of
* the cluster that should be joined. So the level of this nested exception is below the level of the
* ClusterParticipationProperty this nested participation is part of.
*/
public void setHierarchyLevel(HierarchyLevel pHierarchyLevel)
{
Logging.log(this, "Setting cluster member hierarchy level: " + pHierarchyLevel.getValue());
mHierarchyLevel = pHierarchyLevel;
}
/**
* Get the level of the source cluster here. In general this is one level below the level of
* the cluster that should be joined. So the level of this nested exception is below the level of the
* ClusterParticipationProperty this nested participation is part of.
*
* @return The level of the cluster that should participate is returned.
*/
public HierarchyLevel getHierarchyLevel()
{
return mHierarchyLevel;
}
/**
*
* @param pAddress This is the address of the node that is about to join the cluster.
*/
public void setSourceL2Address(HRMName pAddress)
{
mSourceAddress = pAddress;
}
/**
*
* @param pPredecessor This has to be the second last cluster of the path to the target cluster. Once the target interprets
* that cluster it knows which "outgoing" cluster should be used. in order to reach the node that generated the participation
* property.
*/
public void setPredecessor(ClusterName pPredecessor)
{
mPredecessor = pPredecessor;
}
/**
*
* @return This is be the second last cluster of the path to the target cluster. Once the target interprets
* this cluster it knows which "outgoing" cluster should be used. in order to reach the node that generated the participation
* property.
*
*/
public ClusterName getPredecessor()
{
return mPredecessor;
}
/**
*
* @param pSource This is the name of the host or node that is about to join the target cluster.
*/
public void setSourceName(Name pSource)
{
mSourceName = pSource;
}
/**
*
* @return This is the name of the host or node that is about to join the target cluster.
*/
public Name getSourceName()
{
return mSourceName;
}
/**
*
* @return The address of the entity that wishes to become member of the cluster is returned.
*/
public HRMName getSourceL2Address()
{
return mSourceAddress;
}
/**
*
* @return The token of the cluster the coordinator is responsible for is returned here.
*/
public int getCoordinatorID()
{
return mCoordinatorID;
}
/**
* As the target cluster/coordinator has to be informed about the topology and especially has to receive
* the knowledge as to how the source node of the participation request can be reached.
*
* @param pEntry
*/
public void addDiscoveryEntry(DiscoveryEntry pEntry)
{
if(mDiscoveries == null) {
mDiscoveries = new LinkedList<DiscoveryEntry>();
mDiscoveries.add(pEntry);
} else {
mDiscoveries.add(pEntry);
}
}
/**
*
* @return The neighbors of the source node are returned by this method.
*/
public LinkedList<DiscoveryEntry> getNeighbors()
{
return mDiscoveries;
}
/**
*
* @return The cluster identity the coordinator represents is returned.
*/
public Long getClusterID()
{
return mClusterID;
}
/**
* Returns a descriptive string about this object
*
* @return the descriptive string
*/
public String toString()
{
return getClass().getSimpleName() + "(ClusterID=" + getClusterID() + ", CoordID=" + getCoordinatorID() + (getPriority() != null ? ", PeerPrio=" + getPriority().getValue() : "") + ")";
}
}
}
| false | true | public String toString()
{
String tResult = getClass().getSimpleName() + " with ";
synchronized (mClusterMemberDescriptions) {
tResult += mClusterMemberDescriptions.size() + " cluster member descriptions";
int i = 0;
for (ClusterMemberDescription tEntry : mClusterMemberDescriptions){
tResult += "\n ..[" + i + "]: " + tEntry.toString();
i++;
}
}
return tResult;
}
| public String toString()
{
String tResult = getClass().getSimpleName() + "(";
synchronized (mClusterMemberDescriptions) {
tResult += mClusterMemberDescriptions.size() + " member descriptions)";
// int i = 0;
// for (ClusterMemberDescription tEntry : mClusterMemberDescriptions){
// tResult += "\n ..[" + i + "]: " + tEntry.toString();
// i++;
// }
}
return tResult;
}
|
diff --git a/labirynth/src/com/flexymind/labirynth/storage/SettingsStorage.java b/labirynth/src/com/flexymind/labirynth/storage/SettingsStorage.java
index d168865..b193219 100644
--- a/labirynth/src/com/flexymind/labirynth/storage/SettingsStorage.java
+++ b/labirynth/src/com/flexymind/labirynth/storage/SettingsStorage.java
@@ -1,57 +1,58 @@
package com.flexymind.labirynth.storage;
import android.content.Context;
import android.content.SharedPreferences;
public class SettingsStorage {
//////////////////////////////////////////////////
///// Константы для настроек //////
//////////////////////////////////////////////////
private static final String STORAGE = "Labirynth settings";
private static final String ACCELX = "accelX";
private static final String ACCELY = "accelY";
private static final String ACCELZ = "accelZ";
private static Context context = null;
public SettingsStorage(Context initContext){
context = initContext;
}
/**
* Инициализация хранилища.
* @param initContext - контекст приложения
*/
public static void initialize(Context initContext){
context = initContext;
}
/**
* Сохраняет состояние акселерометра в настройках
* @param pos 3-d вектор состояния акселерометра
* @return true если сохранено успешно
*/
public static boolean saveAcellPosition(float[] pos){
if (pos.length < 3)
return false;
SharedPreferences settings = context.getSharedPreferences(STORAGE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putFloat(ACCELX, pos[0]);
edit.putFloat(ACCELY, pos[1]);
edit.putFloat(ACCELZ, pos[2]);
+ edit.commit();
return true;
}
/**
* Загружает состояние акселерометра из настроек, или возвращает нулевой вектор (не ссылку на null !)
*/
public static float[] getAcellPosition(){
float[] pos = new float[]{0,0,0};
SharedPreferences settings = context.getSharedPreferences(STORAGE, 0);
pos[0] = settings.getFloat(ACCELX, 0);
pos[1] = settings.getFloat(ACCELY, 0);
pos[2] = settings.getFloat(ACCELZ, 0);
return pos;
}
}
| true | true | public static boolean saveAcellPosition(float[] pos){
if (pos.length < 3)
return false;
SharedPreferences settings = context.getSharedPreferences(STORAGE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putFloat(ACCELX, pos[0]);
edit.putFloat(ACCELY, pos[1]);
edit.putFloat(ACCELZ, pos[2]);
return true;
}
| public static boolean saveAcellPosition(float[] pos){
if (pos.length < 3)
return false;
SharedPreferences settings = context.getSharedPreferences(STORAGE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putFloat(ACCELX, pos[0]);
edit.putFloat(ACCELY, pos[1]);
edit.putFloat(ACCELZ, pos[2]);
edit.commit();
return true;
}
|
diff --git a/src/test/java/npanday/its/IntegrationTestSuite.java b/src/test/java/npanday/its/IntegrationTestSuite.java
index 48987c0..7b12604 100644
--- a/src/test/java/npanday/its/IntegrationTestSuite.java
+++ b/src/test/java/npanday/its/IntegrationTestSuite.java
@@ -1,88 +1,88 @@
package npanday.its;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class IntegrationTestSuite
extends TestCase
{
public static Test suite()
{
TestSuite suite = new TestSuite();
/*
* This must be the first one to ensure the local repository is properly setup.
*/
suite.addTestSuite( BootstrapTest.class );
/*
* Add tests in order of newest first.
* Newer tests are also more likely to fail, so this is
* a fail fast technique as well.
*/
// Tests that currently don't pass for any Maven version, i.e. the corresponding issue hasn't been resolved yet
// suite.addTestSuite( NPandayIT0033VBSourceWithCSharpSourceTest.class ); // issue #11732
// suite.addTestSuite( NPandayIT0002NetModuleDependencyTest.class ); // issue #11729
// suite.addTestSuite( NPandayIT0003NetModuleTransitiveDependencyTest.class ); // issue #11729
- suite.addTestSuite( NPandayIT328WPF2010ProjectTest.class );
- suite.addTestSuite( NPandayIT330MVC2010ProjectTest.class );
- suite.addTestSuite( NPandayITNet40Test.class );
+ suite.addTestSuite( NPandayIT328WPF2010ProjectTest.class );
+ suite.addTestSuite( NPandayIT330MVC2010ProjectTest.class );
+ suite.addTestSuite( NPandayITNet40Test.class );
suite.addTestSuite( NPandayIT13635SnapshotUpdatesTest.class );
suite.addTestSuite( NPandayIT13542OptionInferTest.class );
suite.addTestSuite( NPandayIT10276ConflictingExtensionsTest.class );
suite.addTestSuite( NPandayIT13018TransitiveDependenciesTest.class );
suite.addTestSuite( NPandayIT12940MixedVersionsTest.class );
suite.addTestSuite( NPandayIT11480MVCProjectTest.class );
suite.addTestSuite( NPandayIT12549WpfProjectTest.class );
suite.addTestSuite( NPandayIT11579MissingGroupOrVersionTest.class );
suite.addTestSuite( NPandayIT11695MsBuildCopyReferencesTest.class );
suite.addTestSuite( NPandayIT11637MsBuildErrorHandlingTest.class );
suite.addTestSuite( NPandayIT9903ResGenWithErrorInFileNameTest.class );
suite.addTestSuite( NPandayITWithResourceFileTest.class );
suite.addTestSuite( NPandayITWebAppInstallTest.class );
suite.addTestSuite( NPandayITVBWebAppTest.class );
suite.addTestSuite( NPandayITSnapshotResolutionTest.class );
suite.addTestSuite( NPandayITNet35Test.class );
suite.addTestSuite( NPandayITIntraProjectDependencyTest.class );
suite.addTestSuite( NPandayITConsoleApplicationTest.class );
suite.addTestSuite( NPandayITCompilerWithArgsTest.class );
suite.addTestSuite( NPandayITClassLibWithWebRefInstallTest.class );
suite.addTestSuite( NPandayIT0036InstalledArtifactsVerificationTest.class );
suite.addTestSuite( NPandayIT0035VBRootNamespaceTest.class );
suite.addTestSuite( NPandayIT0032CompileExclusionsTest.class );
suite.addTestSuite( NPandayIT0029RemoteRepoTest.class );
suite.addTestSuite( NPandayIT0028RemoteSnapshotRepoTest.class );
suite.addTestSuite( NPandayIT0022StrongNameKeyAddedToAssemblyTest.class );
suite.addTestSuite( NPandayIT0020EmbeddedResourcesTest.class );
suite.addTestSuite( NPandayIT0010VBCompilationTest.class );
suite.addTestSuite( NPandayIT0007XSDVerificationTest.class );
suite.addTestSuite( NPandayIT0006StockingHandlersTest.class );
suite.addTestSuite( NPandayIT0004NUnitTestVerificationTest.class );
suite.addTestSuite( NPandayIT0001CompilerVerificationTest.class );
return suite;
}
}
| true | true | public static Test suite()
{
TestSuite suite = new TestSuite();
/*
* This must be the first one to ensure the local repository is properly setup.
*/
suite.addTestSuite( BootstrapTest.class );
/*
* Add tests in order of newest first.
* Newer tests are also more likely to fail, so this is
* a fail fast technique as well.
*/
// Tests that currently don't pass for any Maven version, i.e. the corresponding issue hasn't been resolved yet
// suite.addTestSuite( NPandayIT0033VBSourceWithCSharpSourceTest.class ); // issue #11732
// suite.addTestSuite( NPandayIT0002NetModuleDependencyTest.class ); // issue #11729
// suite.addTestSuite( NPandayIT0003NetModuleTransitiveDependencyTest.class ); // issue #11729
suite.addTestSuite( NPandayIT328WPF2010ProjectTest.class );
suite.addTestSuite( NPandayIT330MVC2010ProjectTest.class );
suite.addTestSuite( NPandayITNet40Test.class );
suite.addTestSuite( NPandayIT13635SnapshotUpdatesTest.class );
suite.addTestSuite( NPandayIT13542OptionInferTest.class );
suite.addTestSuite( NPandayIT10276ConflictingExtensionsTest.class );
suite.addTestSuite( NPandayIT13018TransitiveDependenciesTest.class );
suite.addTestSuite( NPandayIT12940MixedVersionsTest.class );
suite.addTestSuite( NPandayIT11480MVCProjectTest.class );
suite.addTestSuite( NPandayIT12549WpfProjectTest.class );
suite.addTestSuite( NPandayIT11579MissingGroupOrVersionTest.class );
suite.addTestSuite( NPandayIT11695MsBuildCopyReferencesTest.class );
suite.addTestSuite( NPandayIT11637MsBuildErrorHandlingTest.class );
suite.addTestSuite( NPandayIT9903ResGenWithErrorInFileNameTest.class );
suite.addTestSuite( NPandayITWithResourceFileTest.class );
suite.addTestSuite( NPandayITWebAppInstallTest.class );
suite.addTestSuite( NPandayITVBWebAppTest.class );
suite.addTestSuite( NPandayITSnapshotResolutionTest.class );
suite.addTestSuite( NPandayITNet35Test.class );
suite.addTestSuite( NPandayITIntraProjectDependencyTest.class );
suite.addTestSuite( NPandayITConsoleApplicationTest.class );
suite.addTestSuite( NPandayITCompilerWithArgsTest.class );
suite.addTestSuite( NPandayITClassLibWithWebRefInstallTest.class );
suite.addTestSuite( NPandayIT0036InstalledArtifactsVerificationTest.class );
suite.addTestSuite( NPandayIT0035VBRootNamespaceTest.class );
suite.addTestSuite( NPandayIT0032CompileExclusionsTest.class );
suite.addTestSuite( NPandayIT0029RemoteRepoTest.class );
suite.addTestSuite( NPandayIT0028RemoteSnapshotRepoTest.class );
suite.addTestSuite( NPandayIT0022StrongNameKeyAddedToAssemblyTest.class );
suite.addTestSuite( NPandayIT0020EmbeddedResourcesTest.class );
suite.addTestSuite( NPandayIT0010VBCompilationTest.class );
suite.addTestSuite( NPandayIT0007XSDVerificationTest.class );
suite.addTestSuite( NPandayIT0006StockingHandlersTest.class );
suite.addTestSuite( NPandayIT0004NUnitTestVerificationTest.class );
suite.addTestSuite( NPandayIT0001CompilerVerificationTest.class );
return suite;
}
| public static Test suite()
{
TestSuite suite = new TestSuite();
/*
* This must be the first one to ensure the local repository is properly setup.
*/
suite.addTestSuite( BootstrapTest.class );
/*
* Add tests in order of newest first.
* Newer tests are also more likely to fail, so this is
* a fail fast technique as well.
*/
// Tests that currently don't pass for any Maven version, i.e. the corresponding issue hasn't been resolved yet
// suite.addTestSuite( NPandayIT0033VBSourceWithCSharpSourceTest.class ); // issue #11732
// suite.addTestSuite( NPandayIT0002NetModuleDependencyTest.class ); // issue #11729
// suite.addTestSuite( NPandayIT0003NetModuleTransitiveDependencyTest.class ); // issue #11729
suite.addTestSuite( NPandayIT328WPF2010ProjectTest.class );
suite.addTestSuite( NPandayIT330MVC2010ProjectTest.class );
suite.addTestSuite( NPandayITNet40Test.class );
suite.addTestSuite( NPandayIT13635SnapshotUpdatesTest.class );
suite.addTestSuite( NPandayIT13542OptionInferTest.class );
suite.addTestSuite( NPandayIT10276ConflictingExtensionsTest.class );
suite.addTestSuite( NPandayIT13018TransitiveDependenciesTest.class );
suite.addTestSuite( NPandayIT12940MixedVersionsTest.class );
suite.addTestSuite( NPandayIT11480MVCProjectTest.class );
suite.addTestSuite( NPandayIT12549WpfProjectTest.class );
suite.addTestSuite( NPandayIT11579MissingGroupOrVersionTest.class );
suite.addTestSuite( NPandayIT11695MsBuildCopyReferencesTest.class );
suite.addTestSuite( NPandayIT11637MsBuildErrorHandlingTest.class );
suite.addTestSuite( NPandayIT9903ResGenWithErrorInFileNameTest.class );
suite.addTestSuite( NPandayITWithResourceFileTest.class );
suite.addTestSuite( NPandayITWebAppInstallTest.class );
suite.addTestSuite( NPandayITVBWebAppTest.class );
suite.addTestSuite( NPandayITSnapshotResolutionTest.class );
suite.addTestSuite( NPandayITNet35Test.class );
suite.addTestSuite( NPandayITIntraProjectDependencyTest.class );
suite.addTestSuite( NPandayITConsoleApplicationTest.class );
suite.addTestSuite( NPandayITCompilerWithArgsTest.class );
suite.addTestSuite( NPandayITClassLibWithWebRefInstallTest.class );
suite.addTestSuite( NPandayIT0036InstalledArtifactsVerificationTest.class );
suite.addTestSuite( NPandayIT0035VBRootNamespaceTest.class );
suite.addTestSuite( NPandayIT0032CompileExclusionsTest.class );
suite.addTestSuite( NPandayIT0029RemoteRepoTest.class );
suite.addTestSuite( NPandayIT0028RemoteSnapshotRepoTest.class );
suite.addTestSuite( NPandayIT0022StrongNameKeyAddedToAssemblyTest.class );
suite.addTestSuite( NPandayIT0020EmbeddedResourcesTest.class );
suite.addTestSuite( NPandayIT0010VBCompilationTest.class );
suite.addTestSuite( NPandayIT0007XSDVerificationTest.class );
suite.addTestSuite( NPandayIT0006StockingHandlersTest.class );
suite.addTestSuite( NPandayIT0004NUnitTestVerificationTest.class );
suite.addTestSuite( NPandayIT0001CompilerVerificationTest.class );
return suite;
}
|
diff --git a/asm/src/org/objectweb/asm/attrs/EnclosingMethodAttribute.java b/asm/src/org/objectweb/asm/attrs/EnclosingMethodAttribute.java
index 5bb326b9..cf91971b 100644
--- a/asm/src/org/objectweb/asm/attrs/EnclosingMethodAttribute.java
+++ b/asm/src/org/objectweb/asm/attrs/EnclosingMethodAttribute.java
@@ -1,136 +1,137 @@
/**
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000,2002,2003 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm.attrs;
import java.util.Map;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ByteVector;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
/**
* The EnclosingMethod attribute is an optional fixed-length attribute in
* the attributes table of the ClassFile structure. A class must have an
* EnclosingMethod attribute if and only if it is a local class or an
* anonymous class. A class may have no more than one EnclosingMethod attribute.
*
* The EnclosingMethod attribute has the following format:
* <pre>
* EnclosingMethod_attribute {
* u2 attribute_name_index;
* u4 attribute_length;
* u2 class_index
* u2 method_index;
* }
* </pre>
* The items of the EnclosingMethod_attribute structure are as follows:
* <dl>
* <dt>attribute_name_index</dt>
* <dd>The value of the attribute_name_index item must be a valid index
* into the constant_pool table. The constant_pool entry at that index
* must be a CONSTANT_Utf8_info structure representing the
* string "EnclosingMethod".</dd>
* <dt>attribute_length</dt>
* <dd>The value of the attribute_length item is four.</dd>
* <dt>class_index</dt>
* <dd>The value of the class_index item must be a valid index into the
* constant_pool table. The constant_pool entry at that index must be a
* CONSTANT_Class_info structure representing the
* innermost class that encloses the declaration of the current class.</dd>
* <dt>method_index</dt>
* <dd>If the current class is not immediately enclosed by a method or
* constructor, then the value of the method_index item must be zero.
* Otherwise, the value of the method_index item must be a valid
* index into the constant_pool table. The constant_pool entry at that
* index must be a CONSTANT_NameAndType_info structure
* representing a the name and type of a method in the class
* referenced by the class_index attribute above. It is the
* responsibility of the Java compiler to ensure that the method
* identified via the method_index is indeed the closest lexically
* enclosing method of the class that contains this EnclosingMethod
* attribute.</dd>
* </dl>
*
* @author Eugene Kuleshov
*/
public class EnclosingMethodAttribute extends Attribute implements Dumpable {
public String owner;
public String name;
public String desc;
public EnclosingMethodAttribute () {
super("EnclosingMethod");
}
public EnclosingMethodAttribute (String owner, String name, String desc) {
this();
this.owner = owner;
this.name = name;
this.desc = desc;
}
protected Attribute read (ClassReader cr, int off,
int len, char[] buf, int codeOff, Label[] labels) {
// CONSTANT_Class_info
String owner = cr.readClass( off, buf);
// CONSTANT_NameAndType_info (skip CONSTANT_NameAndType tag)
- String name = cr.readUTF8( off + 3, buf);
- String desc = cr.readUTF8( off + 5, buf);
+ int index = cr.getItem(cr.readUnsignedShort(off + 2));
+ String name = cr.readUTF8(index, buf);
+ String desc = cr.readUTF8(index + 2, buf);
return new EnclosingMethodAttribute( owner, name, desc);
}
protected ByteVector write (ClassWriter cw, byte[] code,
int len, int maxStack, int maxLocals) {
return new ByteVector().putShort(cw.newClass(owner))
.putShort(cw.newNameType(name, desc));
}
public void dump (StringBuffer buf, String varName, Map labelNames) {
buf.append("EnclosingMethodAttribute ").append(varName)
.append(" = new EnclosingMethodAttribute(\"")
.append(owner).append(",")
.append(name).append(",")
.append(desc).append("\");\n");
}
public String toString () {
return new StringBuffer("owner:").append( owner)
.append(" name:").append(name)
.append(" desc:").append(desc).toString();
}
}
| true | true | protected Attribute read (ClassReader cr, int off,
int len, char[] buf, int codeOff, Label[] labels) {
// CONSTANT_Class_info
String owner = cr.readClass( off, buf);
// CONSTANT_NameAndType_info (skip CONSTANT_NameAndType tag)
String name = cr.readUTF8( off + 3, buf);
String desc = cr.readUTF8( off + 5, buf);
return new EnclosingMethodAttribute( owner, name, desc);
}
| protected Attribute read (ClassReader cr, int off,
int len, char[] buf, int codeOff, Label[] labels) {
// CONSTANT_Class_info
String owner = cr.readClass( off, buf);
// CONSTANT_NameAndType_info (skip CONSTANT_NameAndType tag)
int index = cr.getItem(cr.readUnsignedShort(off + 2));
String name = cr.readUTF8(index, buf);
String desc = cr.readUTF8(index + 2, buf);
return new EnclosingMethodAttribute( owner, name, desc);
}
|
diff --git a/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java b/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
index 1dc4731d..4e71175b 100644
--- a/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
+++ b/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
@@ -1,188 +1,188 @@
package grisu.frontend.control;
import grisu.control.ServiceInterface;
import grisu.control.ServiceInterfaceCreator;
import grisu.control.exceptions.ServiceInterfaceException;
import grisu.frontend.control.jaxws.CommandLogHandler;
import grisu.frontend.control.login.LoginManager;
import grisu.settings.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.python.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.xml.ws.developer.JAXWSProperties;
public class JaxWsServiceInterfaceCreator implements ServiceInterfaceCreator {
static final Logger myLogger = LoggerFactory
.getLogger(JaxWsServiceInterfaceCreator.class.getName());
public static String TRUST_FILE_NAME = Environment
.getGrisuClientDirectory().getPath()
+ File.separator
+ "truststore.jks";
/**
* configures secure connection parameters.
**/
public JaxWsServiceInterfaceCreator() throws ServiceInterfaceException {
try {
if (!(new File(Environment.getGrisuClientDirectory(),
"truststore.jks").exists())) {
final InputStream ts = JaxWsServiceInterfaceCreator.class
.getResourceAsStream("/truststore.jks");
IOUtils.copy(ts, new FileOutputStream(TRUST_FILE_NAME));
}
} catch (final IOException ex) {
throw new ServiceInterfaceException(
"cannot copy SSL certificate store into grisu home directory. Does "
+ Environment.getGrisuClientDirectory().getPath()
+ " exist?", ex);
}
System.setProperty("javax.net.ssl.trustStore", TRUST_FILE_NAME);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
public boolean canHandleUrl(String url) {
if (StringUtils.isNotBlank(url) && url.startsWith("http")) {
return true;
} else {
return false;
}
}
public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName("http://api.grisu",
"GrisuService");
final QName portName = new QName("http://api.grisu",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
// "ns1.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (final Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n\n"
+ "Please download the latest version from:\n\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n\n"
+ "If you have the latest version and are still experiencing this problem please contact\n\n"
+ "[email protected]\n\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
String clientstring = LoginManager.getClientName()
+ " "
+ LoginManager.getClientVersion()
+ " / "
+ "frontend "
+ grisu.jcommons.utils.Version
.get("grisu-client");
Map map = Maps.newHashMap();
- map.put("X-login-host", myProxyServer);
- map.put("X-login-port", myProxyPort);
+ map.put("X-login-host", Collections.singletonList(myProxyServer));
+ map.put("X-login-port", Collections.singletonList(myProxyPort));
map.put("X-grisu-client", Collections.singletonList(clientstring));
String session_id = LoginManager.USER_SESSION;
if (StringUtils.isNotBlank(session_id)) {
map.put("X-client-session-id",
Collections.singletonList(session_id));
}
bp.getRequestContext()
.put(MessageContext.HTTP_REQUEST_HEADERS, map);
CommandLogHandler authnHandler = new CommandLogHandler(bp);
List<Handler> hc = binding.getHandlerChain();
hc.add(authnHandler);
binding.setHandlerChain(hc);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
}
| true | true | public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName("http://api.grisu",
"GrisuService");
final QName portName = new QName("http://api.grisu",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
// "ns1.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (final Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n\n"
+ "Please download the latest version from:\n\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n\n"
+ "If you have the latest version and are still experiencing this problem please contact\n\n"
+ "[email protected]\n\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
String clientstring = LoginManager.getClientName()
+ " "
+ LoginManager.getClientVersion()
+ " / "
+ "frontend "
+ grisu.jcommons.utils.Version
.get("grisu-client");
Map map = Maps.newHashMap();
map.put("X-login-host", myProxyServer);
map.put("X-login-port", myProxyPort);
map.put("X-grisu-client", Collections.singletonList(clientstring));
String session_id = LoginManager.USER_SESSION;
if (StringUtils.isNotBlank(session_id)) {
map.put("X-client-session-id",
Collections.singletonList(session_id));
}
bp.getRequestContext()
.put(MessageContext.HTTP_REQUEST_HEADERS, map);
CommandLogHandler authnHandler = new CommandLogHandler(bp);
List<Handler> hc = binding.getHandlerChain();
hc.add(authnHandler);
binding.setHandlerChain(hc);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
| public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName("http://api.grisu",
"GrisuService");
final QName portName = new QName("http://api.grisu",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
// "ns1.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (final Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n\n"
+ "Please download the latest version from:\n\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n\n"
+ "If you have the latest version and are still experiencing this problem please contact\n\n"
+ "[email protected]\n\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
String clientstring = LoginManager.getClientName()
+ " "
+ LoginManager.getClientVersion()
+ " / "
+ "frontend "
+ grisu.jcommons.utils.Version
.get("grisu-client");
Map map = Maps.newHashMap();
map.put("X-login-host", Collections.singletonList(myProxyServer));
map.put("X-login-port", Collections.singletonList(myProxyPort));
map.put("X-grisu-client", Collections.singletonList(clientstring));
String session_id = LoginManager.USER_SESSION;
if (StringUtils.isNotBlank(session_id)) {
map.put("X-client-session-id",
Collections.singletonList(session_id));
}
bp.getRequestContext()
.put(MessageContext.HTTP_REQUEST_HEADERS, map);
CommandLogHandler authnHandler = new CommandLogHandler(bp);
List<Handler> hc = binding.getHandlerChain();
hc.add(authnHandler);
binding.setHandlerChain(hc);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
|
diff --git a/ccw.core/src/java/ccw/nature/AutomaticNatureAdder.java b/ccw.core/src/java/ccw/nature/AutomaticNatureAdder.java
index 2840f7f0..74d1924d 100644
--- a/ccw.core/src/java/ccw/nature/AutomaticNatureAdder.java
+++ b/ccw.core/src/java/ccw/nature/AutomaticNatureAdder.java
@@ -1,22 +1,22 @@
package ccw.nature;
import org.eclipse.jdt.core.JavaCore;
public class AutomaticNatureAdder {
private ClojurePackageElementChangeListener elementChangedListener;
public synchronized void start() {
elementChangedListener = new ClojurePackageElementChangeListener();
JavaCore.addElementChangedListener(elementChangedListener);
elementChangedListener.performFullScan();
}
public synchronized void stop() {
- if (elementChangedListener == null) {
+ if (elementChangedListener != null) {
JavaCore.removeElementChangedListener(elementChangedListener);
+ elementChangedListener = null;
}
- elementChangedListener = null;
}
}
| false | true | public synchronized void stop() {
if (elementChangedListener == null) {
JavaCore.removeElementChangedListener(elementChangedListener);
}
elementChangedListener = null;
}
| public synchronized void stop() {
if (elementChangedListener != null) {
JavaCore.removeElementChangedListener(elementChangedListener);
elementChangedListener = null;
}
}
|
diff --git a/CubicTestHtmlPrototypeExporter/src/main/java/org/cubictest/exporters/htmlPrototype/delegates/HtmlPageCreator.java b/CubicTestHtmlPrototypeExporter/src/main/java/org/cubictest/exporters/htmlPrototype/delegates/HtmlPageCreator.java
index 4b6a0faa..f104bb47 100755
--- a/CubicTestHtmlPrototypeExporter/src/main/java/org/cubictest/exporters/htmlPrototype/delegates/HtmlPageCreator.java
+++ b/CubicTestHtmlPrototypeExporter/src/main/java/org/cubictest/exporters/htmlPrototype/delegates/HtmlPageCreator.java
@@ -1,297 +1,300 @@
/*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*/
package org.cubictest.exporters.htmlPrototype.delegates;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.cubictest.exporters.htmlPrototype.interfaces.IPageElementConverter;
import org.cubictest.exporters.htmlPrototype.interfaces.IPageElementConverter.UnknownPageElementException;
import org.cubictest.exporters.htmlPrototype.utils.XmlUtils;
import org.cubictest.model.ActionType;
import org.cubictest.model.Common;
import org.cubictest.model.CommonTransition;
import org.cubictest.model.FormElement;
import org.cubictest.model.IdentifierType;
import org.cubictest.model.Link;
import org.cubictest.model.Page;
import org.cubictest.model.PageElement;
import org.cubictest.model.Title;
import org.cubictest.model.Transition;
import org.cubictest.model.TransitionNode;
import org.cubictest.model.UrlStartPoint;
import org.cubictest.model.UserInteraction;
import org.cubictest.model.UserInteractionsTransition;
import org.cubictest.model.formElement.Button;
import org.jdom.Document;
import org.jdom.Element;
public class HtmlPageCreator {
private IPageElementConverter pageElementConverter;
private File file;
private Map<PageElement, Element> elements = new HashMap<PageElement, Element>();
private HashMap<UserInteractionsTransition, HtmlPageCreator> userActions = new HashMap<UserInteractionsTransition, HtmlPageCreator>();
private Element contents;
private Element html;
private Element title;
private Element breadcrumbs;
private Element transitions;
private Document document;
private String name;
private Element script;
public HtmlPageCreator(File file, IPageElementConverter pageElementConverter, String extension, String prefix, String name) {
this.pageElementConverter = pageElementConverter;
this.file = file;
this.name = name;
createHtmlPage();
}
public String getName() {
return name;
}
public String getFilename() {
return file.getName();
}
public static boolean isNewPageTransition(UserInteractionsTransition transition) {
for(UserInteraction action : transition.getUserInteractions()) {
if((action.getElement() instanceof Link || action.getElement() instanceof Button) && action.getActionType() == ActionType.CLICK) {
return true;
}
}
return false;
}
public static String filenameFor(TransitionNode transitionNode, String extension, String prefix) {
if(transitionNode.getInTransition().getStart() instanceof UrlStartPoint) {
prefix = "index_" + prefix;
}
return prefix + transitionNode.getId() + extension;
}
public void convert(Page page, Stack<HtmlPageCreator> breadcrumbs) {
if(title.getText() == "") {
title.setText(page.getName());
}
Element breadcrumbRow = new Element("div");
breadcrumbRow.setAttribute("class", "breadcrumb");
// genereate breadcrumbs
for(HtmlPageCreator breadcrumb : breadcrumbs) {
Element link = new Element("a");
link.setText(breadcrumb.getName());
link.setAttribute("href", breadcrumb.getFilename());
breadcrumbRow.addContent(link);
breadcrumbRow.addContent(" > ");
}
breadcrumbRow.addContent(page.getName());
this.breadcrumbs.addContent(breadcrumbRow);
// convert commons
List<CommonTransition> commonTransitions = page.getCommonTransitions();
for(CommonTransition transition : commonTransitions) {
Common common = (Common)transition.getStart();
addPageElements(common.getElements());
}
// convert page elements
addPageElements(page.getElements());
save();
}
public void save() {
transitions.removeContent();
for(UserInteractionsTransition actions : userActions.keySet()) {
if(actions.hasUserInteractions()) {
Element entry = new Element("li");
Element transitionLink = convertTransition(actions, userActions.get(actions));
entry.addContent(transitionLink);
Element description = new Element("pre");
description.setText(transitionLink.getAttributeValue("title").toString());
entry.addContent(description);
transitions.addContent(entry);
}
}
Element span = new Element("span").setAttribute("id", "scriptInfo");;
transitions.addContent(span.addContent(new Element("small").setText("Activate JavaScript to enable clickable page elements")));
try {
FileWriter fw = new FileWriter(file);
XmlUtils.getNewXmlOutputter().output(document, fw);
} catch (IOException e) {
e.printStackTrace();
}
}
private void addPageElements(List<PageElement> elements) {
for(PageElement pe : elements) {
addPageElement(pe, contents);
}
}
private void addPageElement(PageElement pe, Element result) {
try {
Element element = pageElementConverter.convert(pe);
elements.put(pe, element);
if(pe instanceof FormElement) {
element = pageElementConverter.labelFormElement((FormElement) pe, element);
}
result.addContent(element);
} catch (UnknownPageElementException e) {}
if(pe instanceof Title) {
title.setText(pe.getIdentifier(IdentifierType.LABEL).getValue());
}
}
public void convertTransitions(HashMap<Transition, HtmlPageCreator> transitions) {
// convert transitions
for(Transition transition : transitions.keySet()) {
if(transition instanceof UserInteractionsTransition) {
String title = new String();
for(UserInteraction action : ((UserInteractionsTransition) transition).getUserInteractions()) {
title += action.toString() + "\n";
}
System.out.println("Adding " + title + ", " + transitions.get(transition).getName());
userActions.put((UserInteractionsTransition) transition, transitions.get(transition));
}
}
}
private Element convertTransition(Transition transition, HtmlPageCreator target) {
Element link = new Element("a");
link.addContent(target.getName());
return convertTransition(transition, link, target);
}
private Element convertTransition(Transition transition, Element link, HtmlPageCreator target) {
link.setAttribute("href", target.getFilename());
if(transition instanceof UserInteractionsTransition) {
String title = new String();
UserInteractionsTransition ua = (UserInteractionsTransition) transition;
String uaId = target.getFilename();
String actionJs = "";
int i = 0;
for(UserInteraction action : ua.getUserInteractions()) {
title += action.toString() + "\n";
if(action.getActionType() != ActionType.NO_ACTION) {
Element element = elements.get(action.getElement());
String actionAttribute = "";
String attribute = "value";
String value = "null";
if(action.getActionType() == ActionType.CLICK) {
actionAttribute = "onClick";
} else if(action.getActionType() == ActionType.CHECK || action.getActionType() == ActionType.UNCHECK) {
actionAttribute = "onClick";
attribute = "checked";
if(action.getActionType() == ActionType.CHECK) {
value = "true";
} else {
value = "false";
}
} else if(action.getActionType() == ActionType.ENTER_TEXT || action.getActionType() == ActionType.ENTER_PARAMETER_TEXT) {
actionAttribute = "onKeyUp";
value = "'" + action.getTextualInput().replaceAll("'", "\\'") + "'";
} else if(action.getActionType() == ActionType.MOUSE_OVER) {
actionAttribute = "onMouseOver";
}
String attributeValue = "";
if(element != null) {
if(element.getAttributeValue(actionAttribute) != null) {
attributeValue += element.getAttributeValue(actionAttribute);
attributeValue = attributeValue.replaceAll("return false;", "");
}
attributeValue += "UserInteractions.test('" + uaId + "', " + i + ", this);";
if (element.getName().equalsIgnoreCase("a")) {
//intercept links
attributeValue += " return false;";
}
element.setAttribute(actionAttribute, attributeValue);
if(element.getAttribute("class") == null || element.getAttribute("class").toString().indexOf("actionable") == -1) {
String classes = element.getAttributeValue("class");
if(classes == null) {
classes = "";
}
element.setAttribute("class", "actionable " + classes);
}
}
+ if(!actionJs.equals("")) {
+ actionJs += ",";
+ }
actionJs += "['" + attribute + "'," + value + ", false]";
i++;
}
}
script.addContent("UserInteractions.actions['" + uaId + "'] = [" + actionJs + "];\n");
link.setAttribute("title", title);
}
return link;
}
private void createHtmlPage() {
html = new Element("html");
document = new Document(html);
Element head = new Element("head");
breadcrumbs = new Element("div");
breadcrumbs.setAttribute("id", "breadcrumbs");
Element body = new Element("body").setAttribute("onLoad", "hideScriptInfo();");
title = new Element("title");
body.addContent(breadcrumbs);
head.addContent(title);
html.addContent(head);
html.addContent(body);
Element transitionsContainer = new Element("div");
transitionsContainer.setAttribute("id", "transitions");
Element transitionsHeading = new Element("h2");
transitionsHeading.setText("Transitions");
transitionsContainer.addContent(transitionsHeading);
transitions = new Element("ul");
transitionsContainer.addContent(transitions);
body.addContent(transitionsContainer);
contents = new Element("div");
contents.setAttribute("id", "contents");
body.addContent(contents);
Element jsCubic = new Element("script");
jsCubic.setAttribute("type", "text/javascript");
jsCubic.setAttribute("src", "cubic.js");
jsCubic.setText(";");
head.addContent(jsCubic);
Element style = new Element("link");
style.setAttribute("type", "text/css");
style.setAttribute("rel", "stylesheet");
style.setAttribute("href", "default.css");
head.addContent(style);
script = new Element("script");
script.setAttribute("type", "text/javascript");
head.addContent(script);
}
}
| true | true | private Element convertTransition(Transition transition, Element link, HtmlPageCreator target) {
link.setAttribute("href", target.getFilename());
if(transition instanceof UserInteractionsTransition) {
String title = new String();
UserInteractionsTransition ua = (UserInteractionsTransition) transition;
String uaId = target.getFilename();
String actionJs = "";
int i = 0;
for(UserInteraction action : ua.getUserInteractions()) {
title += action.toString() + "\n";
if(action.getActionType() != ActionType.NO_ACTION) {
Element element = elements.get(action.getElement());
String actionAttribute = "";
String attribute = "value";
String value = "null";
if(action.getActionType() == ActionType.CLICK) {
actionAttribute = "onClick";
} else if(action.getActionType() == ActionType.CHECK || action.getActionType() == ActionType.UNCHECK) {
actionAttribute = "onClick";
attribute = "checked";
if(action.getActionType() == ActionType.CHECK) {
value = "true";
} else {
value = "false";
}
} else if(action.getActionType() == ActionType.ENTER_TEXT || action.getActionType() == ActionType.ENTER_PARAMETER_TEXT) {
actionAttribute = "onKeyUp";
value = "'" + action.getTextualInput().replaceAll("'", "\\'") + "'";
} else if(action.getActionType() == ActionType.MOUSE_OVER) {
actionAttribute = "onMouseOver";
}
String attributeValue = "";
if(element != null) {
if(element.getAttributeValue(actionAttribute) != null) {
attributeValue += element.getAttributeValue(actionAttribute);
attributeValue = attributeValue.replaceAll("return false;", "");
}
attributeValue += "UserInteractions.test('" + uaId + "', " + i + ", this);";
if (element.getName().equalsIgnoreCase("a")) {
//intercept links
attributeValue += " return false;";
}
element.setAttribute(actionAttribute, attributeValue);
if(element.getAttribute("class") == null || element.getAttribute("class").toString().indexOf("actionable") == -1) {
String classes = element.getAttributeValue("class");
if(classes == null) {
classes = "";
}
element.setAttribute("class", "actionable " + classes);
}
}
actionJs += "['" + attribute + "'," + value + ", false]";
i++;
}
}
script.addContent("UserInteractions.actions['" + uaId + "'] = [" + actionJs + "];\n");
link.setAttribute("title", title);
}
return link;
}
| private Element convertTransition(Transition transition, Element link, HtmlPageCreator target) {
link.setAttribute("href", target.getFilename());
if(transition instanceof UserInteractionsTransition) {
String title = new String();
UserInteractionsTransition ua = (UserInteractionsTransition) transition;
String uaId = target.getFilename();
String actionJs = "";
int i = 0;
for(UserInteraction action : ua.getUserInteractions()) {
title += action.toString() + "\n";
if(action.getActionType() != ActionType.NO_ACTION) {
Element element = elements.get(action.getElement());
String actionAttribute = "";
String attribute = "value";
String value = "null";
if(action.getActionType() == ActionType.CLICK) {
actionAttribute = "onClick";
} else if(action.getActionType() == ActionType.CHECK || action.getActionType() == ActionType.UNCHECK) {
actionAttribute = "onClick";
attribute = "checked";
if(action.getActionType() == ActionType.CHECK) {
value = "true";
} else {
value = "false";
}
} else if(action.getActionType() == ActionType.ENTER_TEXT || action.getActionType() == ActionType.ENTER_PARAMETER_TEXT) {
actionAttribute = "onKeyUp";
value = "'" + action.getTextualInput().replaceAll("'", "\\'") + "'";
} else if(action.getActionType() == ActionType.MOUSE_OVER) {
actionAttribute = "onMouseOver";
}
String attributeValue = "";
if(element != null) {
if(element.getAttributeValue(actionAttribute) != null) {
attributeValue += element.getAttributeValue(actionAttribute);
attributeValue = attributeValue.replaceAll("return false;", "");
}
attributeValue += "UserInteractions.test('" + uaId + "', " + i + ", this);";
if (element.getName().equalsIgnoreCase("a")) {
//intercept links
attributeValue += " return false;";
}
element.setAttribute(actionAttribute, attributeValue);
if(element.getAttribute("class") == null || element.getAttribute("class").toString().indexOf("actionable") == -1) {
String classes = element.getAttributeValue("class");
if(classes == null) {
classes = "";
}
element.setAttribute("class", "actionable " + classes);
}
}
if(!actionJs.equals("")) {
actionJs += ",";
}
actionJs += "['" + attribute + "'," + value + ", false]";
i++;
}
}
script.addContent("UserInteractions.actions['" + uaId + "'] = [" + actionJs + "];\n");
link.setAttribute("title", title);
}
return link;
}
|
diff --git a/src/main/java/org/amicofragile/groovy4dsl/inheritance/CrazyGreetingsSource.java b/src/main/java/org/amicofragile/groovy4dsl/inheritance/CrazyGreetingsSource.java
index 2dd93cf..a96a41b 100644
--- a/src/main/java/org/amicofragile/groovy4dsl/inheritance/CrazyGreetingsSource.java
+++ b/src/main/java/org/amicofragile/groovy4dsl/inheritance/CrazyGreetingsSource.java
@@ -1,9 +1,8 @@
package org.amicofragile.groovy4dsl.inheritance;
public class CrazyGreetingsSource extends DynamicGreetingsSource {
public CrazyGreetingsSource() {
- super();
- setGreetings("AAAAAAAH");
+ super("AAAAAAAH");
}
}
| true | true | public CrazyGreetingsSource() {
super();
setGreetings("AAAAAAAH");
}
| public CrazyGreetingsSource() {
super("AAAAAAAH");
}
|
diff --git a/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java b/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java
index 5e01629c..92397458 100644
--- a/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java
+++ b/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java
@@ -1,187 +1,188 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package info.papyri.dispatch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.net.MalformedURLException;
import javax.servlet.ServletConfig;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
/**
*
* @author hcayless
*/
public class BiblioSearch extends HttpServlet {
private String solrUrl;
private URL searchURL;
private String xmlPath = "";
private String htmlPath = "";
private String home = "";
private FileUtils util;
private SolrUtils solrutil;
private static String BiblioSearch = "biblio-search/";
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
solrUrl = config.getInitParameter("solrUrl");
xmlPath = config.getInitParameter("xmlPath");
htmlPath = config.getInitParameter("htmlPath");
home = config.getInitParameter("home");
util = new FileUtils(xmlPath, htmlPath);
solrutil = new SolrUtils(config);
try {
searchURL = new URL("file://" + home + "/" + "bibliosearch.html");
} catch (MalformedURLException e) {
throw new ServletException(e);
}
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader reader = null;
try {
String q = request.getParameter("q");
reader = new BufferedReader(new InputStreamReader(searchURL.openStream()));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) {
SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch);
- int rows = 20;
+ int rows = 30;
try {
rows = Integer.parseInt(request.getParameter("rows"));
} catch (Exception e) {
}
int start = 0;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (Exception e) {
}
SolrQuery sq = new SolrQuery();
try {
sq.setQuery(q);
+ sq.setRows(rows);
QueryRequest req = new QueryRequest(sq);
req.setMethod(METHOD.POST);
QueryResponse rs = req.process(solr);
SolrDocumentList docs = rs.getResults();
out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>");
out.println("<table>");
String uq = q;
try {
uq = URLEncoder.encode(q, "UTF-8");
} catch (Exception e) {
}
for (SolrDocument doc : docs) {
StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>");
row.append("<a href=\"");
row.append("/biblio/");
row.append(((String) doc.getFieldValue("id")));
row.append("/?q=");
row.append(uq);
row.append("\">");
row.append(doc.getFieldValue("display"));
row.append("</a>");
row.append("</td>");
row.append("</tr>");
out.print(row);
}
out.println("</table>");
if (docs.getNumFound() > rows) {
out.println("<div id=\"pagination\">");
int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows);
int p = 0;
while (p < pages) {
if ((p * rows) == start) {
out.print("<div class=\"page current\">");
out.print((p + 1) + " ");
out.print("</div>");
} else {
StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows);
- out.print("<div class=\"page\"><a href=\"/search?q=" + plink + "\">" + (p + 1) + "</a></div>");
+ out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>");
}
p++;
}
out.println("</div>");
}
} catch (SolrServerException e) {
out.println("<p>Unable to execute query. Please try again.</p>");
throw new ServletException(e);
}
} else {
out.println(line);
}
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader reader = null;
try {
String q = request.getParameter("q");
reader = new BufferedReader(new InputStreamReader(searchURL.openStream()));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) {
SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch);
int rows = 20;
try {
rows = Integer.parseInt(request.getParameter("rows"));
} catch (Exception e) {
}
int start = 0;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (Exception e) {
}
SolrQuery sq = new SolrQuery();
try {
sq.setQuery(q);
QueryRequest req = new QueryRequest(sq);
req.setMethod(METHOD.POST);
QueryResponse rs = req.process(solr);
SolrDocumentList docs = rs.getResults();
out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>");
out.println("<table>");
String uq = q;
try {
uq = URLEncoder.encode(q, "UTF-8");
} catch (Exception e) {
}
for (SolrDocument doc : docs) {
StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>");
row.append("<a href=\"");
row.append("/biblio/");
row.append(((String) doc.getFieldValue("id")));
row.append("/?q=");
row.append(uq);
row.append("\">");
row.append(doc.getFieldValue("display"));
row.append("</a>");
row.append("</td>");
row.append("</tr>");
out.print(row);
}
out.println("</table>");
if (docs.getNumFound() > rows) {
out.println("<div id=\"pagination\">");
int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows);
int p = 0;
while (p < pages) {
if ((p * rows) == start) {
out.print("<div class=\"page current\">");
out.print((p + 1) + " ");
out.print("</div>");
} else {
StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows);
out.print("<div class=\"page\"><a href=\"/search?q=" + plink + "\">" + (p + 1) + "</a></div>");
}
p++;
}
out.println("</div>");
}
} catch (SolrServerException e) {
out.println("<p>Unable to execute query. Please try again.</p>");
throw new ServletException(e);
}
} else {
out.println(line);
}
}
} finally {
out.close();
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader reader = null;
try {
String q = request.getParameter("q");
reader = new BufferedReader(new InputStreamReader(searchURL.openStream()));
String line = "";
while ((line = reader.readLine()) != null) {
if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) {
SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch);
int rows = 30;
try {
rows = Integer.parseInt(request.getParameter("rows"));
} catch (Exception e) {
}
int start = 0;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (Exception e) {
}
SolrQuery sq = new SolrQuery();
try {
sq.setQuery(q);
sq.setRows(rows);
QueryRequest req = new QueryRequest(sq);
req.setMethod(METHOD.POST);
QueryResponse rs = req.process(solr);
SolrDocumentList docs = rs.getResults();
out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>");
out.println("<table>");
String uq = q;
try {
uq = URLEncoder.encode(q, "UTF-8");
} catch (Exception e) {
}
for (SolrDocument doc : docs) {
StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>");
row.append("<a href=\"");
row.append("/biblio/");
row.append(((String) doc.getFieldValue("id")));
row.append("/?q=");
row.append(uq);
row.append("\">");
row.append(doc.getFieldValue("display"));
row.append("</a>");
row.append("</td>");
row.append("</tr>");
out.print(row);
}
out.println("</table>");
if (docs.getNumFound() > rows) {
out.println("<div id=\"pagination\">");
int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows);
int p = 0;
while (p < pages) {
if ((p * rows) == start) {
out.print("<div class=\"page current\">");
out.print((p + 1) + " ");
out.print("</div>");
} else {
StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows);
out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>");
}
p++;
}
out.println("</div>");
}
} catch (SolrServerException e) {
out.println("<p>Unable to execute query. Please try again.</p>");
throw new ServletException(e);
}
} else {
out.println(line);
}
}
} finally {
out.close();
}
}
|
diff --git a/AppServer_Java/src/com/google/appengine/api/datastore/dev/LocalDatastoreService.java b/AppServer_Java/src/com/google/appengine/api/datastore/dev/LocalDatastoreService.java
index e283a8a8e..2af762776 100644
--- a/AppServer_Java/src/com/google/appengine/api/datastore/dev/LocalDatastoreService.java
+++ b/AppServer_Java/src/com/google/appengine/api/datastore/dev/LocalDatastoreService.java
@@ -1,2353 +1,2357 @@
package com.google.appengine.api.datastore.dev;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityProtoComparators;
import com.google.appengine.api.datastore.EntityProtoComparators.EntityProtoComparator;
import com.google.appengine.api.datastore.EntityTranslator;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.taskqueue.TaskQueuePb;
import com.google.appengine.api.taskqueue.TaskQueuePb.TaskQueueAddRequest;
import com.google.appengine.api.taskqueue.TaskQueuePb.TaskQueueBulkAddRequest;
import com.google.appengine.api.taskqueue.Transaction;
import com.google.appengine.repackaged.com.google.common.base.Preconditions;
import com.google.appengine.repackaged.com.google.common.base.Predicate;
import com.google.appengine.repackaged.com.google.common.base.Predicates;
import com.google.appengine.repackaged.com.google.common.collect.HashMultimap;
import com.google.appengine.repackaged.com.google.common.collect.Iterables;
import com.google.appengine.repackaged.com.google.common.collect.Iterators;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
import com.google.appengine.repackaged.com.google.common.collect.Multimap;
import com.google.appengine.repackaged.com.google.common.collect.Sets;
import com.google.appengine.repackaged.com.google.io.protocol.ProtocolMessage;
import com.google.appengine.tools.development.AbstractLocalRpcService;
import com.google.appengine.tools.development.Clock;
import com.google.appengine.tools.development.LocalRpcService;
import com.google.appengine.tools.development.LocalRpcService.Status;
import com.google.appengine.tools.development.LocalServerEnvironment;
import com.google.appengine.tools.development.LocalServiceContext;
import com.google.appengine.tools.development.ServiceProvider;
import com.google.apphosting.api.ApiBasePb;
import com.google.apphosting.api.ApiBasePb.Integer64Proto;
import com.google.apphosting.api.ApiBasePb.StringProto;
import com.google.apphosting.api.ApiBasePb.VoidProto;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.ApplicationException;
import com.google.apphosting.api.DatastorePb;
import com.google.apphosting.api.DatastorePb.AllocateIdsRequest;
import com.google.apphosting.api.DatastorePb.AllocateIdsResponse;
import com.google.apphosting.api.DatastorePb.BeginTransactionRequest;
import com.google.apphosting.api.DatastorePb.CommitResponse;
import com.google.apphosting.api.DatastorePb.CompiledCursor;
import com.google.apphosting.api.DatastorePb.CompiledCursor.Position;
import com.google.apphosting.api.DatastorePb.CompiledCursor.PositionIndexValue;
import com.google.apphosting.api.DatastorePb.CompiledQuery;
import com.google.apphosting.api.DatastorePb.CompiledQuery.PrimaryScan;
import com.google.apphosting.api.DatastorePb.CompositeIndices;
import com.google.apphosting.api.DatastorePb.Cost;
import com.google.apphosting.api.DatastorePb.Cursor;
import com.google.apphosting.api.DatastorePb.DeleteRequest;
import com.google.apphosting.api.DatastorePb.DeleteResponse;
import com.google.apphosting.api.DatastorePb.Error.ErrorCode;
import com.google.apphosting.api.DatastorePb.GetRequest;
import com.google.apphosting.api.DatastorePb.GetResponse;
import com.google.apphosting.api.DatastorePb.NextRequest;
import com.google.apphosting.api.DatastorePb.PutRequest;
import com.google.apphosting.api.DatastorePb.PutResponse;
import com.google.apphosting.api.DatastorePb.Query;
import com.google.apphosting.api.DatastorePb.Query.Order;
import com.google.apphosting.api.DatastorePb.Query.Order.Direction;
import com.google.apphosting.api.DatastorePb.QueryResult;
import com.google.apphosting.utils.config.GenerationDirectory;
import com.google.storage.onestore.v3.OnestoreEntity;
import com.google.storage.onestore.v3.OnestoreEntity.CompositeIndex;
import com.google.storage.onestore.v3.OnestoreEntity.CompositeIndex.State;
import com.google.storage.onestore.v3.OnestoreEntity.EntityProto;
import com.google.storage.onestore.v3.OnestoreEntity.Index;
import com.google.storage.onestore.v3.OnestoreEntity.Path;
import com.google.storage.onestore.v3.OnestoreEntity.Path.Element;
import com.google.storage.onestore.v3.OnestoreEntity.Property;
import com.google.storage.onestore.v3.OnestoreEntity.Property.Meaning;
import com.google.storage.onestore.v3.OnestoreEntity.PropertyValue;
import com.google.storage.onestore.v3.OnestoreEntity.PropertyValue.UserValue;
import com.google.storage.onestore.v3.OnestoreEntity.Reference;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* AppScale addition to #end
*/
import com.google.appengine.tools.resources.ResourceLoader;
import org.apache.http.*;
/* #end */
@ServiceProvider(LocalRpcService.class)
public final class LocalDatastoreService extends AbstractLocalRpcService
{
private static final Logger logger = Logger.getLogger(LocalDatastoreService.class.getName());
static final int DEFAULT_BATCH_SIZE = 20;
static final int MAXIMUM_RESULTS_SIZE = 300;
public static final String PACKAGE = "datastore_v3";
public static final String MAX_QUERY_LIFETIME_PROPERTY = "datastore.max_query_lifetime";
private static final int DEFAULT_MAX_QUERY_LIFETIME = 30000;
public static final String MAX_TRANSACTION_LIFETIME_PROPERTY = "datastore.max_txn_lifetime";
private static final int DEFAULT_MAX_TRANSACTION_LIFETIME = 300000;
public static final String STORE_DELAY_PROPERTY = "datastore.store_delay";
static final int DEFAULT_STORE_DELAY_MS = 30000;
static final int MAX_STRING_LENGTH = 500;
static final int MAX_LINK_LENGTH = 2038;
public static final int MAX_EG_PER_TXN = 5;
public static final String BACKING_STORE_PROPERTY = "datastore.backing_store";
public static final String NO_INDEX_AUTO_GEN_PROP = "datastore.no_index_auto_gen";
public static final String NO_STORAGE_PROPERTY = "datastore.no_storage";
public static final String HIGH_REP_JOB_POLICY_CLASS_PROPERTY = "datastore.high_replication_job_policy_class";
private static final Pattern RESERVED_NAME = Pattern.compile("^__.*__$");
private static final Set<String> RESERVED_NAME_WHITELIST = new HashSet(Arrays.asList(new String[] { "__BlobUploadSession__", "__BlobInfo__", "__ProspectiveSearchSubscriptions__", "__BlobFileIndex__", "__GsFileInfo__", "__BlobServingUrl__", "__BlobChunk__" }));
static final String ENTITY_GROUP_MESSAGE = "cross-group transaction need to be explicitly specified, see TransactionOptions.Builder.withXG";
static final String TOO_MANY_ENTITY_GROUP_MESSAGE = "operating on too many entity groups in a single transaction.";
static final String MULTI_EG_TXN_NOT_ALLOWED = "transactions on multiple entity groups only allowed in High Replication applications";
static final String CONTENTION_MESSAGE = "too much contention on these datastore entities. please try again.";
static final String TRANSACTION_CLOSED = "transaction closed";
static final String TRANSACTION_NOT_FOUND = "transaction has expired or is invalid";
static final String NAME_TOO_LONG = "name in key path element must be under 500 characters";
static final String QUERY_NOT_FOUND = "query has expired or is invalid. Please restart it with the last cursor to read more results.";
private final AtomicLong entityId = new AtomicLong(1L);
private final AtomicLong queryId = new AtomicLong(0L);
private String backingStore;
private Map<String, Profile> profiles = Collections.synchronizedMap(new HashMap());
private Clock clock;
private static final long MAX_BATCH_GET_KEYS = 1000000000L;
private static final long MAX_ACTIONS_PER_TXN = 5L;
private int maxQueryLifetimeMs;
private int maxTransactionLifetimeMs;
private final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(2, new ThreadFactory()
{
public Thread newThread( Runnable r )
{
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
/*
* AppScale - removed null param from below constructors
*/
private final RemoveStaleQueries removeStaleQueriesTask = new RemoveStaleQueries();
private final RemoveStaleTransactions removeStaleTransactionsTask = new RemoveStaleTransactions();
private final PersistDatastore persistDatastoreTask = new PersistDatastore();
private final AtomicInteger transactionHandleProvider = new AtomicInteger(0);
private int storeDelayMs;
private volatile boolean dirty;
private final ReadWriteLock globalLock = new ReentrantReadWriteLock();
private boolean noStorage;
private Thread shutdownHook;
private PseudoKinds pseudoKinds;
private HighRepJobPolicy highRepJobPolicy;
private boolean isHighRep;
private LocalDatastoreCostAnalysis costAnalysis;
private static Map<String, SpecialProperty> specialPropertyMap = Collections.singletonMap("__scatter__", SpecialProperty.SCATTER);
public void clearProfiles()
{
for (Profile profile : this.profiles.values())
{
LocalFullTextIndex fullTextIndex = profile.getFullTextIndex();
if (fullTextIndex != null)
{
fullTextIndex.close();
}
}
this.profiles.clear();
}
public void clearQueryHistory()
{
LocalCompositeIndexManager.getInstance().clearQueryHistory();
}
// AppScale
private HTTPClientDatastoreProxy proxy;
// Setter added for unit tests
public void setProxy( HTTPClientDatastoreProxy proxy )
{
this.proxy = proxy;
}
public LocalDatastoreService()
{
setMaxQueryLifetime(DEFAULT_MAX_QUERY_LIFETIME);
setMaxTransactionLifetime(DEFAULT_MAX_TRANSACTION_LIFETIME);
setStoreDelay(DEFAULT_STORE_DELAY_MS);
}
/*
* AppScale Replacing public void init(LocalServiceContext context,
* Map<String, String> properties)
*/
public void init( LocalServiceContext context, Map<String, String> properties )
{
this.clock = context.getClock();
/*
* AppScale replacement to #end
*/
ResourceLoader res = ResourceLoader.getResourceLoader();
String host = res.getPbServerIp();
int port = res.getPbServerPort();
boolean isSSL = res.getDatastoreSecurityMode();
this.proxy = new HTTPClientDatastoreProxy(host, port, isSSL);
/* #end */
String storeDelayTime = (String)properties.get(STORE_DELAY_PROPERTY);
this.storeDelayMs = parseInt(storeDelayTime, this.storeDelayMs, STORE_DELAY_PROPERTY);
String maxQueryLifetime = (String)properties.get(MAX_QUERY_LIFETIME_PROPERTY);
this.maxQueryLifetimeMs = parseInt(maxQueryLifetime, this.maxQueryLifetimeMs, MAX_QUERY_LIFETIME_PROPERTY);
String maxTxnLifetime = (String)properties.get(MAX_TRANSACTION_LIFETIME_PROPERTY);
this.maxTransactionLifetimeMs = parseInt(maxTxnLifetime, this.maxTransactionLifetimeMs, MAX_TRANSACTION_LIFETIME_PROPERTY);
LocalCompositeIndexManager.getInstance().setAppDir(context.getLocalServerEnvironment().getAppDir());
LocalCompositeIndexManager.getInstance().setClock(this.clock);
String noIndexAutoGenProp = (String)properties.get(NO_INDEX_AUTO_GEN_PROP);
if (noIndexAutoGenProp != null)
{
LocalCompositeIndexManager.getInstance().setNoIndexAutoGen(Boolean.valueOf(noIndexAutoGenProp).booleanValue());
}
initHighRepJobPolicy(properties);
this.pseudoKinds = new PseudoKinds();
this.pseudoKinds.register(new KindPseudoKind(this));
this.pseudoKinds.register(new PropertyPseudoKind(this));
this.pseudoKinds.register(new NamespacePseudoKind(this));
if (isHighRep())
{
this.pseudoKinds.register(new EntityGroupPseudoKind());
}
this.costAnalysis = new LocalDatastoreCostAnalysis(LocalCompositeIndexManager.getInstance());
logger.info(String.format("Local Datastore initialized: \n\tType: %s\n\tStorage: %s", new Object[] { isHighRep() ? "High Replication" : "Master/Slave", this.noStorage ? "In-memory" : this.backingStore }));
}
boolean isHighRep()
{
return this.isHighRep;
}
private void initHighRepJobPolicy( Map<String, String> properties )
{
String highRepJobPolicyStr = (String)properties.get(HIGH_REP_JOB_POLICY_CLASS_PROPERTY);
if (highRepJobPolicyStr == null)
{
DefaultHighRepJobPolicy defaultPolicy = new DefaultHighRepJobPolicy(properties);
this.isHighRep = (defaultPolicy.unappliedJobCutoff > 0);
this.highRepJobPolicy = defaultPolicy;
}
else
{
this.isHighRep = true;
try
{
Class highRepJobPolicyCls = Class.forName(highRepJobPolicyStr);
Constructor ctor = highRepJobPolicyCls.getDeclaredConstructor(new Class[0]);
ctor.setAccessible(true);
this.highRepJobPolicy = ((HighRepJobPolicy)ctor.newInstance(new Object[0]));
}
catch (ClassNotFoundException e)
{
throw new IllegalArgumentException(e);
}
catch (InvocationTargetException e)
{
throw new IllegalArgumentException(e);
}
catch (NoSuchMethodException e)
{
throw new IllegalArgumentException(e);
}
catch (InstantiationException e)
{
throw new IllegalArgumentException(e);
}
catch (IllegalAccessException e)
{
throw new IllegalArgumentException(e);
}
}
}
private static int parseInt( String valStr, int defaultVal, String propName )
{
if (valStr != null)
{
try
{
return Integer.parseInt(valStr);
}
catch (NumberFormatException e)
{
logger.log(Level.WARNING, "Expected a numeric value for property " + propName + "but received, " + valStr + ". Resetting property to the default.");
}
}
return defaultVal;
}
public void start()
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
LocalDatastoreService.this.startInternal();
return null;
}
});
}
private void startInternal()
{
/*
* AppScale - removed this call to load load();
*/
this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.scheduler.scheduleWithFixedDelay(this.removeStaleQueriesTask, this.maxQueryLifetimeMs * 5, this.maxQueryLifetimeMs * 5, TimeUnit.MILLISECONDS);
this.scheduler.scheduleWithFixedDelay(this.removeStaleTransactionsTask, this.maxTransactionLifetimeMs * 5, this.maxTransactionLifetimeMs * 5, TimeUnit.MILLISECONDS);
if (!this.noStorage)
{
this.scheduler.scheduleWithFixedDelay(this.persistDatastoreTask, this.storeDelayMs, this.storeDelayMs, TimeUnit.MILLISECONDS);
}
this.shutdownHook = new Thread()
{
public void run()
{
LocalDatastoreService.this.stop();
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
public void stop()
{
this.scheduler.shutdown();
if (!this.noStorage)
{
rollForwardAllUnappliedJobs();
this.persistDatastoreTask.run();
}
clearProfiles();
try
{
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex)
{
}
}
private void rollForwardAllUnappliedJobs()
{
for (Profile profile : this.profiles.values())
if (profile.getGroups() != null) for (LocalDatastoreService.Profile.EntityGroup eg : profile.getGroups().values())
eg.rollForwardUnappliedJobs();
}
public void setMaxQueryLifetime( int milliseconds )
{
this.maxQueryLifetimeMs = milliseconds;
}
public void setMaxTransactionLifetime( int milliseconds )
{
this.maxTransactionLifetimeMs = milliseconds;
}
public void setBackingStore( String backingStore )
{
this.backingStore = backingStore;
}
public void setStoreDelay( int delayMs )
{
this.storeDelayMs = delayMs;
}
public void setNoStorage( boolean noStorage )
{
this.noStorage = noStorage;
}
public String getPackage()
{
return "datastore_v3";
}
/*
* AppScale replacement of method body
*/
public DatastorePb.GetResponse get( LocalRpcService.Status status, DatastorePb.GetRequest request )
{
DatastorePb.GetResponse response = new DatastorePb.GetResponse();
logger.log(Level.INFO, "Get Request: " + request.toFlatString());
proxy.doPost(request.getKey(0).getApp(), "Get", request, response);
if (response.entitySize() == 0) response.addEntity(new GetResponse.Entity());
logger.log(Level.INFO, "Get Response: " + response.toFlatString());
return response;
}
public DatastorePb.PutResponse put( LocalRpcService.Status status, DatastorePb.PutRequest request )
{
try
{
this.globalLock.readLock().lock();
return putImpl(status, request);
}
finally
{
this.globalLock.readLock().unlock();
}
}
private static void processEntityForSpecialProperties( OnestoreEntity.EntityProto entity, boolean store )
{
/*
* AppScale - Added type Property to Iterator below in for loop
*/
for (Iterator<Property> iter = entity.propertyIterator(); iter.hasNext();)
{
if (getSpecialPropertyMap().containsKey(((OnestoreEntity.Property)iter.next()).getName()))
{
iter.remove();
}
}
for (SpecialProperty specialProp : getSpecialPropertyMap().values())
if (store ? specialProp.isStored() : specialProp.isVisible())
{
OnestoreEntity.PropertyValue value = specialProp.getValue(entity);
if (value != null) entity.addProperty(specialProp.getProperty(value));
}
}
public DatastorePb.PutResponse putImpl( LocalRpcService.Status status, DatastorePb.PutRequest request )
{
DatastorePb.PutResponse response = new DatastorePb.PutResponse();
if (request.entitySize() == 0)
{
return response;
}
DatastorePb.Cost totalCost = response.getMutableCost();
String app = ((OnestoreEntity.EntityProto)request.entitys().get(0)).getKey().getApp();
List clones = new ArrayList();
for (OnestoreEntity.EntityProto entity : request.entitys())
{
validateAndProcessEntityProto(entity);
OnestoreEntity.EntityProto clone = (OnestoreEntity.EntityProto)entity.clone();
clones.add(clone);
Preconditions.checkArgument(clone.hasKey());
OnestoreEntity.Reference key = clone.getKey();
Preconditions.checkArgument(key.getPath().elementSize() > 0);
clone.getMutableKey().setApp(app);
OnestoreEntity.Path.Element lastPath = Utils.getLastElement(key);
if ((lastPath.getId() == 0L) && (!lastPath.hasName()))
{
lastPath.setId(this.entityId.getAndIncrement());
}
processEntityForSpecialProperties(clone, true);
if (clone.getEntityGroup().elementSize() == 0)
{
OnestoreEntity.Path group = clone.getMutableEntityGroup();
OnestoreEntity.Path.Element root = (OnestoreEntity.Path.Element)key.getPath().elements().get(0);
OnestoreEntity.Path.Element pathElement = group.addElement();
pathElement.setType(root.getType());
if (root.hasName())
pathElement.setName(root.getName());
else
pathElement.setId(root.getId());
}
else
{
Preconditions.checkState((clone.hasEntityGroup()) && (clone.getEntityGroup().elementSize() > 0));
}
}
/*
* AppScale - remainder of body replaced
*/
proxy.doPost(app, "Put", request, response);
if (!request.hasTransaction())
{
logger.fine("Put: " + request.entitySize() + " entities");
}
return response;
}
private void validateAndProcessEntityProto( OnestoreEntity.EntityProto entity )
{
validatePathForPut(entity.getKey());
for (OnestoreEntity.Property prop : entity.propertys())
{
validateAndProcessProperty(prop);
validateLengthLimit(prop);
}
for (OnestoreEntity.Property prop : entity.rawPropertys())
validateAndProcessProperty(prop);
}
private void validatePathForPut( OnestoreEntity.Reference key )
{
OnestoreEntity.Path path = key.getPath();
for (OnestoreEntity.Path.Element ele : path.elements())
{
String type = ele.getType();
if ((RESERVED_NAME.matcher(type).matches()) && (!RESERVED_NAME_WHITELIST.contains(type)))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, String.format("illegal key.path.element.type: %s", new Object[] { ele.getType() }));
}
if ((ele.hasName()) && (ele.getName().length() > 500)) throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "name in key path element must be under 500 characters");
}
}
private void validateAndProcessProperty( OnestoreEntity.Property prop )
{
if (RESERVED_NAME.matcher(prop.getName()).matches())
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, String.format("illegal property.name: %s", new Object[] { prop.getName() }));
}
OnestoreEntity.PropertyValue val = prop.getMutableValue();
if (val.hasUserValue())
{
OnestoreEntity.PropertyValue.UserValue userVal = val.getMutableUserValue();
userVal.setObfuscatedGaiaid(Integer.toString(userVal.getEmail().hashCode()));
}
}
private void validateLengthLimit( OnestoreEntity.Property property )
{
String name = property.getName();
OnestoreEntity.PropertyValue value = property.getValue();
if (value.hasStringValue()) if ((property.hasMeaning()) && (property.getMeaningEnum() == OnestoreEntity.Property.Meaning.ATOM_LINK))
{
if (value.getStringValue().length() > 2038)
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "Link property " + name + " is too long. Use TEXT for links over " + 2038 + " characters.");
}
}
else if (value.getStringValue().length() > 500) throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "string property " + name + " is too long. It cannot exceed " + 500 + " characters.");
}
public DatastorePb.DeleteResponse delete( LocalRpcService.Status status, DatastorePb.DeleteRequest request )
{
try
{
this.globalLock.readLock().lock();
return deleteImpl(status, request);
}
finally
{
this.globalLock.readLock().unlock();
}
}
public ApiBasePb.VoidProto addActions( LocalRpcService.Status status, TaskQueuePb.TaskQueueBulkAddRequest request )
{
try
{
this.globalLock.readLock().lock();
addActionsImpl(status, request);
}
finally
{
this.globalLock.readLock().unlock();
}
return new ApiBasePb.VoidProto();
}
private OnestoreEntity.Path getGroup( OnestoreEntity.Reference key )
{
OnestoreEntity.Path path = key.getPath();
OnestoreEntity.Path group = new OnestoreEntity.Path();
group.addElement(path.getElement(0));
return group;
}
public DatastorePb.DeleteResponse deleteImpl( LocalRpcService.Status status, DatastorePb.DeleteRequest request )
{
DatastorePb.DeleteResponse response = new DatastorePb.DeleteResponse();
if (request.keySize() == 0)
{
return response;
}
/*
* AppScale replaced remainder of method
*/
proxy.doPost(request.getKey(0).getApp(), "Delete", request, response);
if (!request.hasTransaction())
{
logger.fine("deleted " + request.keySize() + " keys.");
}
return response;
}
private void addActionsImpl( LocalRpcService.Status status, TaskQueuePb.TaskQueueBulkAddRequest request )
{
if (request.addRequestSize() == 0)
{
return;
}
List addRequests = new ArrayList(request.addRequestSize());
for (TaskQueuePb.TaskQueueAddRequest addRequest : request.addRequests())
{
addRequests.add(((TaskQueuePb.TaskQueueAddRequest)addRequest.clone()).clearTransaction());
}
Profile profile = (Profile)this.profiles.get(((TaskQueuePb.TaskQueueAddRequest)request.addRequests().get(0)).getTransaction().getApp());
LiveTxn liveTxn = profile.getTxn(((TaskQueuePb.TaskQueueAddRequest)request.addRequests().get(0)).getTransaction().getHandle());
liveTxn.addActions(addRequests);
}
public DatastorePb.QueryResult runQuery( LocalRpcService.Status status, DatastorePb.Query query )
{
final LocalCompositeIndexManager.ValidatedQuery validatedQuery = new LocalCompositeIndexManager.ValidatedQuery(query);
query = validatedQuery.getQuery();
String app = query.getApp();
Profile profile = getOrCreateProfile(app);
synchronized (profile)
{
if ((query.hasTransaction()) || (query.hasAncestor()))
{
OnestoreEntity.Path groupPath = getGroup(query.getAncestor());
LocalDatastoreService.Profile.EntityGroup eg = profile.getGroup(groupPath);
if (query.hasTransaction())
{
if (!app.equals(query.getTransaction().getApp()))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.INTERNAL_ERROR, "Can't query app " + app + "in a transaction on app " + query.getTransaction().getApp());
}
LiveTxn liveTxn = profile.getTxn(query.getTransaction().getHandle());
eg.addTransaction(liveTxn);
}
if ((query.hasAncestor()) && ((query.hasTransaction()) || (!query.hasFailoverMs())))
{
eg.rollForwardUnappliedJobs();
}
}
LocalFullTextIndex fullTextIndex = profile.getFullTextIndex();
if ((query.hasSearchQuery()) && (fullTextIndex == null))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "full-text search unsupported");
}
/*
* AppScale line replacement to #end
*/
DatastorePb.QueryResult queryResult = new DatastorePb.QueryResult();
proxy.doPost(app, "RunQuery", query, queryResult);
List<EntityProto> queryEntities = new ArrayList<EntityProto>(queryResult.results());
/* #end */
if (queryEntities == null)
{
Map extents = profile.getExtents();
Extent extent = (Extent)extents.get(query.getKind());
if (!query.hasSearchQuery())
{
if (extent != null)
{
queryEntities = new ArrayList(extent.getEntities().values());
}
else if (!query.hasKind())
{
queryEntities = profile.getAllEntities();
if (query.orderSize() == 0)
{
query.addOrder(new DatastorePb.Query.Order().setDirection(DatastorePb.Query.Order.Direction.ASCENDING).setProperty("__key__"));
}
}
}
else
{
/*
* AppScale - Added type to keys below
*/
List<OnestoreEntity.Reference> keys = fullTextIndex.search(query.getKind(), query.getSearchQuery());
List entities = new ArrayList(keys.size());
for (OnestoreEntity.Reference key : keys)
{
entities.add(extent.getEntities().get(key));
}
queryEntities = entities;
}
}
profile.groom();
if (queryEntities == null)
{
queryEntities = Collections.emptyList();
}
List predicates = new ArrayList();
if (query.hasAncestor())
{
final List ancestorPath = query.getAncestor().getPath().elements();
predicates.add(new Predicate()
{
public boolean apply( Object entity )
{
/*
* AppScale - Added type to entity below
*/
List path = ((OnestoreEntity.EntityProto)entity).getKey().getPath().elements();
return (path.size() >= ancestorPath.size()) && (path.subList(0, ancestorPath.size()).equals(ancestorPath));
}
});
}
final boolean hasNamespace = query.hasNameSpace();
final String namespace = query.getNameSpace();
predicates.add(new Predicate()
{
/*
* Added type to entity below
*/
public boolean apply( Object entity )
{
OnestoreEntity.Reference ref = ((OnestoreEntity.EntityProto)entity).getKey();
if (hasNamespace)
{
if ((!ref.hasNameSpace()) || (!namespace.equals(ref.getNameSpace())))
{
return false;
}
}
else if (ref.hasNameSpace())
{
return false;
}
return true;
}
});
final EntityProtoComparators.EntityProtoComparator entityComparator = new EntityProtoComparators.EntityProtoComparator(validatedQuery.getQuery().orders(), validatedQuery.getQuery().filters());
predicates.add(new Predicate()
{
public boolean apply( Object entity )
{
/*
* AppScale - Added cast to entity below
*/
return entityComparator.matches((EntityProto)entity);
}
});
Predicate queryPredicate = Predicates.not(Predicates.and(predicates));
Iterators.removeIf(queryEntities.iterator(), queryPredicate);
if (query.propertyNameSize() > 0)
{
queryEntities = createIndexOnlyQueryResults(queryEntities, entityComparator);
}
Collections.sort(queryEntities, entityComparator);
LiveQuery liveQuery = new LiveQuery(queryEntities, query, entityComparator, this.clock);
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
LocalCompositeIndexManager.getInstance().processQuery(validatedQuery.getQuery());
return null;
}
});
/*
* AppScale - removed duplicate count instantiations
*/
int count;
if (query.hasCount())
{
count = query.getCount();
}
else
{
if (query.hasLimit())
count = query.getLimit();
else
{
count = 20;
}
}
DatastorePb.QueryResult result = nextImpl(liveQuery, query.getOffset(), count, query.isCompile());
if (query.isCompile())
{
result.setCompiledQuery(liveQuery.compileQuery());
}
if (result.isMoreResults())
{
long cursor = this.queryId.getAndIncrement();
profile.addQuery(cursor, liveQuery);
result.getMutableCursor().setApp(query.getApp()).setCursor(cursor);
}
for (OnestoreEntity.Index index : LocalCompositeIndexManager.getInstance().queryIndexList(query))
{
result.addIndex(wrapIndexInCompositeIndex(app, index));
- }
+ }
+ /*
+ * AppScale - adding skipped results to the result, otherwise query counts are wrong
+ */
+ result.setSkippedResults(queryResult.getSkippedResults());
return result;
}
}
private List<OnestoreEntity.EntityProto> createIndexOnlyQueryResults( List<OnestoreEntity.EntityProto> queryEntities, EntityProtoComparators.EntityProtoComparator entityComparator )
{
Set postfixProps = Sets.newHashSetWithExpectedSize(entityComparator.getAdjustedOrders().size());
for (DatastorePb.Query.Order order : entityComparator.getAdjustedOrders())
{
postfixProps.add(order.getProperty());
}
List results = Lists.newArrayListWithExpectedSize(queryEntities.size());
for (OnestoreEntity.EntityProto entity : queryEntities)
{
List indexEntities = createIndexEntities(entity, postfixProps, entityComparator);
results.addAll(indexEntities);
}
return results;
}
private List<OnestoreEntity.EntityProto> createIndexEntities( OnestoreEntity.EntityProto entity, Set<String> postfixProps, EntityProtoComparators.EntityProtoComparator entityComparator )
{
Multimap toSplit = HashMultimap.create(postfixProps.size(), 1);
Set seen = Sets.newHashSet();
boolean splitRequired = false;
for (OnestoreEntity.Property prop : entity.propertys())
{
if (postfixProps.contains(prop.getName()))
{
splitRequired |= !seen.add(prop.getName());
if (entityComparator.matches(prop))
{
toSplit.put(prop.getName(), prop.getValue());
}
}
}
if (!splitRequired)
{
return Collections.singletonList(entity);
}
OnestoreEntity.EntityProto clone = new OnestoreEntity.EntityProto();
clone.getMutableKey().copyFrom(entity.getKey());
clone.getMutableEntityGroup();
List results = Lists.newArrayList(new OnestoreEntity.EntityProto[] { clone });
for (Map.Entry entry : ((Set<Map.Entry>)toSplit.asMap().entrySet()))
if (((Collection)entry.getValue()).size() == 1)
{
/*
* AppScale - Added cast to results below
*/
for (OnestoreEntity.EntityProto result : ((List<OnestoreEntity.EntityProto>)results))
{
result.addProperty().setName((String)entry.getKey()).setMeaning(OnestoreEntity.Property.Meaning.INDEX_VALUE).getMutableValue().copyFrom(((PropertyValue)((ProtocolMessage)Iterables.getOnlyElement((Iterable)entry.getValue()))));
}
}
else
{
List splitResults = Lists.newArrayListWithCapacity(results.size() * ((Collection)entry.getValue()).size());
for (Iterator i$ = ((Collection)entry.getValue()).iterator(); i$.hasNext();)
{
/*
* AppScale - Added type to value below
*/
OnestoreEntity.PropertyValue value = (OnestoreEntity.PropertyValue)i$.next();
/*
* AppScale - Added type to results below
*/
for (OnestoreEntity.EntityProto result : (List<OnestoreEntity.EntityProto>)results)
{
OnestoreEntity.EntityProto split = (OnestoreEntity.EntityProto)result.clone();
split.addProperty().setName((String)entry.getKey()).setMeaning(OnestoreEntity.Property.Meaning.INDEX_VALUE).getMutableValue().copyFrom(value);
splitResults.add(split);
}
}
OnestoreEntity.PropertyValue value;
results = splitResults;
}
return results;
}
private static <T> T safeGetFromExpiringMap( Map<Long, T> map, long key, String errorMsg )
{
/*
* AppScale - Changed "value" from type Object to T
*/
T value = map.get(Long.valueOf(key));
if (value == null)
{
throw Utils.newError(DatastorePb.Error.ErrorCode.INTERNAL_ERROR, errorMsg);
}
return value;
}
public DatastorePb.QueryResult next( LocalRpcService.Status status, DatastorePb.NextRequest request )
{
Profile profile = (Profile)this.profiles.get(request.getCursor().getApp());
LiveQuery liveQuery = profile.getQuery(request.getCursor().getCursor());
int count = request.hasCount() ? request.getCount() : 20;
DatastorePb.QueryResult result = nextImpl(liveQuery, request.getOffset(), count, request.isCompile());
if (result.isMoreResults())
result.setCursor(request.getCursor());
else
{
profile.removeQuery(request.getCursor().getCursor());
}
return result;
}
private DatastorePb.QueryResult nextImpl( LiveQuery liveQuery, int offset, int count, boolean compile )
{
DatastorePb.QueryResult result = new DatastorePb.QueryResult();
if (offset > 0)
{
result.setSkippedResults(liveQuery.offsetResults(offset));
}
if (offset == result.getSkippedResults())
{
int end = Math.min(300, count);
result.mutableResults().addAll(liveQuery.nextResults(end));
}
result.setMoreResults(liveQuery.entitiesRemaining().size() > 0);
result.setKeysOnly(liveQuery.isKeysOnly());
if (compile)
{
result.getMutableCompiledCursor().addPosition(liveQuery.compilePosition());
}
return result;
}
public ApiBasePb.VoidProto deleteCursor( LocalRpcService.Status status, DatastorePb.Cursor request )
{
Profile profile = (Profile)this.profiles.get(request.getApp());
profile.removeQuery(request.getCursor());
return new ApiBasePb.VoidProto();
}
public DatastorePb.Transaction beginTransaction( LocalRpcService.Status status, DatastorePb.BeginTransactionRequest req )
{
Profile profile = getOrCreateProfile(req.getApp());
DatastorePb.Transaction txn = new DatastorePb.Transaction().setApp(req.getApp()).setHandle(this.transactionHandleProvider.getAndIncrement());
if ((req.isAllowMultipleEg()) && (!isHighRep()))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "transactions on multiple entity groups only allowed in High Replication applications");
}
/*
* AppScale line replacement
*/
proxy.doPost(req.getApp(), "BeginTransaction", req, txn);
profile.addTxn(txn.getHandle(), new LiveTxn(this.clock, req.isAllowMultipleEg()));
return txn;
}
public DatastorePb.CommitResponse commit( LocalRpcService.Status status, DatastorePb.Transaction req )
{
Profile profile = (Profile)this.profiles.get(req.getApp());
DatastorePb.CommitResponse response = new DatastorePb.CommitResponse();
/*
* AppScale - Added proxy call
*/
proxy.doPost(req.getApp(), "Commit", req, response);
synchronized (profile)
{
LiveTxn liveTxn = profile.removeTxn(req.getHandle());
/*
* AppScale removed if block
*/
for (TaskQueuePb.TaskQueueAddRequest action : liveTxn.getActions())
{
try
{
ApiProxy.makeSyncCall("taskqueue", "Add", action.toByteArray());
}
catch (ApiProxy.ApplicationException e)
{
logger.log(Level.WARNING, "Transactional task: " + action + " has been dropped.", e);
}
}
}
return response;
}
private DatastorePb.Cost commitImpl( LiveTxn liveTxn, final Profile profile )
{
for (EntityGroupTracker tracker : liveTxn.getAllTrackers())
{
tracker.checkEntityGroupVersion();
}
int deleted = 0;
int written = 0;
DatastorePb.Cost totalCost = new DatastorePb.Cost();
for (EntityGroupTracker tracker : liveTxn.getAllTrackers())
{
LocalDatastoreService.Profile.EntityGroup eg = tracker.getEntityGroup();
eg.incrementVersion();
final Collection writtenEntities = tracker.getWrittenEntities();
final Collection deletedKeys = tracker.getDeletedKeys();
LocalDatastoreJob job = new LocalDatastoreJob(this.highRepJobPolicy, eg.pathAsKey())
{
private DatastorePb.Cost calculateJobCost( boolean apply )
{
DatastorePb.Cost cost = LocalDatastoreService.this.calculatePutCost(apply, profile, writtenEntities);
/*
* AppScale - Before: LocalDatastoreService.addTo(cost,
* LocalDatastoreService
* .access$700(LocalDatastoreService.this, apply, profile,
* deletedKeys)); After (2lines):
*/
DatastorePb.Cost cost2 = LocalDatastoreService.this.calculateDeleteCost(apply, profile, deletedKeys);
LocalDatastoreService.addTo(cost, cost2); // CJK
return cost;
}
DatastorePb.Cost calculateJobCost()
{
return calculateJobCost(false);
}
DatastorePb.Cost applyInternal()
{
return calculateJobCost(true);
}
};
addTo(totalCost, eg.addJob(job));
deleted += deletedKeys.size();
written += writtenEntities.size();
}
logger.fine("committed: " + written + " puts, " + deleted + " deletes in " + liveTxn.getAllTrackers().size() + " entity groups");
return totalCost;
}
/*
* AppScale body replaced CJK: Keeping removeTxn in this method b/c
* removeTxn in commit(..) above is kept
*/
public ApiBasePb.VoidProto rollback( LocalRpcService.Status status, DatastorePb.Transaction req )
{
((Profile)this.profiles.get(req.getApp())).removeTxn(req.getHandle());
VoidProto response = new VoidProto();
proxy.doPost(req.getApp(), "Rollback", req, response);
return response;
}
/*
* AppScale replaced body
*/
public ApiBasePb.Integer64Proto createIndex( LocalRpcService.Status status, OnestoreEntity.CompositeIndex req )
{
Integer64Proto response = new Integer64Proto();
if (req.getId() != 0)
{
throw new IllegalArgumentException("New index id must be 0.");
}
proxy.doPost(req.getAppId(), "CreateIndex", req, response);
return response;
}
/*
* AppScale replaced body
*/
public ApiBasePb.VoidProto updateIndex( LocalRpcService.Status status, OnestoreEntity.CompositeIndex req )
{
VoidProto response = new ApiBasePb.VoidProto();
proxy.doPost(req.getAppId(), "UpdateIndex", req, response);
return response;
}
private OnestoreEntity.CompositeIndex wrapIndexInCompositeIndex( String app, OnestoreEntity.Index index )
{
OnestoreEntity.CompositeIndex ci = new OnestoreEntity.CompositeIndex().setAppId(app).setState(OnestoreEntity.CompositeIndex.State.READ_WRITE);
if (index != null)
{
ci.setDefinition(index);
}
return ci;
}
/*
* AppScale replaced body
*/
public DatastorePb.CompositeIndices getIndices( LocalRpcService.Status status, ApiBasePb.StringProto req )
{
DatastorePb.CompositeIndices answer = new DatastorePb.CompositeIndices();
proxy.doPost(req.getValue(), "GetIndices", req, answer);
return answer;
}
/*
* AppScale - replaced body
*/
public ApiBasePb.VoidProto deleteIndex( LocalRpcService.Status status, OnestoreEntity.CompositeIndex req )
{
VoidProto response = new VoidProto();
proxy.doPost(req.getAppId(), "DeleteIndex", req, response);
return response;
}
public DatastorePb.AllocateIdsResponse allocateIds( LocalRpcService.Status status, DatastorePb.AllocateIdsRequest req )
{
try
{
this.globalLock.readLock().lock();
return allocateIdsImpl(req);
}
finally
{
this.globalLock.readLock().unlock();
}
}
/*
* AppScale - replaced body
*/
private DatastorePb.AllocateIdsResponse allocateIdsImpl( DatastorePb.AllocateIdsRequest req )
{
if (req.hasSize() && req.getSize() > MAX_BATCH_GET_KEYS)
{
throw new ApiProxy.ApplicationException(DatastorePb.Error.ErrorCode.BAD_REQUEST.getValue(), "cannot get more than " + MAX_BATCH_GET_KEYS + " keys in a single call");
}
DatastorePb.AllocateIdsResponse response = new DatastorePb.AllocateIdsResponse();
proxy.doPost("appId", "AllocateIds", req, response);
return response;
}
Profile getOrCreateProfile( String app )
{
synchronized (this.profiles)
{
Preconditions.checkArgument((app != null) && (app.length() > 0), "appId not set");
Profile profile = (Profile)this.profiles.get(app);
if (profile == null)
{
profile = new Profile();
this.profiles.put(app, profile);
}
return profile;
}
}
Extent getOrCreateExtent( Profile profile, String kind )
{
Map extents = profile.getExtents();
synchronized (extents)
{
Extent e = (Extent)extents.get(kind);
if (e == null)
{
e = new Extent();
extents.put(kind, e);
}
return e;
}
}
private void load()
{
if (this.noStorage)
{
return;
}
File backingStoreFile = new File(this.backingStore);
String path = backingStoreFile.getAbsolutePath();
if (!backingStoreFile.exists())
{
logger.log(Level.INFO, "The backing store, " + path + ", does not exist. " + "It will be created.");
return;
}
try
{
long start = this.clock.getCurrentTime();
ObjectInputStream objectIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream(this.backingStore)));
this.entityId.set(objectIn.readLong());
Map profilesOnDisk = (Map)objectIn.readObject();
this.profiles = profilesOnDisk;
objectIn.close();
long end = this.clock.getCurrentTime();
logger.log(Level.INFO, "Time to load datastore: " + (end - start) + " ms");
}
catch (FileNotFoundException e)
{
logger.log(Level.SEVERE, "Failed to find the backing store, " + path);
}
catch (IOException e)
{
logger.log(Level.INFO, "Failed to load from the backing store, " + path, e);
}
catch (ClassNotFoundException e)
{
logger.log(Level.INFO, "Failed to load from the backing store, " + path, e);
}
}
static void pruneHasCreationTimeMap( long now, int maxLifetimeMs, Map<Long, ? extends HasCreationTime> hasCreationTimeMap )
{
long deadline = now - maxLifetimeMs;
Iterator queryIt = hasCreationTimeMap.entrySet().iterator();
while (queryIt.hasNext())
{
Map.Entry entry = (Map.Entry)queryIt.next();
HasCreationTime query = (HasCreationTime)entry.getValue();
if (query.getCreationTime() < deadline) queryIt.remove();
}
}
static Map<String, SpecialProperty> getSpecialPropertyMap()
{
return specialPropertyMap;
}
void removeStaleQueriesNow()
{
this.removeStaleQueriesTask.run();
}
void removeStaleTxnsNow()
{
this.removeStaleTransactionsTask.run();
}
public Double getDefaultDeadline( boolean isOfflineRequest )
{
return Double.valueOf(30.0D);
}
public Double getMaximumDeadline( boolean isOfflineRequest )
{
return Double.valueOf(30.0D);
}
public CreationCostAnalysis getCreationCostAnalysis( Entity e )
{
return this.costAnalysis.getCreationCostAnalysis(EntityTranslator.convertToPb(e));
}
private static void addTo( DatastorePb.Cost target, DatastorePb.Cost addMe )
{
target.setEntityWrites(target.getEntityWrites() + addMe.getEntityWrites());
target.setIndexWrites(target.getIndexWrites() + addMe.getIndexWrites());
}
private DatastorePb.Cost calculatePutCost( boolean apply, Profile profile, Collection<OnestoreEntity.EntityProto> entities )
{
DatastorePb.Cost totalCost = new DatastorePb.Cost();
for (OnestoreEntity.EntityProto entityProto : entities)
{
String kind = Utils.getKind(entityProto.getKey());
Extent extent = getOrCreateExtent(profile, kind);
OnestoreEntity.EntityProto oldEntity;
if (apply)
{
/*
* AppScale - removed type declaration from oldEntity below
*/
oldEntity = (OnestoreEntity.EntityProto)extent.getEntities().put(entityProto.getKey(), entityProto);
LocalFullTextIndex fullTextIndex = profile.getFullTextIndex();
if (fullTextIndex != null) fullTextIndex.write(entityProto);
}
else
{
oldEntity = (OnestoreEntity.EntityProto)extent.getEntities().get(entityProto.getKey());
}
addTo(totalCost, this.costAnalysis.getWriteOps(oldEntity, entityProto));
}
if (apply)
{
this.dirty = true;
}
return totalCost;
}
private DatastorePb.Cost calculateDeleteCost( boolean apply, Profile profile, Collection<OnestoreEntity.Reference> keys )
{
DatastorePb.Cost totalCost = new DatastorePb.Cost();
for (OnestoreEntity.Reference key : keys)
{
String kind = Utils.getKind(key);
Map extents = profile.getExtents();
Extent extent = (Extent)extents.get(kind);
if (extent != null)
{
OnestoreEntity.EntityProto oldEntity;
if (apply)
{
oldEntity = (OnestoreEntity.EntityProto)extent.getEntities().remove(key);
LocalFullTextIndex fullTextIndex = profile.getFullTextIndex();
if (fullTextIndex != null) fullTextIndex.delete(key);
}
else
{
/*
* AppScale - removed type declaration from oldEntity below
*/
oldEntity = (OnestoreEntity.EntityProto)extent.getEntities().get(key);
}
if (oldEntity != null)
{
addTo(totalCost, this.costAnalysis.getWriteCost(oldEntity));
}
}
}
if (apply)
{
this.dirty = true;
}
return totalCost;
}
private class PersistDatastore implements Runnable
{
private PersistDatastore()
{}
public void run()
{
try
{
LocalDatastoreService.this.globalLock.writeLock().lock();
privilegedPersist();
}
catch (IOException e)
{
LocalDatastoreService.logger.log(Level.SEVERE, "Unable to save the datastore", e);
}
finally
{
LocalDatastoreService.this.globalLock.writeLock().unlock();
}
}
private void privilegedPersist() throws IOException
{
try
{
AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws IOException
{
LocalDatastoreService.PersistDatastore.this.persist();
return null;
}
});
}
catch (PrivilegedActionException e)
{
Throwable t = e.getCause();
if ((t instanceof IOException))
{
throw ((IOException)t);
}
throw new RuntimeException(t);
}
}
private void persist() throws IOException
{
if ((LocalDatastoreService.this.noStorage) || (!LocalDatastoreService.this.dirty))
{
return;
}
long start = LocalDatastoreService.this.clock.getCurrentTime();
ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(LocalDatastoreService.this.backingStore)));
objectOut.writeLong(LocalDatastoreService.this.entityId.get());
objectOut.writeObject(LocalDatastoreService.this.profiles);
objectOut.close();
LocalDatastoreService.this.dirty = false;
long end = LocalDatastoreService.this.clock.getCurrentTime();
LocalDatastoreService.logger.log(Level.INFO, "Time to persist datastore: " + (end - start) + " ms");
}
}
static enum SpecialProperty
{
SCATTER(false, true);
private final String name;
private final boolean isVisible;
private final boolean isStored;
private SpecialProperty( boolean isVisible, boolean isStored )
{
this.name = ("__" + name().toLowerCase() + "__");
this.isVisible = isVisible;
this.isStored = isStored;
}
public final String getName()
{
return this.name;
}
public final boolean isVisible()
{
return this.isVisible;
}
final boolean isStored()
{
return this.isStored;
}
OnestoreEntity.PropertyValue getValue( OnestoreEntity.EntityProto entity )
{
/*
* AppScale - changed to avoid UnsupportedOperationException()
* thrown for all DB txn's.
*/
return null;
// CJK throw new UnsupportedOperationException();
}
OnestoreEntity.Property getProperty( OnestoreEntity.PropertyValue value )
{
OnestoreEntity.Property processedProp = new OnestoreEntity.Property();
processedProp.setName(getName());
processedProp.setValue(value);
processedProp.setMultiple(false);
return processedProp;
}
}
private class RemoveStaleTransactions implements Runnable
{
private RemoveStaleTransactions()
{}
public void run()
{
for (LocalDatastoreService.Profile profile : LocalDatastoreService.this.profiles.values())
/*
* AppScale - changed from access$2100 to profile.getTxns()
*/
synchronized (profile.getTxns())
{
LocalDatastoreService.pruneHasCreationTimeMap(LocalDatastoreService.this.clock.getCurrentTime(), LocalDatastoreService.this.maxTransactionLifetimeMs, profile.getTxns());
}
}
}
private class RemoveStaleQueries implements Runnable
{
private RemoveStaleQueries()
{}
public void run()
{
/*
* AppScale - changed to get rid of "access$1800" which is caued by
* accessing inner class variables
*/
for (LocalDatastoreService.Profile profile : LocalDatastoreService.this.profiles.values())
synchronized (profile.getQueries())
{
LocalDatastoreService.pruneHasCreationTimeMap(LocalDatastoreService.this.clock.getCurrentTime(), LocalDatastoreService.this.maxQueryLifetimeMs, profile.getQueries());
}
}
}
static class EntityGroupTracker
{
private LocalDatastoreService.Profile.EntityGroup entityGroup;
private Long entityGroupVersion;
private final Map<OnestoreEntity.Reference, OnestoreEntity.EntityProto> written = new HashMap();
private final Set<OnestoreEntity.Reference> deleted = new HashSet();
EntityGroupTracker( LocalDatastoreService.Profile.EntityGroup entityGroup )
{
this.entityGroup = entityGroup;
this.entityGroupVersion = Long.valueOf(entityGroup.getVersion());
}
synchronized LocalDatastoreService.Profile.EntityGroup getEntityGroup()
{
return this.entityGroup;
}
synchronized void checkEntityGroupVersion()
{
if (!this.entityGroupVersion.equals(Long.valueOf(this.entityGroup.getVersion()))) throw Utils.newError(DatastorePb.Error.ErrorCode.CONCURRENT_TRANSACTION, "too much contention on these datastore entities. please try again.");
}
synchronized Long getEntityGroupVersion()
{
return this.entityGroupVersion;
}
synchronized void addWrittenEntity( OnestoreEntity.EntityProto entity )
{
OnestoreEntity.Reference key = entity.getKey();
this.written.put(key, entity);
this.deleted.remove(key);
}
synchronized void addDeletedEntity( OnestoreEntity.Reference key )
{
this.deleted.add(key);
this.written.remove(key);
}
synchronized Collection<OnestoreEntity.EntityProto> getWrittenEntities()
{
return new ArrayList(this.written.values());
}
synchronized Collection<OnestoreEntity.Reference> getDeletedKeys()
{
return new ArrayList(this.deleted);
}
synchronized boolean isDirty()
{
return this.written.size() + this.deleted.size() > 0;
}
}
static class LiveTxn extends LocalDatastoreService.HasCreationTime
{
private final Map<LocalDatastoreService.Profile.EntityGroup, LocalDatastoreService.EntityGroupTracker> entityGroups = new HashMap();
private final List<TaskQueuePb.TaskQueueAddRequest> actions = new ArrayList();
private final boolean allowMultipleEg;
private boolean failed = false;
LiveTxn( Clock clock, boolean allowMultipleEg )
{
/*
* changed super() call below to include clocl.getCurrentTime()
*/
super(clock.getCurrentTime());
this.allowMultipleEg = allowMultipleEg;
}
synchronized LocalDatastoreService.EntityGroupTracker trackEntityGroup( LocalDatastoreService.Profile.EntityGroup newEntityGroup )
{
if (newEntityGroup == null)
{
throw new NullPointerException("EntityGroup cannot be null");
}
checkFailed();
LocalDatastoreService.EntityGroupTracker tracker = (LocalDatastoreService.EntityGroupTracker)this.entityGroups.get(newEntityGroup);
if (tracker == null)
{
if (this.allowMultipleEg)
{
if (this.entityGroups.size() >= 5)
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "operating on too many entity groups in a single transaction.");
}
}
else if (this.entityGroups.size() >= 1)
{
LocalDatastoreService.Profile.EntityGroup entityGroup = (LocalDatastoreService.Profile.EntityGroup)this.entityGroups.keySet().iterator().next();
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "cross-group transaction need to be explicitly specified, see TransactionOptions.Builder.withXGfound both " + entityGroup + " and " + newEntityGroup);
}
for (LocalDatastoreService.EntityGroupTracker other : getAllTrackers())
{
try
{
other.checkEntityGroupVersion();
}
catch (ApiProxy.ApplicationException e)
{
this.failed = true;
throw e;
}
}
tracker = new LocalDatastoreService.EntityGroupTracker(newEntityGroup);
this.entityGroups.put(newEntityGroup, tracker);
}
return tracker;
}
synchronized Collection<LocalDatastoreService.EntityGroupTracker> getAllTrackers()
{
return this.entityGroups.values();
}
synchronized void addActions( Collection<TaskQueuePb.TaskQueueAddRequest> newActions )
{
checkFailed();
if (this.actions.size() + newActions.size() > 5L)
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "Too many messages, maximum allowed: 5");
}
this.actions.addAll(newActions);
}
synchronized Collection<TaskQueuePb.TaskQueueAddRequest> getActions()
{
return new ArrayList(this.actions);
}
synchronized boolean isDirty()
{
checkFailed();
for (LocalDatastoreService.EntityGroupTracker tracker : getAllTrackers())
{
if (tracker.isDirty())
{
return true;
}
}
return false;
}
synchronized void close()
{
for (LocalDatastoreService.EntityGroupTracker tracker : getAllTrackers())
tracker.getEntityGroup().removeTransaction(this);
}
private void checkFailed()
{
if (this.failed) throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "transaction closed");
}
}
static class LiveQuery extends LocalDatastoreService.HasCreationTime
{
private final Set<String> orderProperties;
private final Set<String> projectedProperties;
private final DatastorePb.Query query;
private List<OnestoreEntity.EntityProto> entities;
private OnestoreEntity.EntityProto lastResult = null;
public LiveQuery( List<OnestoreEntity.EntityProto> entities, DatastorePb.Query query, EntityProtoComparators.EntityProtoComparator entityComparator, Clock clock )
{
/*
* AppScale - included param in super() call.
*/
super(clock.getCurrentTime());
if (entities == null)
{
throw new NullPointerException("Entities cannot be null");
}
this.query = query;
this.entities = entities;
this.orderProperties = new HashSet();
for (DatastorePb.Query.Order order : entityComparator.getAdjustedOrders())
{
if (!"__key__".equals(order.getProperty()))
{
this.orderProperties.add(order.getProperty());
}
}
this.projectedProperties = Sets.newHashSet(query.propertyNames());
applyCursors(entityComparator);
applyLimit();
entities = Lists.newArrayList(entities);
}
private void applyCursors( EntityProtoComparators.EntityProtoComparator entityComparator )
{
DecompiledCursor startCursor = new DecompiledCursor(this.query.getCompiledCursor());
this.lastResult = startCursor.getCursorEntity();
int endCursorPos = new DecompiledCursor(this.query.getEndCompiledCursor()).getPosition(entityComparator, this.entities.size());
int startCursorPos = Math.min(endCursorPos, startCursor.getPosition(entityComparator, 0));
this.entities = this.entities.subList(startCursorPos, endCursorPos);
}
private void applyLimit()
{
if (this.query.hasLimit())
{
int toIndex = this.query.getLimit() + this.query.getOffset();
if ((toIndex < 0) || (toIndex > this.entities.size()))
{
toIndex = this.entities.size();
}
this.entities = this.entities.subList(0, toIndex);
}
}
public List<OnestoreEntity.EntityProto> entitiesRemaining()
{
return this.entities;
}
public int offsetResults( int offset )
{
int realOffset = Math.min(Math.min(offset, this.entities.size()), 300);
if (realOffset > 0)
{
this.lastResult = ((OnestoreEntity.EntityProto)this.entities.get(realOffset - 1));
this.entities = this.entities.subList(realOffset, this.entities.size());
}
return realOffset;
}
public List<OnestoreEntity.EntityProto> nextResults( int end )
{
List<OnestoreEntity.EntityProto> subList = this.entities.subList(0, Math.min(end, this.entities.size()));
if (subList.size() > 0)
{
this.lastResult = ((OnestoreEntity.EntityProto)subList.get(subList.size() - 1));
}
List results = new ArrayList(subList.size());
for (OnestoreEntity.EntityProto entity : subList)
{
OnestoreEntity.EntityProto result;
Set seenProps;
if (!this.projectedProperties.isEmpty())
{
result = new OnestoreEntity.EntityProto();
result.getMutableKey().copyFrom(entity.getKey());
result.getMutableEntityGroup();
seenProps = Sets.newHashSetWithExpectedSize(this.query.propertyNameSize());
for (OnestoreEntity.Property prop : entity.propertys())
{
if (this.projectedProperties.contains(prop.getName()))
{
if (!seenProps.add(prop.getName()))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.INTERNAL_ERROR, "LocalDatstoreServer produced invalude results.");
}
result.addProperty().setName(prop.getName()).setMeaning(OnestoreEntity.Property.Meaning.INDEX_VALUE).setMultiple(false).getMutableValue().copyFrom(prop.getValue());
}
}
}
else if (this.query.isKeysOnly())
{
/*
* Removed type declaration of result below
*/
result = new OnestoreEntity.EntityProto();
result.getMutableKey().copyFrom(entity.getKey());
result.getMutableEntityGroup();
}
else
{
result = (OnestoreEntity.EntityProto)entity.clone();
}
LocalDatastoreService.processEntityForSpecialProperties(result, false);
results.add(result);
}
subList.clear();
return results;
}
public void restrictRange( int fromIndex, int toIndex )
{
toIndex = Math.max(fromIndex, toIndex);
if (fromIndex > 0)
{
this.lastResult = ((OnestoreEntity.EntityProto)this.entities.get(fromIndex - 1));
}
if ((fromIndex != 0) || (toIndex != this.entities.size())) this.entities = new ArrayList(this.entities.subList(fromIndex, toIndex));
}
public boolean isKeysOnly()
{
return this.query.isKeysOnly();
}
public OnestoreEntity.EntityProto decompilePosition( DatastorePb.CompiledCursor.Position position )
{
OnestoreEntity.EntityProto result = new OnestoreEntity.EntityProto();
if (position.hasKey())
{
if ((this.query.hasKind()) && (!this.query.getKind().equals(((OnestoreEntity.Path.Element)Iterables.getLast(position.getKey().getPath().elements())).getType())))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "Cursor does not match query.");
}
result.setKey(position.getKey());
}
Set remainingProperties = new HashSet(this.orderProperties);
for (DatastorePb.CompiledCursor.PositionIndexValue prop : position.indexValues())
{
if (!this.orderProperties.contains(prop.getProperty()))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "Cursor does not match query.");
}
remainingProperties.remove(prop.getProperty());
result.addProperty().setName(prop.getProperty()).setValue(prop.getValue());
}
if (!remainingProperties.isEmpty())
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "Cursor does not match query.");
}
return result;
}
public DatastorePb.CompiledCursor.Position compilePosition()
{
DatastorePb.CompiledCursor.Position position = new DatastorePb.CompiledCursor.Position();
if (this.lastResult != null)
{
position.setKey(this.lastResult.getKey());
for (OnestoreEntity.Property prop : this.lastResult.propertys())
{
if (this.orderProperties.contains(prop.getName()))
{
position.addIndexValue().setProperty(prop.getName()).setValue(prop.getValue());
}
}
position.setStartInclusive(false);
}
return position;
}
public DatastorePb.CompiledQuery compileQuery()
{
DatastorePb.CompiledQuery result = new DatastorePb.CompiledQuery();
DatastorePb.CompiledQuery.PrimaryScan scan = result.getMutablePrimaryScan();
scan.setIndexNameAsBytes(this.query.toByteArray());
return result;
}
class DecompiledCursor
{
final OnestoreEntity.EntityProto cursorEntity;
final boolean inclusive;
public DecompiledCursor( DatastorePb.CompiledCursor compiledCursor )
{
if ((compiledCursor == null) || (compiledCursor.positionSize() == 0))
{
this.cursorEntity = null;
this.inclusive = false;
return;
}
DatastorePb.CompiledCursor.Position position = compiledCursor.getPosition(0);
if ((!position.hasStartKey()) && (!position.hasKey()) && (position.indexValueSize() <= 0))
{
this.cursorEntity = null;
this.inclusive = false;
return;
}
this.cursorEntity = LocalDatastoreService.LiveQuery.this.decompilePosition(position);
this.inclusive = position.isStartInclusive();
}
public int getPosition( EntityProtoComparators.EntityProtoComparator entityComparator, int defaultValue )
{
if (this.cursorEntity == null)
{
return defaultValue;
}
int loc = Collections.binarySearch(LocalDatastoreService.LiveQuery.this.entities, this.cursorEntity, entityComparator);
if (loc < 0)
{
return -(loc + 1);
}
return this.inclusive ? loc : loc + 1;
}
public OnestoreEntity.EntityProto getCursorEntity()
{
return this.cursorEntity;
}
}
}
static class HasCreationTime
{
private final long creationTime;
HasCreationTime( long creationTime )
{
this.creationTime = creationTime;
}
long getCreationTime()
{
return this.creationTime;
}
}
static class Extent implements Serializable
{
private Map<OnestoreEntity.Reference, OnestoreEntity.EntityProto> entities = new LinkedHashMap();
public Map<OnestoreEntity.Reference, OnestoreEntity.EntityProto> getEntities()
{
return this.entities;
}
}
static class Profile implements Serializable
{
private final Map<String, LocalDatastoreService.Extent> extents = Collections.synchronizedMap(new HashMap());
private transient Map<OnestoreEntity.Path, EntityGroup> groups;
private transient Set<OnestoreEntity.Path> groupsWithUnappliedJobs;
private transient Map<Long, LocalDatastoreService.LiveQuery> queries;
private transient Map<Long, LocalDatastoreService.LiveTxn> txns;
private final LocalFullTextIndex fullTextIndex;
public synchronized List<OnestoreEntity.EntityProto> getAllEntities()
{
List entities = new ArrayList();
for (LocalDatastoreService.Extent extent : this.extents.values())
{
entities.addAll(extent.getEntities().values());
}
return entities;
}
public Profile()
{
this.fullTextIndex = createFullTextIndex();
}
private LocalFullTextIndex createFullTextIndex()
{
Class indexClass = getFullTextIndexClass();
if (indexClass == null)
{
return null;
}
try
{
return (LocalFullTextIndex)indexClass.newInstance();
}
catch (InstantiationException e)
{
throw new RuntimeException(e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
private Class<LocalFullTextIndex> getFullTextIndexClass()
{
try
{
/*
* AppScale - added cast below
*/
return (Class<LocalFullTextIndex>)Class.forName("com.google.appengine.api.datastore.dev.LuceneFullTextIndex");
}
catch (ClassNotFoundException e)
{
return null;
}
catch (NoClassDefFoundError e)
{
}
return null;
}
public Map<String, LocalDatastoreService.Extent> getExtents()
{
return this.extents;
}
public synchronized EntityGroup getGroup( OnestoreEntity.Path path )
{
Map map = getGroups();
EntityGroup group = (EntityGroup)map.get(path);
if (group == null)
{
group = new EntityGroup(path);
map.put(path, group);
}
return group;
}
private synchronized void groom()
{
for (OnestoreEntity.Path path : new HashSet<OnestoreEntity.Path>(getGroupsWithUnappliedJobs()))
{
EntityGroup eg = getGroup(path);
eg.maybeRollForwardUnappliedJobs();
}
}
public synchronized LocalDatastoreService.LiveQuery getQuery( long cursor )
{
return (LocalDatastoreService.LiveQuery)LocalDatastoreService.safeGetFromExpiringMap(getQueries(), cursor, "query has expired or is invalid. Please restart it with the last cursor to read more results.");
}
public synchronized void addQuery( long cursor, LocalDatastoreService.LiveQuery query )
{
getQueries().put(Long.valueOf(cursor), query);
}
private synchronized LocalDatastoreService.LiveQuery removeQuery( long cursor )
{
LocalDatastoreService.LiveQuery query = getQuery(cursor);
this.queries.remove(Long.valueOf(cursor));
return query;
}
private synchronized Map<Long, LocalDatastoreService.LiveQuery> getQueries()
{
if (this.queries == null)
{
this.queries = new HashMap();
}
return this.queries;
}
public synchronized LocalDatastoreService.LiveTxn getTxn( long handle )
{
return (LocalDatastoreService.LiveTxn)LocalDatastoreService.safeGetFromExpiringMap(getTxns(), handle, "transaction has expired or is invalid");
}
public LocalFullTextIndex getFullTextIndex()
{
return this.fullTextIndex;
}
public synchronized void addTxn( long handle, LocalDatastoreService.LiveTxn txn )
{
getTxns().put(Long.valueOf(handle), txn);
}
private synchronized LocalDatastoreService.LiveTxn removeTxn( long handle )
{
LocalDatastoreService.LiveTxn txn = getTxn(handle);
txn.close();
this.txns.remove(Long.valueOf(handle));
return txn;
}
private synchronized Map<Long, LocalDatastoreService.LiveTxn> getTxns()
{
if (this.txns == null)
{
this.txns = new HashMap();
}
return this.txns;
}
private synchronized Map<OnestoreEntity.Path, EntityGroup> getGroups()
{
if (this.groups == null)
{
this.groups = new LinkedHashMap();
}
return this.groups;
}
private synchronized Set<OnestoreEntity.Path> getGroupsWithUnappliedJobs()
{
if (this.groupsWithUnappliedJobs == null)
{
this.groupsWithUnappliedJobs = new LinkedHashSet();
}
return this.groupsWithUnappliedJobs;
}
class EntityGroup
{
private final OnestoreEntity.Path path;
private final AtomicLong version = new AtomicLong();
private final WeakHashMap<LocalDatastoreService.LiveTxn, LocalDatastoreService.Profile> snapshots = new WeakHashMap();
private final LinkedList<LocalDatastoreJob> unappliedJobs = new LinkedList();
private EntityGroup( OnestoreEntity.Path path )
{
this.path = path;
}
public long getVersion()
{
return this.version.get();
}
public void incrementVersion()
{
long oldVersion = this.version.getAndIncrement();
LocalDatastoreService.Profile snapshot = null;
for (LocalDatastoreService.LiveTxn txn : this.snapshots.keySet())
if (txn.trackEntityGroup(this).getEntityGroupVersion().longValue() == oldVersion)
{
if (snapshot == null)
{
snapshot = takeSnapshot();
}
this.snapshots.put(txn, snapshot);
}
}
public OnestoreEntity.EntityProto get( LocalDatastoreService.LiveTxn liveTxn, OnestoreEntity.Reference key, boolean eventualConsistency )
{
if (!eventualConsistency)
{
rollForwardUnappliedJobs();
}
LocalDatastoreService.Profile profile = getSnapshot(liveTxn);
Map extents = profile.getExtents();
LocalDatastoreService.Extent extent = (LocalDatastoreService.Extent)extents.get(Utils.getKind(key));
if (extent != null)
{
Map entities = extent.getEntities();
return (OnestoreEntity.EntityProto)entities.get(key);
}
return null;
}
public LocalDatastoreService.EntityGroupTracker addTransaction( LocalDatastoreService.LiveTxn txn )
{
LocalDatastoreService.EntityGroupTracker tracker = txn.trackEntityGroup(this);
if (!this.snapshots.containsKey(txn))
{
this.snapshots.put(txn, null);
}
return tracker;
}
public void removeTransaction( LocalDatastoreService.LiveTxn txn )
{
this.snapshots.remove(txn);
}
private LocalDatastoreService.Profile getSnapshot( LocalDatastoreService.LiveTxn txn )
{
if (txn == null)
{
return LocalDatastoreService.Profile.this;
}
LocalDatastoreService.Profile snapshot = (LocalDatastoreService.Profile)this.snapshots.get(txn);
if (snapshot == null)
{
return LocalDatastoreService.Profile.this;
}
return snapshot;
}
private LocalDatastoreService.Profile takeSnapshot()
{
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(LocalDatastoreService.Profile.this);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (LocalDatastoreService.Profile)ois.readObject();
}
catch (IOException ex)
{
throw new RuntimeException("Unable to take transaction snapshot.", ex);
}
catch (ClassNotFoundException ex)
{
throw new RuntimeException("Unable to take transaction snapshot.", ex);
}
}
public String toString()
{
return this.path.toString();
}
public DatastorePb.Cost addJob( LocalDatastoreJob job )
{
this.unappliedJobs.addLast(job);
LocalDatastoreService.Profile.this.getGroupsWithUnappliedJobs().add(this.path);
return maybeRollForwardUnappliedJobs();
}
public void rollForwardUnappliedJobs()
{
if (!this.unappliedJobs.isEmpty())
{
for (LocalDatastoreJob applyJob : this.unappliedJobs)
{
applyJob.apply();
}
this.unappliedJobs.clear();
LocalDatastoreService.Profile.this.getGroupsWithUnappliedJobs().remove(this.path);
LocalDatastoreService.logger.fine("Rolled forward unapplied jobs for " + this.path);
}
}
public DatastorePb.Cost maybeRollForwardUnappliedJobs()
{
int jobsAtStart = this.unappliedJobs.size();
LocalDatastoreService.logger.fine(String.format("Maybe rolling forward %d unapplied jobs for %s.", new Object[] { Integer.valueOf(jobsAtStart), this.path }));
int applied = 0;
DatastorePb.Cost totalCost = new DatastorePb.Cost();
for (Iterator iter = this.unappliedJobs.iterator(); iter.hasNext();)
{
LocalDatastoreJob.TryApplyResult result = ((LocalDatastoreJob)iter.next()).tryApply();
LocalDatastoreService.addTo(totalCost, result.cost);
if (!result.applied) break;
iter.remove();
applied++;
}
if (this.unappliedJobs.isEmpty())
{
LocalDatastoreService.Profile.this.getGroupsWithUnappliedJobs().remove(this.path);
}
LocalDatastoreService.logger.fine(String.format("Rolled forward %d of %d jobs for %s", new Object[] { Integer.valueOf(applied), Integer.valueOf(jobsAtStart), this.path }));
return totalCost;
}
public Key pathAsKey()
{
OnestoreEntity.Reference entityGroupRef = new OnestoreEntity.Reference();
entityGroupRef.setPath(this.path);
return LocalCompositeIndexManager.KeyTranslator.createFromPb(entityGroupRef);
}
}
}
}
| true | true | public DatastorePb.QueryResult runQuery( LocalRpcService.Status status, DatastorePb.Query query )
{
final LocalCompositeIndexManager.ValidatedQuery validatedQuery = new LocalCompositeIndexManager.ValidatedQuery(query);
query = validatedQuery.getQuery();
String app = query.getApp();
Profile profile = getOrCreateProfile(app);
synchronized (profile)
{
if ((query.hasTransaction()) || (query.hasAncestor()))
{
OnestoreEntity.Path groupPath = getGroup(query.getAncestor());
LocalDatastoreService.Profile.EntityGroup eg = profile.getGroup(groupPath);
if (query.hasTransaction())
{
if (!app.equals(query.getTransaction().getApp()))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.INTERNAL_ERROR, "Can't query app " + app + "in a transaction on app " + query.getTransaction().getApp());
}
LiveTxn liveTxn = profile.getTxn(query.getTransaction().getHandle());
eg.addTransaction(liveTxn);
}
if ((query.hasAncestor()) && ((query.hasTransaction()) || (!query.hasFailoverMs())))
{
eg.rollForwardUnappliedJobs();
}
}
LocalFullTextIndex fullTextIndex = profile.getFullTextIndex();
if ((query.hasSearchQuery()) && (fullTextIndex == null))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "full-text search unsupported");
}
/*
* AppScale line replacement to #end
*/
DatastorePb.QueryResult queryResult = new DatastorePb.QueryResult();
proxy.doPost(app, "RunQuery", query, queryResult);
List<EntityProto> queryEntities = new ArrayList<EntityProto>(queryResult.results());
/* #end */
if (queryEntities == null)
{
Map extents = profile.getExtents();
Extent extent = (Extent)extents.get(query.getKind());
if (!query.hasSearchQuery())
{
if (extent != null)
{
queryEntities = new ArrayList(extent.getEntities().values());
}
else if (!query.hasKind())
{
queryEntities = profile.getAllEntities();
if (query.orderSize() == 0)
{
query.addOrder(new DatastorePb.Query.Order().setDirection(DatastorePb.Query.Order.Direction.ASCENDING).setProperty("__key__"));
}
}
}
else
{
/*
* AppScale - Added type to keys below
*/
List<OnestoreEntity.Reference> keys = fullTextIndex.search(query.getKind(), query.getSearchQuery());
List entities = new ArrayList(keys.size());
for (OnestoreEntity.Reference key : keys)
{
entities.add(extent.getEntities().get(key));
}
queryEntities = entities;
}
}
profile.groom();
if (queryEntities == null)
{
queryEntities = Collections.emptyList();
}
List predicates = new ArrayList();
if (query.hasAncestor())
{
final List ancestorPath = query.getAncestor().getPath().elements();
predicates.add(new Predicate()
{
public boolean apply( Object entity )
{
/*
* AppScale - Added type to entity below
*/
List path = ((OnestoreEntity.EntityProto)entity).getKey().getPath().elements();
return (path.size() >= ancestorPath.size()) && (path.subList(0, ancestorPath.size()).equals(ancestorPath));
}
});
}
final boolean hasNamespace = query.hasNameSpace();
final String namespace = query.getNameSpace();
predicates.add(new Predicate()
{
/*
* Added type to entity below
*/
public boolean apply( Object entity )
{
OnestoreEntity.Reference ref = ((OnestoreEntity.EntityProto)entity).getKey();
if (hasNamespace)
{
if ((!ref.hasNameSpace()) || (!namespace.equals(ref.getNameSpace())))
{
return false;
}
}
else if (ref.hasNameSpace())
{
return false;
}
return true;
}
});
final EntityProtoComparators.EntityProtoComparator entityComparator = new EntityProtoComparators.EntityProtoComparator(validatedQuery.getQuery().orders(), validatedQuery.getQuery().filters());
predicates.add(new Predicate()
{
public boolean apply( Object entity )
{
/*
* AppScale - Added cast to entity below
*/
return entityComparator.matches((EntityProto)entity);
}
});
Predicate queryPredicate = Predicates.not(Predicates.and(predicates));
Iterators.removeIf(queryEntities.iterator(), queryPredicate);
if (query.propertyNameSize() > 0)
{
queryEntities = createIndexOnlyQueryResults(queryEntities, entityComparator);
}
Collections.sort(queryEntities, entityComparator);
LiveQuery liveQuery = new LiveQuery(queryEntities, query, entityComparator, this.clock);
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
LocalCompositeIndexManager.getInstance().processQuery(validatedQuery.getQuery());
return null;
}
});
/*
* AppScale - removed duplicate count instantiations
*/
int count;
if (query.hasCount())
{
count = query.getCount();
}
else
{
if (query.hasLimit())
count = query.getLimit();
else
{
count = 20;
}
}
DatastorePb.QueryResult result = nextImpl(liveQuery, query.getOffset(), count, query.isCompile());
if (query.isCompile())
{
result.setCompiledQuery(liveQuery.compileQuery());
}
if (result.isMoreResults())
{
long cursor = this.queryId.getAndIncrement();
profile.addQuery(cursor, liveQuery);
result.getMutableCursor().setApp(query.getApp()).setCursor(cursor);
}
for (OnestoreEntity.Index index : LocalCompositeIndexManager.getInstance().queryIndexList(query))
{
result.addIndex(wrapIndexInCompositeIndex(app, index));
}
return result;
}
}
| public DatastorePb.QueryResult runQuery( LocalRpcService.Status status, DatastorePb.Query query )
{
final LocalCompositeIndexManager.ValidatedQuery validatedQuery = new LocalCompositeIndexManager.ValidatedQuery(query);
query = validatedQuery.getQuery();
String app = query.getApp();
Profile profile = getOrCreateProfile(app);
synchronized (profile)
{
if ((query.hasTransaction()) || (query.hasAncestor()))
{
OnestoreEntity.Path groupPath = getGroup(query.getAncestor());
LocalDatastoreService.Profile.EntityGroup eg = profile.getGroup(groupPath);
if (query.hasTransaction())
{
if (!app.equals(query.getTransaction().getApp()))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.INTERNAL_ERROR, "Can't query app " + app + "in a transaction on app " + query.getTransaction().getApp());
}
LiveTxn liveTxn = profile.getTxn(query.getTransaction().getHandle());
eg.addTransaction(liveTxn);
}
if ((query.hasAncestor()) && ((query.hasTransaction()) || (!query.hasFailoverMs())))
{
eg.rollForwardUnappliedJobs();
}
}
LocalFullTextIndex fullTextIndex = profile.getFullTextIndex();
if ((query.hasSearchQuery()) && (fullTextIndex == null))
{
throw Utils.newError(DatastorePb.Error.ErrorCode.BAD_REQUEST, "full-text search unsupported");
}
/*
* AppScale line replacement to #end
*/
DatastorePb.QueryResult queryResult = new DatastorePb.QueryResult();
proxy.doPost(app, "RunQuery", query, queryResult);
List<EntityProto> queryEntities = new ArrayList<EntityProto>(queryResult.results());
/* #end */
if (queryEntities == null)
{
Map extents = profile.getExtents();
Extent extent = (Extent)extents.get(query.getKind());
if (!query.hasSearchQuery())
{
if (extent != null)
{
queryEntities = new ArrayList(extent.getEntities().values());
}
else if (!query.hasKind())
{
queryEntities = profile.getAllEntities();
if (query.orderSize() == 0)
{
query.addOrder(new DatastorePb.Query.Order().setDirection(DatastorePb.Query.Order.Direction.ASCENDING).setProperty("__key__"));
}
}
}
else
{
/*
* AppScale - Added type to keys below
*/
List<OnestoreEntity.Reference> keys = fullTextIndex.search(query.getKind(), query.getSearchQuery());
List entities = new ArrayList(keys.size());
for (OnestoreEntity.Reference key : keys)
{
entities.add(extent.getEntities().get(key));
}
queryEntities = entities;
}
}
profile.groom();
if (queryEntities == null)
{
queryEntities = Collections.emptyList();
}
List predicates = new ArrayList();
if (query.hasAncestor())
{
final List ancestorPath = query.getAncestor().getPath().elements();
predicates.add(new Predicate()
{
public boolean apply( Object entity )
{
/*
* AppScale - Added type to entity below
*/
List path = ((OnestoreEntity.EntityProto)entity).getKey().getPath().elements();
return (path.size() >= ancestorPath.size()) && (path.subList(0, ancestorPath.size()).equals(ancestorPath));
}
});
}
final boolean hasNamespace = query.hasNameSpace();
final String namespace = query.getNameSpace();
predicates.add(new Predicate()
{
/*
* Added type to entity below
*/
public boolean apply( Object entity )
{
OnestoreEntity.Reference ref = ((OnestoreEntity.EntityProto)entity).getKey();
if (hasNamespace)
{
if ((!ref.hasNameSpace()) || (!namespace.equals(ref.getNameSpace())))
{
return false;
}
}
else if (ref.hasNameSpace())
{
return false;
}
return true;
}
});
final EntityProtoComparators.EntityProtoComparator entityComparator = new EntityProtoComparators.EntityProtoComparator(validatedQuery.getQuery().orders(), validatedQuery.getQuery().filters());
predicates.add(new Predicate()
{
public boolean apply( Object entity )
{
/*
* AppScale - Added cast to entity below
*/
return entityComparator.matches((EntityProto)entity);
}
});
Predicate queryPredicate = Predicates.not(Predicates.and(predicates));
Iterators.removeIf(queryEntities.iterator(), queryPredicate);
if (query.propertyNameSize() > 0)
{
queryEntities = createIndexOnlyQueryResults(queryEntities, entityComparator);
}
Collections.sort(queryEntities, entityComparator);
LiveQuery liveQuery = new LiveQuery(queryEntities, query, entityComparator, this.clock);
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
LocalCompositeIndexManager.getInstance().processQuery(validatedQuery.getQuery());
return null;
}
});
/*
* AppScale - removed duplicate count instantiations
*/
int count;
if (query.hasCount())
{
count = query.getCount();
}
else
{
if (query.hasLimit())
count = query.getLimit();
else
{
count = 20;
}
}
DatastorePb.QueryResult result = nextImpl(liveQuery, query.getOffset(), count, query.isCompile());
if (query.isCompile())
{
result.setCompiledQuery(liveQuery.compileQuery());
}
if (result.isMoreResults())
{
long cursor = this.queryId.getAndIncrement();
profile.addQuery(cursor, liveQuery);
result.getMutableCursor().setApp(query.getApp()).setCursor(cursor);
}
for (OnestoreEntity.Index index : LocalCompositeIndexManager.getInstance().queryIndexList(query))
{
result.addIndex(wrapIndexInCompositeIndex(app, index));
}
/*
* AppScale - adding skipped results to the result, otherwise query counts are wrong
*/
result.setSkippedResults(queryResult.getSkippedResults());
return result;
}
}
|
diff --git a/src/main/java/com/khs/sherpa/servlet/SherpaServlet.java b/src/main/java/com/khs/sherpa/servlet/SherpaServlet.java
index 1975d55..84ca76e 100644
--- a/src/main/java/com/khs/sherpa/servlet/SherpaServlet.java
+++ b/src/main/java/com/khs/sherpa/servlet/SherpaServlet.java
@@ -1,113 +1,116 @@
package com.khs.sherpa.servlet;
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static com.khs.sherpa.util.Util.msg;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.khs.sherpa.context.GenericApplicationContext;
import com.khs.sherpa.exception.SherpaInvalidUsernamePassword;
import com.khs.sherpa.exception.SherpaRuntimeException;
import com.khs.sherpa.servlet.request.DefaultSherpaRequest;
public class SherpaServlet extends HttpServlet {
private static final long serialVersionUID = 4345668988238038540L;
private static final Logger LOGGER = LoggerFactory.getLogger(SherpaServlet.class);
@Override
public void init() throws ServletException {
super.init();
}
private void doService(HttpServletRequest request, HttpServletResponse response) throws RuntimeException, IOException {
try {
DefaultSherpaRequest sherpaRequest = new DefaultSherpaRequest();
sherpaRequest.setApplicationContext(GenericApplicationContext.getApplicationContext(getServletContext()));
sherpaRequest.doService(request, response);
} catch (SherpaInvalidUsernamePassword e) {
- response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Username or Password!");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ response.setContentType("application/json");
LOGGER.info(msg("INFO "+e.getMessage() ));
} catch (SherpaRuntimeException e) {
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Sherpa Error "+e.getMessage());
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.setContentType("application/json");
LOGGER.error(msg("ERROR "+e.getMessage() ));
} catch (Exception e) {
- throw new SherpaRuntimeException(e);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.setContentType("application/json");
} finally {
// do nothing right now
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doService(request, response);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doService(request, response);
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doService(request, response);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doService(request, response);
}
@Override
protected long getLastModified(HttpServletRequest req) {
return super.getLastModified(req);
}
@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doHead(req, resp);
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doOptions(req, resp);
}
@Override
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doTrace(req, resp);
}
}
| false | true | private void doService(HttpServletRequest request, HttpServletResponse response) throws RuntimeException, IOException {
try {
DefaultSherpaRequest sherpaRequest = new DefaultSherpaRequest();
sherpaRequest.setApplicationContext(GenericApplicationContext.getApplicationContext(getServletContext()));
sherpaRequest.doService(request, response);
} catch (SherpaInvalidUsernamePassword e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Username or Password!");
LOGGER.info(msg("INFO "+e.getMessage() ));
} catch (SherpaRuntimeException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Sherpa Error "+e.getMessage());
LOGGER.error(msg("ERROR "+e.getMessage() ));
} catch (Exception e) {
throw new SherpaRuntimeException(e);
} finally {
// do nothing right now
}
}
| private void doService(HttpServletRequest request, HttpServletResponse response) throws RuntimeException, IOException {
try {
DefaultSherpaRequest sherpaRequest = new DefaultSherpaRequest();
sherpaRequest.setApplicationContext(GenericApplicationContext.getApplicationContext(getServletContext()));
sherpaRequest.doService(request, response);
} catch (SherpaInvalidUsernamePassword e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
LOGGER.info(msg("INFO "+e.getMessage() ));
} catch (SherpaRuntimeException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("application/json");
LOGGER.error(msg("ERROR "+e.getMessage() ));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("application/json");
} finally {
// do nothing right now
}
}
|
diff --git a/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CompositeRefactoringsQuickAssistProcessor.java b/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CompositeRefactoringsQuickAssistProcessor.java
index f233073..ecbe40e 100644
--- a/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CompositeRefactoringsQuickAssistProcessor.java
+++ b/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CompositeRefactoringsQuickAssistProcessor.java
@@ -1,166 +1,167 @@
/**
* Copyright (c) 2008-2012 University of Illinois at Urbana-Champaign.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package edu.illinois.compositerefactorings.extractsuperclass;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.ui.text.java.IQuickAssistProcessor;
import org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal;
import org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal;
import org.eclipse.jdt.ui.text.java.correction.ICommandAccess;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.swt.graphics.Image;
import org.eclipse.text.edits.InsertEdit;
@SuppressWarnings("restriction")
public class CompositeRefactoringsQuickAssistProcessor implements IQuickAssistProcessor {
@Override
public boolean hasAssists(IInvocationContext context) throws CoreException {
ASTNode coveringNode= context.getCoveringNode();
if (coveringNode != null) {
return getCreateNewSuperclassProposal(context, coveringNode, false, null) ||
getMoveToImmediateSuperclassProposal(context, coveringNode, false, null) ||
getMoveTypeToNewFileProposal(context, coveringNode, false, null);
}
return false;
}
@Override
public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
ASTNode coveringNode= context.getCoveringNode();
if (coveringNode != null) {
ArrayList<ICommandAccess> resultingCollections= new ArrayList<ICommandAccess>();
getCreateNewSuperclassProposal(context, coveringNode, false, resultingCollections);
getMoveToImmediateSuperclassProposal(context, coveringNode, false, resultingCollections);
getMoveTypeToNewFileProposal(context, coveringNode, false, resultingCollections);
return resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
}
return null;
}
private static boolean getCreateNewSuperclassProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
if (!(coveringNode instanceof TypeDeclaration)) {
return false;
}
if (proposals == null) {
return true;
}
final ICompilationUnit cu= context.getCompilationUnit();
ASTNode coveringTypeDeclarationASTNode= context.getCoveringNode();
ASTNode node= coveringTypeDeclarationASTNode.getParent();
AST ast= node.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
String label= "Create new superclass in file";
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image);
TypeDeclaration newSuperclass= ast.newTypeDeclaration();
newSuperclass.setName(ast.newSimpleName("NewSuperclass"));
ListRewrite listRewrite= rewrite.getListRewrite(node, CompilationUnit.TYPES_PROPERTY);
listRewrite.insertLast(newSuperclass, null);
rewrite.set(newSuperclass, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, coveringTypeDeclarationASTNode.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY), null);
rewrite.set(coveringTypeDeclarationASTNode, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperclass.getName(), null);
proposals.add(proposal);
return true;
}
private static boolean getMoveToImmediateSuperclassProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals)
throws CoreException {
if (!(coveringNode instanceof SimpleName) || !(coveringNode.getParent() instanceof MethodDeclaration)) {
return false;
}
MethodDeclaration methodDeclaration= (MethodDeclaration)coveringNode.getParent();
if (methodDeclaration.getName() != coveringNode || methodDeclaration.resolveBinding() == null) {
return false;
}
if (proposals == null) {
return true;
}
final ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit cuASTNode= (CompilationUnit)methodDeclaration.getRoot();
ASTNode typeDeclarationASTNode= methodDeclaration.getParent();
ASTRewrite rewrite= ASTRewrite.create(typeDeclarationASTNode.getAST());
String label= "Move to immediate superclass";
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image);
ASTNode placeHolderForMethodDeclaration= rewrite.createMoveTarget(methodDeclaration);
SimpleType superTypeASTNode= (SimpleType)typeDeclarationASTNode.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY);
ITypeBinding superTypeBinding= superTypeASTNode.resolveBinding();
// See http://wiki.eclipse.org/JDT/FAQ#From_an_IBinding_to_its_declaring_ASTNode
ASTNode SuperTypeDeclarationASTNode= cuASTNode.findDeclaringNode(superTypeBinding);
ListRewrite superTypeMembersListRewrite= rewrite.getListRewrite(SuperTypeDeclarationASTNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
superTypeMembersListRewrite.insertFirst(placeHolderForMethodDeclaration, null);
rewrite.remove(methodDeclaration, null);
proposals.add(proposal);
return true;
}
private static boolean getMoveTypeToNewFileProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
if (!(coveringNode instanceof TypeDeclaration)) {
return false;
}
if (proposals == null) {
return true;
}
final ICompilationUnit cu= context.getCompilationUnit();
ITypeBinding typeBinding= ((TypeDeclaration)coveringNode).resolveBinding();
IType type= (IType)typeBinding.getJavaElement();
final MoveInnerToTopRefactoring moveInnerToTopRefactoring= new MoveInnerToTopRefactoring(type, null);
if (moveInnerToTopRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
- String label= "Move selected type to new file";
+ String label= String.format("Move type %s to a new file", type.getElementName());
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
int relevance= problemsAtLocation ? 1 : 4;
RefactoringStatus status= moveInnerToTopRefactoring.checkFinalConditions(new NullProgressMonitor());
Change change= null;
if (status.hasFatalError()) {
change= new TextFileChange("fatal error", (IFile)cu.getResource()); //$NON-NLS-1$
((TextFileChange)change).setEdit(new InsertEdit(0, "")); //$NON-NLS-1$
+ return false;
} else {
change= moveInnerToTopRefactoring.createChange(new NullProgressMonitor());
}
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(label, change, relevance, image);
proposals.add(proposal);
}
return true;
}
}
| false | true | private static boolean getMoveTypeToNewFileProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
if (!(coveringNode instanceof TypeDeclaration)) {
return false;
}
if (proposals == null) {
return true;
}
final ICompilationUnit cu= context.getCompilationUnit();
ITypeBinding typeBinding= ((TypeDeclaration)coveringNode).resolveBinding();
IType type= (IType)typeBinding.getJavaElement();
final MoveInnerToTopRefactoring moveInnerToTopRefactoring= new MoveInnerToTopRefactoring(type, null);
if (moveInnerToTopRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
String label= "Move selected type to new file";
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
int relevance= problemsAtLocation ? 1 : 4;
RefactoringStatus status= moveInnerToTopRefactoring.checkFinalConditions(new NullProgressMonitor());
Change change= null;
if (status.hasFatalError()) {
change= new TextFileChange("fatal error", (IFile)cu.getResource()); //$NON-NLS-1$
((TextFileChange)change).setEdit(new InsertEdit(0, "")); //$NON-NLS-1$
} else {
change= moveInnerToTopRefactoring.createChange(new NullProgressMonitor());
}
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(label, change, relevance, image);
proposals.add(proposal);
}
return true;
}
| private static boolean getMoveTypeToNewFileProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
if (!(coveringNode instanceof TypeDeclaration)) {
return false;
}
if (proposals == null) {
return true;
}
final ICompilationUnit cu= context.getCompilationUnit();
ITypeBinding typeBinding= ((TypeDeclaration)coveringNode).resolveBinding();
IType type= (IType)typeBinding.getJavaElement();
final MoveInnerToTopRefactoring moveInnerToTopRefactoring= new MoveInnerToTopRefactoring(type, null);
if (moveInnerToTopRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
String label= String.format("Move type %s to a new file", type.getElementName());
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
int relevance= problemsAtLocation ? 1 : 4;
RefactoringStatus status= moveInnerToTopRefactoring.checkFinalConditions(new NullProgressMonitor());
Change change= null;
if (status.hasFatalError()) {
change= new TextFileChange("fatal error", (IFile)cu.getResource()); //$NON-NLS-1$
((TextFileChange)change).setEdit(new InsertEdit(0, "")); //$NON-NLS-1$
return false;
} else {
change= moveInnerToTopRefactoring.createChange(new NullProgressMonitor());
}
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(label, change, relevance, image);
proposals.add(proposal);
}
return true;
}
|
diff --git a/src/edu/common/dynamicextensions/domain/FloatAttributeTypeInformation.java b/src/edu/common/dynamicextensions/domain/FloatAttributeTypeInformation.java
index 947814aba..69fc86732 100644
--- a/src/edu/common/dynamicextensions/domain/FloatAttributeTypeInformation.java
+++ b/src/edu/common/dynamicextensions/domain/FloatAttributeTypeInformation.java
@@ -1,61 +1,71 @@
package edu.common.dynamicextensions.domain;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import edu.common.dynamicextensions.domaininterface.FloatTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.FloatValueInterface;
import edu.common.dynamicextensions.domaininterface.PermissibleValueInterface;
import edu.common.dynamicextensions.entitymanager.EntityManagerConstantsInterface;
/**
* This Class represent the Floating value Attribute of the Entity.
* @hibernate.joined-subclass table="DYEXTN_FLOAT_TYPE_INFO"
* @hibernate.joined-subclass-key column="IDENTIFIER"
* @author sujay_narkar
*/
public class FloatAttributeTypeInformation extends NumericAttributeTypeInformation
implements
FloatTypeInformationInterface
{
/**
* @see edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface#getDataType()
*/
public String getDataType()
{
return EntityManagerConstantsInterface.FLOAT_ATTRIBUTE_TYPE;
}
/**
*
*/
public PermissibleValueInterface getPermissibleValueForString(String value)
{
DomainObjectFactory factory = DomainObjectFactory.getInstance();
FloatValueInterface floatValue = factory.createFloatValue();
floatValue.setValue(new Float(value));
return floatValue;
}
/**
*
*/
public String getFormattedValue(Double value)
{
String formattedValue = "";
if (value != null)
{
- DecimalFormat formatDecimal = (DecimalFormat) NumberFormat
- .getNumberInstance();
- formatDecimal.setParseBigDecimal(true);
- formatDecimal.setGroupingUsed(false);
- formatDecimal.setMaximumFractionDigits(this.decimalPlaces
- .intValue());
- formattedValue = formatDecimal.format(Float.valueOf(value
- .floatValue()));
+ if (this.decimalPlaces.intValue() > 0)
+ {
+ DecimalFormat formatDecimal = (DecimalFormat) NumberFormat
+ .getNumberInstance();
+ formatDecimal.setParseBigDecimal(true);
+ formatDecimal.setGroupingUsed(false);
+ formatDecimal.setMaximumFractionDigits(this.decimalPlaces
+ .intValue());
+ formattedValue = formatDecimal.format(Float.valueOf(value
+ .floatValue()));
+ }
+ else
+ {
+ PermissibleValueInterface permissibleValueInterface = getPermissibleValueForString(Float
+ .valueOf(value.floatValue()).toString());
+ formattedValue = permissibleValueInterface.getValueAsObject()
+ .toString();
+ }
}
return formattedValue;
}
}
| true | true | public String getFormattedValue(Double value)
{
String formattedValue = "";
if (value != null)
{
DecimalFormat formatDecimal = (DecimalFormat) NumberFormat
.getNumberInstance();
formatDecimal.setParseBigDecimal(true);
formatDecimal.setGroupingUsed(false);
formatDecimal.setMaximumFractionDigits(this.decimalPlaces
.intValue());
formattedValue = formatDecimal.format(Float.valueOf(value
.floatValue()));
}
return formattedValue;
}
| public String getFormattedValue(Double value)
{
String formattedValue = "";
if (value != null)
{
if (this.decimalPlaces.intValue() > 0)
{
DecimalFormat formatDecimal = (DecimalFormat) NumberFormat
.getNumberInstance();
formatDecimal.setParseBigDecimal(true);
formatDecimal.setGroupingUsed(false);
formatDecimal.setMaximumFractionDigits(this.decimalPlaces
.intValue());
formattedValue = formatDecimal.format(Float.valueOf(value
.floatValue()));
}
else
{
PermissibleValueInterface permissibleValueInterface = getPermissibleValueForString(Float
.valueOf(value.floatValue()).toString());
formattedValue = permissibleValueInterface.getValueAsObject()
.toString();
}
}
return formattedValue;
}
|
diff --git a/src/org/pentaho/pms/schema/security/SecurityService.java b/src/org/pentaho/pms/schema/security/SecurityService.java
index 67314e7e..f5f6634e 100644
--- a/src/org/pentaho/pms/schema/security/SecurityService.java
+++ b/src/org/pentaho/pms/schema/security/SecurityService.java
@@ -1,518 +1,518 @@
/*
* Copyright 2006 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the Mozilla Public License, Version 1.1, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
* BI Platform. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.pms.schema.security;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.pentaho.di.core.changed.ChangedFlag;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.pms.core.exception.PentahoMetadataException;
import org.pentaho.pms.messages.Messages;
import org.pentaho.pms.util.Const;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class SecurityService extends ChangedFlag implements Cloneable {
public static final int SERVICE_TYPE_ALL = 0;
public static final int SERVICE_TYPE_USERS = 1;
public static final int SERVICE_TYPE_ROLES = 2;
public static final String[] serviceTypeCodes = new String[] { "all", "users", "roles" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
public static final String[] serviceTypeDescriptions = new String[] { Messages.getString("SecurityService.USER_ALL"), //$NON-NLS-1$
Messages.getString("SecurityService.USER_USERS"), //$NON-NLS-1$
Messages.getString("SecurityService.USER_ROLES") }; //$NON-NLS-1$
public static final String ACTION = "action"; //$NON-NLS-1$
public static final String USERNAME = "userid"; //$NON-NLS-1$
public static final String PASSWORD = "password"; //$NON-NLS-1$
private String serviceURL;
private String serviceName;
private String detailNameParameter;
private int detailServiceType;
private String username;
private String password;
private String proxyHostname;
private String proxyPort;
private String nonProxyHosts;
private String filename;
LogWriter log = null;
public SecurityService() {
try {
LogWriter log = LogWriter.getInstance(Const.META_EDITOR_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC);
} catch (KettleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object clone() {
try {
return super.clone();
} catch (Exception e) {
return null;
}
}
public String toString() {
if (hasService())
return serviceName;
return "SecurityService"; //$NON-NLS-1$
}
/**
* @return the detailNameParameter
*/
public String getDetailNameParameter() {
return detailNameParameter;
}
/**
* @param detailNameParameter the detailNameParameter to set
*/
public void setDetailNameParameter(String detailServiceName) {
this.detailNameParameter = detailServiceName;
}
/**
* @return the detailServiceType
*/
public int getDetailServiceType() {
return detailServiceType;
}
/**
* @param detailServiceType the detailServiceType to set
*/
public void setDetailServiceType(int detailServiceType) {
this.detailServiceType = detailServiceType;
}
/**
* @return the serviceName
*/
public String getServiceName() {
return serviceName;
}
/**
* @param serviceName the serviceName to set
*/
public void setServiceName(String name) {
this.serviceName = name;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the serviceURL
*/
public String getServiceURL() {
return serviceURL;
}
/**
* @param serviceURL the serviceURL to set
*/
public void setServiceURL(String serviceURL) {
this.serviceURL = serviceURL;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
public String getServiceTypeCode() {
return serviceTypeCodes[detailServiceType];
}
public String getServiceTypeDesc() {
return serviceTypeDescriptions[detailServiceType];
}
/**
* @return the nonProxyHosts
*/
public String getNonProxyHosts() {
return nonProxyHosts;
}
/**
* @param nonProxyHosts the nonProxyHosts to set
*/
public void setNonProxyHosts(String nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts;
}
/**
* @return the proxyHostname
*/
public String getProxyHostname() {
return proxyHostname;
}
/**
* @param proxyHostname the proxyHostname to set
*/
public void setProxyHostname(String proxyHostname) {
this.proxyHostname = proxyHostname;
}
/**
* @return the proxyPort
*/
public String getProxyPort() {
return proxyPort;
}
/**
* @param proxyPort the proxyPort to set
*/
public void setProxyPort(String proxyPort) {
this.proxyPort = proxyPort;
}
public static final int getServiceType(String description) {
for (int i = 0; i < serviceTypeDescriptions.length; i++) {
if (serviceTypeDescriptions[i].equalsIgnoreCase(description))
return i;
}
for (int i = 0; i < serviceTypeCodes.length; i++) {
if (serviceTypeCodes[i].equalsIgnoreCase(description))
return i;
}
return SERVICE_TYPE_ALL;
}
public Node getContent() throws Exception {
if (hasService()) {
return getContentFromServer();
} else if (hasFile()) {
return getContentFromFile();
}
throw new Exception(Messages.getString("SecurityService.ERROR_0001_UNABLE_TO_GET_SECURITY_REFERENCE")); //$NON-NLS-1$
}
/**
* Contact the server and get back the content as XML
* @return the requested security reference information
* @throws Exception in case something goes awry
*/
public Node getContentFromServer() throws PentahoMetadataException {
LogWriter log = LogWriter.getInstance();
String urlToUse = getURL();
String result = null;
int status = -1;
URL tempURL;
try {
// verify the URL is syntactically correct; we will use these pieces later in this method
tempURL = new URL(urlToUse);
} catch (MalformedURLException e) {
String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
HttpClient client = new HttpClient();
log.logBasic(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$
// Assume we are using a proxy if proxyHostName is set?
// TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1)
if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) {
int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ?
client.getHostConfiguration().getPort(): Integer.parseInt(proxyPort);
//TODO: Where to set nonProxyHosts?
client.getHostConfiguration().setProxy(proxyHostname, port);
//TODO: Credentials for proxy will be added if demand shows for it (post v1)
// if (username != null && username.length() > 0) {
// client.getState().setProxyCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials(username, password != null ? password : new String()));
// }
}
// If server userid/password was supplied, use basic authentication to
// authenticate with the server.
if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) {
Credentials creds = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds);
client.getParams().setAuthenticationPreemptive(true);
}
// Get a stream for the specified URL
GetMethod getMethod = new GetMethod(urlToUse);
try {
status = client.executeMethod(getMethod);
if (status == HttpStatus.SC_OK) {
log.logDetailed(toString(), Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$
result = getMethod.getResponseBodyAsString();
log.logBasic(toString(), Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", Integer.toString(result.length()))); //$NON-NLS-1$
} else if (status == HttpStatus.SC_UNAUTHORIZED) {
String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$
log.logError(toString(), msg);
throw new PentahoMetadataException(msg);
}
} catch (HttpException e) {
String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
} catch (IOException e) {
String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", e.getMessage()); //$NON-NLS-1$
- log.logError(toString(), msg);
- log.logError(toString(), Const.getStackTracker(e));
+// log.logError(toString(), msg);
+// log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
if (result != null){
// Get the result back...
Document doc;
try {
doc = XMLHandler.loadXMLString(result);
} catch (KettleXMLException e) {
String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$
if (envelope != null) {
Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$
if (body != null) {
Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$
if (response != null) {
Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$
return content;
}
}
}
}
return null;
}
/**
* Read the specified security file and get back the content as XML
* @return the requested security reference information
* @throws Exception in case something goes awry
*/
public Node getContentFromFile() throws Exception {
try {
Document doc = XMLHandler.loadXMLFile(filename);
return XMLHandler.getSubNode(doc, "content"); //$NON-NLS-1$
} catch (KettleXMLException e) {
throw new Exception(Messages.getString("SecurityService.ERROR_0007_UNABLE_TO_GET_SECURITY_CONTENT", filename), e); //$NON-NLS-1$
}
}
public String getContentAsXMLString() throws Exception {
Node content = getContent();
if (content == null)
return null;
return content.getChildNodes().toString();
}
public String getURL() {
StringBuffer url = new StringBuffer();
url.append(serviceURL);
url.append("?").append(ACTION).append("=").append(serviceName); //$NON-NLS-1$ //$NON-NLS-2$
url.append("&").append(detailNameParameter).append("=").append(getServiceTypeCode()); //$NON-NLS-1$ //$NON-NLS-2$
return url.toString();
}
public boolean hasService() {
return !Const.isEmpty(serviceURL) && !Const.isEmpty(serviceName) && !Const.isEmpty(detailNameParameter);
}
public boolean hasFile() {
return !Const.isEmpty(filename);
}
/**
* @return the filename
*/
public String getFilename() {
return filename;
}
/**
* @param filename the filename to set
*/
public void setFilename(String filename) {
this.filename = filename;
}
public List<String> getUsers() {
List<String> users = new ArrayList<String>();
if (hasService() || hasFile()) {
try {
Node contentNode = getContent();
// Load the users
Node usersNode = XMLHandler.getSubNode(contentNode, "users"); //$NON-NLS-1$
int nrUsers = XMLHandler.countNodes(usersNode, "user"); //$NON-NLS-1$
for (int i = 0; i < nrUsers; i++) {
Node userNode = XMLHandler.getSubNodeByNr(usersNode, "user", i); //$NON-NLS-1$
String username = XMLHandler.getNodeValue(userNode);
if (username != null)
users.add(username);
}
} catch (PentahoMetadataException ex) {
log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), ex.getLocalizedMessage()); //$NON-NLS-1$
} catch (Exception e) {
log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), e.getLocalizedMessage()); //$NON-NLS-1$
}
}
return users;
}
public List<String> getRoles() {
List<String> roles = new ArrayList<String>();
if (hasService() || hasFile()) {
try {
Node contentNode = getContent();
// Load the roles
Node rolesNode = XMLHandler.getSubNode(contentNode, "roles"); //$NON-NLS-1$
int nrRoles = XMLHandler.countNodes(rolesNode, "role"); //$NON-NLS-1$
for (int i=0;i<nrRoles;i++)
{
Node roleNode = XMLHandler.getSubNodeByNr(rolesNode, "role", i); //$NON-NLS-1$
String rolename = XMLHandler.getNodeValue(roleNode);
if (rolename!=null) roles.add(rolename);
}
} catch (PentahoMetadataException ex) {
log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), ex.getLocalizedMessage()); //$NON-NLS-1$
} catch (Exception e) {
log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), e.getLocalizedMessage()); //$NON-NLS-1$
}
}
return roles;
}
public List<SecurityACL> getAcls() {
List<SecurityACL> acls = new ArrayList<SecurityACL>();
if (hasService() || hasFile()) {
try {
Node contentNode = getContent();
// Load the ACLs
Node aclsNode = XMLHandler.getSubNode(contentNode, "acls"); //$NON-NLS-1$
int nrAcls = XMLHandler.countNodes(aclsNode, "acl"); //$NON-NLS-1$
for (int i=0;i<nrAcls;i++)
{
Node aclNode = XMLHandler.getSubNodeByNr(aclsNode, "acl", i); //$NON-NLS-1$
SecurityACL acl = new SecurityACL(aclNode);
acls.add(acl);
}
Collections.sort(acls); // sort by acl mask, from low to high
} catch (PentahoMetadataException ex) {
log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), ex.getLocalizedMessage()); //$NON-NLS-1$
} catch (Exception e) {
log.logError(Messages.getString("SecurityReference.ERROR_0001_CANT_CREATE_REFERENCE_FROM_XML"), e.getLocalizedMessage()); //$NON-NLS-1$
}
}
return acls;
}
}
| true | true | public Node getContentFromServer() throws PentahoMetadataException {
LogWriter log = LogWriter.getInstance();
String urlToUse = getURL();
String result = null;
int status = -1;
URL tempURL;
try {
// verify the URL is syntactically correct; we will use these pieces later in this method
tempURL = new URL(urlToUse);
} catch (MalformedURLException e) {
String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
HttpClient client = new HttpClient();
log.logBasic(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$
// Assume we are using a proxy if proxyHostName is set?
// TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1)
if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) {
int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ?
client.getHostConfiguration().getPort(): Integer.parseInt(proxyPort);
//TODO: Where to set nonProxyHosts?
client.getHostConfiguration().setProxy(proxyHostname, port);
//TODO: Credentials for proxy will be added if demand shows for it (post v1)
// if (username != null && username.length() > 0) {
// client.getState().setProxyCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials(username, password != null ? password : new String()));
// }
}
// If server userid/password was supplied, use basic authentication to
// authenticate with the server.
if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) {
Credentials creds = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds);
client.getParams().setAuthenticationPreemptive(true);
}
// Get a stream for the specified URL
GetMethod getMethod = new GetMethod(urlToUse);
try {
status = client.executeMethod(getMethod);
if (status == HttpStatus.SC_OK) {
log.logDetailed(toString(), Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$
result = getMethod.getResponseBodyAsString();
log.logBasic(toString(), Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", Integer.toString(result.length()))); //$NON-NLS-1$
} else if (status == HttpStatus.SC_UNAUTHORIZED) {
String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$
log.logError(toString(), msg);
throw new PentahoMetadataException(msg);
}
} catch (HttpException e) {
String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
} catch (IOException e) {
String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
if (result != null){
// Get the result back...
Document doc;
try {
doc = XMLHandler.loadXMLString(result);
} catch (KettleXMLException e) {
String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$
if (envelope != null) {
Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$
if (body != null) {
Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$
if (response != null) {
Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$
return content;
}
}
}
}
return null;
}
| public Node getContentFromServer() throws PentahoMetadataException {
LogWriter log = LogWriter.getInstance();
String urlToUse = getURL();
String result = null;
int status = -1;
URL tempURL;
try {
// verify the URL is syntactically correct; we will use these pieces later in this method
tempURL = new URL(urlToUse);
} catch (MalformedURLException e) {
String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
HttpClient client = new HttpClient();
log.logBasic(toString(), Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$
// Assume we are using a proxy if proxyHostName is set?
// TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1)
if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) {
int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ?
client.getHostConfiguration().getPort(): Integer.parseInt(proxyPort);
//TODO: Where to set nonProxyHosts?
client.getHostConfiguration().setProxy(proxyHostname, port);
//TODO: Credentials for proxy will be added if demand shows for it (post v1)
// if (username != null && username.length() > 0) {
// client.getState().setProxyCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials(username, password != null ? password : new String()));
// }
}
// If server userid/password was supplied, use basic authentication to
// authenticate with the server.
if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) {
Credentials creds = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds);
client.getParams().setAuthenticationPreemptive(true);
}
// Get a stream for the specified URL
GetMethod getMethod = new GetMethod(urlToUse);
try {
status = client.executeMethod(getMethod);
if (status == HttpStatus.SC_OK) {
log.logDetailed(toString(), Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$
result = getMethod.getResponseBodyAsString();
log.logBasic(toString(), Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", Integer.toString(result.length()))); //$NON-NLS-1$
} else if (status == HttpStatus.SC_UNAUTHORIZED) {
String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$
log.logError(toString(), msg);
throw new PentahoMetadataException(msg);
}
} catch (HttpException e) {
String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
} catch (IOException e) {
String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", e.getMessage()); //$NON-NLS-1$
// log.logError(toString(), msg);
// log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
if (result != null){
// Get the result back...
Document doc;
try {
doc = XMLHandler.loadXMLString(result);
} catch (KettleXMLException e) {
String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$
log.logError(toString(), msg);
log.logError(toString(), Const.getStackTracker(e));
throw new PentahoMetadataException(msg, e);
}
Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$
if (envelope != null) {
Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$
if (body != null) {
Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$
if (response != null) {
Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$
return content;
}
}
}
}
return null;
}
|
diff --git a/src/main/java/me/zford/jobs/bukkit/tasks/BufferedPaymentThread.java b/src/main/java/me/zford/jobs/bukkit/tasks/BufferedPaymentThread.java
index 87af248..311ab4b 100644
--- a/src/main/java/me/zford/jobs/bukkit/tasks/BufferedPaymentThread.java
+++ b/src/main/java/me/zford/jobs/bukkit/tasks/BufferedPaymentThread.java
@@ -1,90 +1,93 @@
/**
* Jobs Plugin for Bukkit
* Copyright (C) 2011 Zak Ford <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.zford.jobs.bukkit.tasks;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.RegisteredServiceProvider;
import me.zford.jobs.bukkit.JobsPlugin;
import me.zford.jobs.bukkit.economy.BufferedEconomy;
public class BufferedPaymentThread extends Thread {
private JobsPlugin plugin;
private BufferedEconomy bufferedEconomy;
private volatile boolean running = true;
private int sleep;
public BufferedPaymentThread(JobsPlugin plugin, BufferedEconomy bufferedEconomy, int duration) {
super("Jobs-BufferedPaymentThread");
this.plugin = plugin;
this.bufferedEconomy = bufferedEconomy;
this.sleep = duration * 1000;
}
@Override
public void run() {
plugin.getLogger().info("Started buffered payment thread");
while (running) {
try {
sleep(sleep);
} catch (InterruptedException e) {
this.running = false;
continue;
}
try {
Future<Economy> economyFuture = plugin.getServer().getScheduler().callSyncMethod(plugin, new EconomyRegistrationCallable());
Economy economy = economyFuture.get();
if (economy != null)
bufferedEconomy.payAll(economy);
+ } catch (InterruptedException e) {
+ running = false;
+ continue;
} catch (Throwable t) {
t.printStackTrace();
plugin.getLogger().severe("Exception in BufferedPaymentThread, stopping economy payments!");
running = false;
}
}
plugin.getLogger().info("Buffered payment thread shutdown");
}
public void shutdown() {
this.running = false;
interrupt();
}
public class EconomyRegistrationCallable implements Callable<Economy> {
@Override
public Economy call() throws Exception {
RegisteredServiceProvider<Economy> provider = plugin.getServer().getServicesManager().getRegistration(Economy.class);
if (provider == null)
return null;
Economy economy = provider.getProvider();
if (economy == null || !economy.isEnabled())
return null;
return economy;
}
}
}
| true | true | public void run() {
plugin.getLogger().info("Started buffered payment thread");
while (running) {
try {
sleep(sleep);
} catch (InterruptedException e) {
this.running = false;
continue;
}
try {
Future<Economy> economyFuture = plugin.getServer().getScheduler().callSyncMethod(plugin, new EconomyRegistrationCallable());
Economy economy = economyFuture.get();
if (economy != null)
bufferedEconomy.payAll(economy);
} catch (Throwable t) {
t.printStackTrace();
plugin.getLogger().severe("Exception in BufferedPaymentThread, stopping economy payments!");
running = false;
}
}
plugin.getLogger().info("Buffered payment thread shutdown");
}
| public void run() {
plugin.getLogger().info("Started buffered payment thread");
while (running) {
try {
sleep(sleep);
} catch (InterruptedException e) {
this.running = false;
continue;
}
try {
Future<Economy> economyFuture = plugin.getServer().getScheduler().callSyncMethod(plugin, new EconomyRegistrationCallable());
Economy economy = economyFuture.get();
if (economy != null)
bufferedEconomy.payAll(economy);
} catch (InterruptedException e) {
running = false;
continue;
} catch (Throwable t) {
t.printStackTrace();
plugin.getLogger().severe("Exception in BufferedPaymentThread, stopping economy payments!");
running = false;
}
}
plugin.getLogger().info("Buffered payment thread shutdown");
}
|
diff --git a/ndx/src/main/uk/ac/starlink/ndx/XMLNdxHandler.java b/ndx/src/main/uk/ac/starlink/ndx/XMLNdxHandler.java
index 451505196..f7f6cd02a 100644
--- a/ndx/src/main/uk/ac/starlink/ndx/XMLNdxHandler.java
+++ b/ndx/src/main/uk/ac/starlink/ndx/XMLNdxHandler.java
@@ -1,550 +1,550 @@
package uk.ac.starlink.ndx;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.logging.Logger;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import uk.ac.starlink.array.AccessMode;
import uk.ac.starlink.array.ArrayBuilder;
import uk.ac.starlink.array.BadHandler;
import uk.ac.starlink.array.NDArray;
import uk.ac.starlink.array.NDArrays;
import uk.ac.starlink.array.NDArrayFactory;
import uk.ac.starlink.array.NDShape;
import uk.ac.starlink.array.Type;
import uk.ac.starlink.ast.AstPackage;
import uk.ac.starlink.ast.FrameSet;
import uk.ac.starlink.ast.xml.XAstReader;
import uk.ac.starlink.util.SourceReader;
import uk.ac.starlink.util.URLUtils;
/**
* Turns URLs which reference XML files into Ndxs.
* This does not do such sophisticated processing as the HDX system,
* and is mainly intended as a stopgap until that is complete.
* No namespace is used in XML files, and array URL references may
* be either as the value of a 'url' attribute or as the text
* content of an element, e.g.:
* <pre>
* <variance url="http://archive.org/data/stars-vars.fits"/>
* <pre>
* or
* <pre>
* <variance>http://archive.org/data/stars-vars.fits</variance>
* </pre>
* URLs relative to the position of the XML file in question are allowed.
* <p>
* A URL is normally only considered suitable if it ends in '.xml'.
* However, the special URL "<tt>file:-</tt>" may be used to
* indicate standard input/output.
*/
public class XMLNdxHandler implements NdxHandler {
/** Sole instance of the class. */
private static XMLNdxHandler instance = new XMLNdxHandler();
private static NDArrayFactory arrayfact = new NDArrayFactory();
private static Logger logger = Logger.getLogger( "uk.ac.starlink.ndx" );
/**
* Private sole constructor.
*/
private XMLNdxHandler() {}
/**
* Returns an XMLNdxHandler.
*
* @return the sole instance of this class
*/
public static XMLNdxHandler getInstance() {
return instance;
}
/**
* Constructs an Ndx object from a URL pointing to an appropriate
* XML resource.
*
* @param url a URL pointing to some XML representing an NDX
* @param mode read/write/update access mode for component arrays
* @throws IOException if some error occurs in the I/O
*/
public Ndx makeNdx( URL url, AccessMode mode ) throws IOException {
Source xsrc;
if ( url.toString().equals( "file:-" ) ) {
xsrc = new StreamSource( System.in );
}
else if ( isXmlUrl( url ) ) {
xsrc = new StreamSource( url.toString() );
}
else {
return null;
}
return makeNdx( xsrc, mode );
}
/**
* Constructs a readable Ndx object from an XML source.
*
* @param xsrc an XML source containing the XML representation of
* the NDX. Must represent a document or element.
* Note that the SystemId attribute, if present,
* will be used to resolve relative URLs
* @param mode read/write/update access mode for component arrays
* @throws IOException if some error occurs in the I/O
* @throws IllegalArgumentException if <tt>xsrc</tt> does not
* correspond to a document or element XML source
*/
public Ndx makeNdx( Source xsrc, AccessMode mode ) throws IOException {
/* Try to get the System ID for resolving relative URLs. */
String systemId = xsrc.getSystemId();
/* Get a DOM. */
Node ndxdom;
try {
ndxdom = new SourceReader().getDOM( xsrc );
}
catch ( TransformerException e ) {
throw (IOException) new IOException( e.getMessage() )
.initCause( e );
}
/* Check we have an <ndx> element. */
Element ndxel;
if ( ndxdom instanceof Document ) {
ndxel = ((Document) ndxdom).getDocumentElement();
}
else if ( ndxdom instanceof Element ) {
ndxel = (Element) ndxdom;
}
else {
throw new IllegalArgumentException( "Not a Document or Element" );
}
if ( ! ndxel.getTagName().equals( "ndx" ) ) {
throw new IOException(
"XML element of type <" + ndxel.getTagName() + "> not <ndx>" );
}
Document doc = ndxel.getOwnerDocument();
/* Parse the DOM looking for known elements. A proper implementation
* probably wants to use XPaths and so on. */
NDArray image = null;
NDArray variance = null;
NDArray quality = null;
String title = null;
FrameSet wcs = null;
int badbits = 0;
Node etc = null;
for ( Node child = ndxel.getFirstChild(); child != null;
child = child.getNextSibling() ) {
if ( child instanceof Element ) {
Element cel = (Element) child;
String tagname = cel.getTagName();
if ( tagname.equals( "image" ) ) {
image = makeNDArray( cel, mode, systemId );
}
else if ( tagname.equals( "variance" ) ) {
variance = makeNDArray( cel, mode, systemId );
}
else if ( tagname.equals( "quality" ) ) {
quality = makeNDArray( cel, mode, systemId );
}
else if ( tagname.equals( "title" ) ) {
title = getTextContent( cel );
}
else if ( tagname.equals( "badbits" ) ) {
badbits = Long.decode( getTextContent( cel ) ).intValue();
}
else if ( tagname.equals( "wcs" ) &&
AstPackage.isAvailable() ) {
Source wcssrc = null;
for ( Node ch = cel.getFirstChild(); ch != null;
ch = ch.getNextSibling() ) {
if ( ch instanceof Element ) {
String chname = ((Element) ch).getTagName();
if ( chname.equals( "FrameSet" ) ) {
wcssrc = new DOMSource( ch );
break;
}
}
}
try {
wcs = (FrameSet) new XAstReader()
.makeAst( wcssrc, null );
}
catch ( IOException e ) {
wcs = null;
}
if ( wcs == null ) {
logger.warning( "Broken WCS element" );
}
}
else if ( tagname.equals( "etc" ) ) {
etc = doc.createElement( "etc" );
for ( Node ext = cel.getFirstChild(); ext != null;
ext = ext.getNextSibling() ) {
etc.appendChild( doc.importNode( ext, true ) );
}
}
}
}
return makeNdx( image, variance, quality, title, wcs, badbits, etc );
}
private NDArray makeNDArray( Element el, AccessMode mode, String systemId )
throws IOException {
String loc;
if ( el.hasAttribute( "url" ) ) {
loc = el.getAttribute( "url" );
}
else {
loc = getTextContent( el );
}
if ( loc == null || loc.trim().length() == 0 ) {
throw new IOException( "No location supplied for <"
+ el.getTagName() + "> array" );
}
URL url = URLUtils.makeURL( systemId, loc );
return arrayfact.makeNDArray( url, mode );
}
private String getTextContent( Element el ) {
String content = "";
for ( Node sub = el.getFirstChild(); sub != null;
sub = sub.getNextSibling() ) {
if ( sub instanceof Text || sub instanceof CDATASection ) {
content += ((CharacterData) sub).getData();
}
}
return content;
}
private Ndx makeNdx( final NDArray image, final NDArray variance,
final NDArray quality, final String title,
final FrameSet wcs, final int badbits,
final Node etc )
throws IOException {
if ( image == null ) {
throw new IOException( "No <image> component found" );
}
NdxImpl impl = new NdxImpl() {
public NDArray getImage() {
return image;
}
public NDArray getVariance() {
return variance;
}
public NDArray getQuality() {
return quality;
}
public String getTitle() {
return title;
}
public Object getWCS() {
return wcs;
}
public int getBadBits() {
return badbits;
}
public Source getEtc() {
return new DOMSource( etc );
}
public boolean hasTitle() {
return title != null;
}
public boolean hasVariance() {
return variance != null;
}
public boolean hasQuality() {
return quality != null;
}
public boolean hasWCS() {
return wcs != null;
}
public boolean hasEtc() {
return etc != null;
}
};
return new BridgeNdx( impl );
}
/**
* Writes an XML representation of an existing Ndx object to the given
* (writable) URL.
* <p>
* If any of the array components is virtual, then the array data
* needs to be output too. Currently, for a URL 'blah.xml'
* these are written into successive components of a new FITS file
* 'blah-data.fits'. If the FITS handlers are not installed,
* or <tt>url</tt> does not end in '.xml' an IOException will be thrown.
* This behaviour may be subject to change in future releases.
*
* @param xurl the URL to which the Ndx is to be serialised in XML
* @param ndx the Ndx object to serialise
* @throws java.net.UnknownServiceException if the URL does not support
* output (most protocols, apart from <tt>file</tt>, don't)
* @throws IOException if some other I/O error occurs
*/
public boolean outputNdx( URL xurl, Ndx ndx ) throws IOException {
/* If we need one, get a URL for writing array data. */
URL aurl = null;
ArrayBuilder fab = null;
if ( ! ndx.isPersistent() ) {
aurl = getDataUrl( xurl );
fab = getFitsArrayBuilder();
}
boolean writeArrays = ( aurl != null );
/* Get XML output stream. */
OutputStream xstrm;
if ( xurl.toString().equals( "file:-" ) ) {
if ( writeArrays ) {
throw new IOException( "Cannot serialise non-persistent NDX "
+ "to a stream" );
}
xstrm = System.out;
}
else if ( isXmlUrl( xurl ) ) {
if ( xurl.getProtocol().equals( "file" ) ) {
xstrm = new FileOutputStream( xurl.getPath() );
}
else {
URLConnection xconn = xurl.openConnection();
xconn.setDoInput( false );
xconn.setDoOutput( true );
/* The following may throw a java.net.UnknownServiceException
- * (which is-a IOException) - in fact it almost certiainly will,
+ * (which is-a IOException) - in fact it almost certainly will,
* since I don't know of any URL protocols (including file)
* which support output streams. */
xconn.connect();
xstrm = xconn.getOutputStream();
}
xstrm = new BufferedOutputStream( xstrm );
}
else {
return false;
}
/* Get an XML source representing the XML to be written. */
Source xsrc;
if ( ! writeArrays ) {
xsrc = ndx.toXML( null );
}
else {
int hdu = 0;
NDArray inda2;
URL iurl = new URL( aurl, "#" + hdu++ );
NDArray inda1 = ndx.getImage();
inda2 = fab.makeNewNDArray( iurl, inda1.getShape(),
inda1.getType(),
inda1.getBadHandler() );
NDArrays.copy( inda1, inda2 );
NDArray vnda2;
if ( ndx.hasVariance() ) {
URL vurl = new URL( aurl, "#" + hdu++ );
NDArray vnda1 = ndx.getVariance();
vnda2 = fab.makeNewNDArray( vurl, vnda1.getShape(),
vnda1.getType(),
vnda1.getBadHandler() );
NDArrays.copy( vnda1, vnda2 );
}
else {
vnda2 = null;
}
NDArray qnda2;
if ( ndx.hasQuality() ) {
URL qurl = new URL( aurl, "#" + hdu++ );
NDArray qnda1 = ndx.getQuality();
BadHandler qbh = BadHandler.getHandler( qnda1.getType(), null );
qnda2 = fab.makeNewNDArray( qurl, qnda1.getShape(),
qnda1.getType(), qbh );
NDArrays.copy( qnda1, qnda2 );
}
else {
qnda2 = null;
}
MutableNdx ndx2 = new DefaultMutableNdx( ndx );
ndx2.setImage( inda2 );
ndx2.setVariance( vnda2 );
ndx2.setQuality( qnda2 );
xsrc = ndx2.toXML( xurl );
}
/* Write the XML to the XML stream. */
SourceReader sr = new SourceReader();
// this bit isn't safe - can't guarantee the transformer will be
// invoked, so we may get no declaration after all.
sr.setIncludeDeclaration( true );
sr.setIndent( 2 );
try {
sr.writeSource( xsrc, xstrm );
}
catch ( TransformerException e ) {
throw (IOException) new IOException( "Trouble writing XML" )
.initCause( e );
}
xstrm.close();
return true;
}
/**
* Writes an XML file representing a new NDX with writable array
* components.
* <p>
* The array components themselves reside in a new fits file;
* currently for a URL 'blah.xml' a new fits file called
* 'blah-data.fits' is written. If the FITS handlers are not installed,
* or <tt>url</tt> does not end in '.xml' an IOException will be thrown.
* This behaviour may be subject to change in future releases.
*
* @param url a URL at which the new NDX should be written
* @param template a template Ndx object from which non-array data
* should be initialised - any title, bad bits mask,
* WCS component etc will be copied from here
* @param a new Ndx based on <tt>template</tt> but with writable arrays
* @return true if the new Ndx was written successfully
* @throws IOException if the URL is understood but an NDArray cannot
* be made
*/
public boolean makeBlankNdx( URL url, Ndx template ) throws IOException {
if ( ! isXmlUrl( url ) ) {
return false;
}
URL xurl = url;
URL aurl = getDataUrl( xurl );
ArrayBuilder fab = getFitsArrayBuilder();
OutputStream xstrm = new FileOutputStream( xurl.getPath() );
xstrm = new BufferedOutputStream( xstrm );
/* Make NDArrays containing the data. */
int hdu = 0;
URL iurl = new URL( aurl, "#" + hdu++ );
NDArray inda1 = template.getImage();
NDArray inda2 = fab.makeNewNDArray( iurl, inda1.getShape(),
inda1.getType(),
inda1.getBadHandler() );
NDArray vnda2;
if ( template.hasVariance() ) {
URL vurl = new URL( aurl, "#" + hdu++ );
NDArray vnda1 = template.getVariance();
vnda2 = fab.makeNewNDArray( vurl, vnda1.getShape(),
vnda1.getType(),
vnda1.getBadHandler() );
}
else {
vnda2 = null;
}
NDArray qnda2;
if ( template.hasQuality() ) {
URL qurl = new URL( aurl, "#" + hdu++ );
NDArray qnda1 = template.getQuality();
BadHandler qbh = BadHandler.getHandler( qnda1.getType(), null );
qnda2 = fab.makeNewNDArray( qurl, qnda1.getShape(),
qnda1.getType(), qbh );
}
else {
qnda2 = null;
}
MutableNdx ndx = new DefaultMutableNdx( template );
/* Write the XML representation of the NDX to the XML stream. */
SourceReader sr = new SourceReader();
sr.setIncludeDeclaration( true );
sr.setIndent( 2 );
try {
sr.writeSource( ndx.toXML( xurl ), xstrm );
}
catch ( TransformerException e ) {
throw (IOException) new IOException( "Trouble writing XML" )
.initCause( e );
}
xstrm.close();
return true;
}
private boolean isXmlUrl( URL url ) {
return url.getPath().endsWith( ".xml" );
}
/**
* Returns a URL for a FITS file related to a given URL suitable
* for writing array data into.
*
* @param baseUrl the URL of an XML file
* @return a URL suitable for writing fits data to if the XML is in
* baseUrl
* @throws IOException if something breaks
*/
private static URL getDataUrl( URL baseUrl ) throws IOException {
URL durl;
if ( baseUrl.toString().endsWith( ".xml" ) ) {
String dloc = baseUrl.toString()
.replaceFirst( ".xml$", "-data.fits" );
try {
return new URL( dloc );
}
catch ( MalformedURLException e ) {
throw new AssertionError();
}
}
else {
throw new IOException( "Cannot write data for base URL <"
+ baseUrl + "> not ending in '.xml'" );
}
}
/**
* Get an ArrayBuilder that can build Fits files.
*
* @return a FitsArrayBuilder
* @throws IOException if the FITS handlers aren't installed
*/
private static ArrayBuilder getFitsArrayBuilder() throws IOException {
for ( Iterator it = arrayfact.getBuilders().iterator();
it.hasNext(); ) {
ArrayBuilder builder = (ArrayBuilder) it.next();
if ( builder.getClass().getName()
.equals( "uk.ac.starlink.fits.FitsArrayBuilder" ) ) {
return builder;
}
}
throw new IOException( "Can't get FitsArrayBuilder - " +
"FITS package not installed" );
}
}
| true | true | public boolean outputNdx( URL xurl, Ndx ndx ) throws IOException {
/* If we need one, get a URL for writing array data. */
URL aurl = null;
ArrayBuilder fab = null;
if ( ! ndx.isPersistent() ) {
aurl = getDataUrl( xurl );
fab = getFitsArrayBuilder();
}
boolean writeArrays = ( aurl != null );
/* Get XML output stream. */
OutputStream xstrm;
if ( xurl.toString().equals( "file:-" ) ) {
if ( writeArrays ) {
throw new IOException( "Cannot serialise non-persistent NDX "
+ "to a stream" );
}
xstrm = System.out;
}
else if ( isXmlUrl( xurl ) ) {
if ( xurl.getProtocol().equals( "file" ) ) {
xstrm = new FileOutputStream( xurl.getPath() );
}
else {
URLConnection xconn = xurl.openConnection();
xconn.setDoInput( false );
xconn.setDoOutput( true );
/* The following may throw a java.net.UnknownServiceException
* (which is-a IOException) - in fact it almost certiainly will,
* since I don't know of any URL protocols (including file)
* which support output streams. */
xconn.connect();
xstrm = xconn.getOutputStream();
}
xstrm = new BufferedOutputStream( xstrm );
}
else {
return false;
}
/* Get an XML source representing the XML to be written. */
Source xsrc;
if ( ! writeArrays ) {
xsrc = ndx.toXML( null );
}
else {
int hdu = 0;
NDArray inda2;
URL iurl = new URL( aurl, "#" + hdu++ );
NDArray inda1 = ndx.getImage();
inda2 = fab.makeNewNDArray( iurl, inda1.getShape(),
inda1.getType(),
inda1.getBadHandler() );
NDArrays.copy( inda1, inda2 );
NDArray vnda2;
if ( ndx.hasVariance() ) {
URL vurl = new URL( aurl, "#" + hdu++ );
NDArray vnda1 = ndx.getVariance();
vnda2 = fab.makeNewNDArray( vurl, vnda1.getShape(),
vnda1.getType(),
vnda1.getBadHandler() );
NDArrays.copy( vnda1, vnda2 );
}
else {
vnda2 = null;
}
NDArray qnda2;
if ( ndx.hasQuality() ) {
URL qurl = new URL( aurl, "#" + hdu++ );
NDArray qnda1 = ndx.getQuality();
BadHandler qbh = BadHandler.getHandler( qnda1.getType(), null );
qnda2 = fab.makeNewNDArray( qurl, qnda1.getShape(),
qnda1.getType(), qbh );
NDArrays.copy( qnda1, qnda2 );
}
else {
qnda2 = null;
}
MutableNdx ndx2 = new DefaultMutableNdx( ndx );
ndx2.setImage( inda2 );
ndx2.setVariance( vnda2 );
ndx2.setQuality( qnda2 );
xsrc = ndx2.toXML( xurl );
}
/* Write the XML to the XML stream. */
SourceReader sr = new SourceReader();
// this bit isn't safe - can't guarantee the transformer will be
// invoked, so we may get no declaration after all.
sr.setIncludeDeclaration( true );
sr.setIndent( 2 );
try {
sr.writeSource( xsrc, xstrm );
}
catch ( TransformerException e ) {
throw (IOException) new IOException( "Trouble writing XML" )
.initCause( e );
}
xstrm.close();
return true;
}
| public boolean outputNdx( URL xurl, Ndx ndx ) throws IOException {
/* If we need one, get a URL for writing array data. */
URL aurl = null;
ArrayBuilder fab = null;
if ( ! ndx.isPersistent() ) {
aurl = getDataUrl( xurl );
fab = getFitsArrayBuilder();
}
boolean writeArrays = ( aurl != null );
/* Get XML output stream. */
OutputStream xstrm;
if ( xurl.toString().equals( "file:-" ) ) {
if ( writeArrays ) {
throw new IOException( "Cannot serialise non-persistent NDX "
+ "to a stream" );
}
xstrm = System.out;
}
else if ( isXmlUrl( xurl ) ) {
if ( xurl.getProtocol().equals( "file" ) ) {
xstrm = new FileOutputStream( xurl.getPath() );
}
else {
URLConnection xconn = xurl.openConnection();
xconn.setDoInput( false );
xconn.setDoOutput( true );
/* The following may throw a java.net.UnknownServiceException
* (which is-a IOException) - in fact it almost certainly will,
* since I don't know of any URL protocols (including file)
* which support output streams. */
xconn.connect();
xstrm = xconn.getOutputStream();
}
xstrm = new BufferedOutputStream( xstrm );
}
else {
return false;
}
/* Get an XML source representing the XML to be written. */
Source xsrc;
if ( ! writeArrays ) {
xsrc = ndx.toXML( null );
}
else {
int hdu = 0;
NDArray inda2;
URL iurl = new URL( aurl, "#" + hdu++ );
NDArray inda1 = ndx.getImage();
inda2 = fab.makeNewNDArray( iurl, inda1.getShape(),
inda1.getType(),
inda1.getBadHandler() );
NDArrays.copy( inda1, inda2 );
NDArray vnda2;
if ( ndx.hasVariance() ) {
URL vurl = new URL( aurl, "#" + hdu++ );
NDArray vnda1 = ndx.getVariance();
vnda2 = fab.makeNewNDArray( vurl, vnda1.getShape(),
vnda1.getType(),
vnda1.getBadHandler() );
NDArrays.copy( vnda1, vnda2 );
}
else {
vnda2 = null;
}
NDArray qnda2;
if ( ndx.hasQuality() ) {
URL qurl = new URL( aurl, "#" + hdu++ );
NDArray qnda1 = ndx.getQuality();
BadHandler qbh = BadHandler.getHandler( qnda1.getType(), null );
qnda2 = fab.makeNewNDArray( qurl, qnda1.getShape(),
qnda1.getType(), qbh );
NDArrays.copy( qnda1, qnda2 );
}
else {
qnda2 = null;
}
MutableNdx ndx2 = new DefaultMutableNdx( ndx );
ndx2.setImage( inda2 );
ndx2.setVariance( vnda2 );
ndx2.setQuality( qnda2 );
xsrc = ndx2.toXML( xurl );
}
/* Write the XML to the XML stream. */
SourceReader sr = new SourceReader();
// this bit isn't safe - can't guarantee the transformer will be
// invoked, so we may get no declaration after all.
sr.setIncludeDeclaration( true );
sr.setIndent( 2 );
try {
sr.writeSource( xsrc, xstrm );
}
catch ( TransformerException e ) {
throw (IOException) new IOException( "Trouble writing XML" )
.initCause( e );
}
xstrm.close();
return true;
}
|
diff --git a/demos/src/main/java/com/datatorrent/demos/mobile/SeedPhonesGenerator.java b/demos/src/main/java/com/datatorrent/demos/mobile/SeedPhonesGenerator.java
index 9a6fe4fc0..ed98ce5fc 100644
--- a/demos/src/main/java/com/datatorrent/demos/mobile/SeedPhonesGenerator.java
+++ b/demos/src/main/java/com/datatorrent/demos/mobile/SeedPhonesGenerator.java
@@ -1,76 +1,77 @@
package com.datatorrent.demos.mobile;
import com.datatorrent.api.BaseOperator;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.InputOperator;
import com.datatorrent.api.annotation.OutputPortFieldAnnotation;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.Min;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* Generates mobile numbers that will be displayed in mobile demo just after launch.<br></br>
* Operator attributes:<b>
* <ul>
* <li>initialDisplayCount: No. of seed phone numbers that will be generated.</li>
* <li>maxSeedPhoneNumber: The largest seed phone number.</li>
* </ul>
* </b>
* @since 0.3.5
*/
public class SeedPhonesGenerator extends BaseOperator implements InputOperator
{
private static Logger LOG = LoggerFactory.getLogger(SeedPhonesGenerator.class);
@Min(0)
private int initialDisplayCount = 0;
private int maxSeedPhoneNumber = 0;
private int rangeLowerEndpoint;
private int rangeUpperEndpoint;
public void setInitialDisplayCount(int i)
{
initialDisplayCount = i;
}
public void setPhoneRange(Range<Integer> phoneRange)
{
this.rangeLowerEndpoint = phoneRange.lowerEndpoint();
this.rangeUpperEndpoint = phoneRange.upperEndpoint();
}
public void setMaxSeedPhoneNumber(int number)
{
this.maxSeedPhoneNumber = number;
}
@OutputPortFieldAnnotation(name = "seedPhones")
public final transient DefaultOutputPort<Map<String, String>> seedPhones = new DefaultOutputPort<Map<String, String>>();
@Override
public void emitTuples()
{
Random random = new Random();
int maxPhone = (maxSeedPhoneNumber <= rangeUpperEndpoint && maxSeedPhoneNumber >= rangeLowerEndpoint) ? maxSeedPhoneNumber : rangeUpperEndpoint;
maxPhone -= 5550000;
- for (int i = initialDisplayCount; i-- > 0; ) {
+ int phonesToDisplay = initialDisplayCount > maxPhone ? maxPhone : initialDisplayCount;
+ for (int i = phonesToDisplay; i-- > 0; ) {
int phoneNo = 5550000 + random.nextInt(maxPhone + 1);
LOG.info("seed no: "+phoneNo);
Map<String, String> query = Maps.newHashMap();
query.put(PhoneMovementGenerator.KEY_COMMAND, PhoneMovementGenerator.COMMAND_ADD);
query.put(PhoneMovementGenerator.KEY_PHONE, Integer.toString(phoneNo));
query.put(PhoneMovementGenerator.KEY_QUERYID, "SPG" + i);
seedPhones.emit(query);
}
// done generating data
LOG.info("Finished generating data.");
throw new RuntimeException(new InterruptedException("Finished generating data."));
}
}
| true | true | public void emitTuples()
{
Random random = new Random();
int maxPhone = (maxSeedPhoneNumber <= rangeUpperEndpoint && maxSeedPhoneNumber >= rangeLowerEndpoint) ? maxSeedPhoneNumber : rangeUpperEndpoint;
maxPhone -= 5550000;
for (int i = initialDisplayCount; i-- > 0; ) {
int phoneNo = 5550000 + random.nextInt(maxPhone + 1);
LOG.info("seed no: "+phoneNo);
Map<String, String> query = Maps.newHashMap();
query.put(PhoneMovementGenerator.KEY_COMMAND, PhoneMovementGenerator.COMMAND_ADD);
query.put(PhoneMovementGenerator.KEY_PHONE, Integer.toString(phoneNo));
query.put(PhoneMovementGenerator.KEY_QUERYID, "SPG" + i);
seedPhones.emit(query);
}
// done generating data
LOG.info("Finished generating data.");
throw new RuntimeException(new InterruptedException("Finished generating data."));
}
| public void emitTuples()
{
Random random = new Random();
int maxPhone = (maxSeedPhoneNumber <= rangeUpperEndpoint && maxSeedPhoneNumber >= rangeLowerEndpoint) ? maxSeedPhoneNumber : rangeUpperEndpoint;
maxPhone -= 5550000;
int phonesToDisplay = initialDisplayCount > maxPhone ? maxPhone : initialDisplayCount;
for (int i = phonesToDisplay; i-- > 0; ) {
int phoneNo = 5550000 + random.nextInt(maxPhone + 1);
LOG.info("seed no: "+phoneNo);
Map<String, String> query = Maps.newHashMap();
query.put(PhoneMovementGenerator.KEY_COMMAND, PhoneMovementGenerator.COMMAND_ADD);
query.put(PhoneMovementGenerator.KEY_PHONE, Integer.toString(phoneNo));
query.put(PhoneMovementGenerator.KEY_QUERYID, "SPG" + i);
seedPhones.emit(query);
}
// done generating data
LOG.info("Finished generating data.");
throw new RuntimeException(new InterruptedException("Finished generating data."));
}
|
diff --git a/android/src/net/wesley/gitadroia/ExpandedListView.java b/android/src/net/wesley/gitadroia/ExpandedListView.java
index a1a9c51..325b924 100644
--- a/android/src/net/wesley/gitadroia/ExpandedListView.java
+++ b/android/src/net/wesley/gitadroia/ExpandedListView.java
@@ -1,27 +1,27 @@
package net.wesley.gitadroia;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ListView;
public class ExpandedListView extends ListView {
private android.view.ViewGroup.LayoutParams params;
private int old_count = 0;
public ExpandedListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
if (getCount() != old_count) {
old_count = getCount();
params = getLayoutParams();
- params.height = getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0);
+ params.height = getCount() * (old_count > 0 ? (getChildAt(0).getHeight()+2) : 0);
setLayoutParams(params);
}
super.onDraw(canvas);
}
}
| true | true | protected void onDraw(Canvas canvas) {
if (getCount() != old_count) {
old_count = getCount();
params = getLayoutParams();
params.height = getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0);
setLayoutParams(params);
}
super.onDraw(canvas);
}
| protected void onDraw(Canvas canvas) {
if (getCount() != old_count) {
old_count = getCount();
params = getLayoutParams();
params.height = getCount() * (old_count > 0 ? (getChildAt(0).getHeight()+2) : 0);
setLayoutParams(params);
}
super.onDraw(canvas);
}
|
diff --git a/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/parser/ast/AsfixImploder.java b/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/parser/ast/AsfixImploder.java
index 6f49fb14..0e66d7fc 100644
--- a/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/parser/ast/AsfixImploder.java
+++ b/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/parser/ast/AsfixImploder.java
@@ -1,353 +1,355 @@
package org.strategoxt.imp.runtime.parser.ast;
import static java.lang.Math.*;
import static org.spoofax.jsglr.Term.*;
import static org.strategoxt.imp.runtime.parser.tokens.TokenKind.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import lpg.runtime.IToken;
import lpg.runtime.PrsStream;
import org.strategoxt.imp.runtime.Debug;
import org.strategoxt.imp.runtime.parser.tokens.SGLRTokenizer;
import org.strategoxt.imp.runtime.parser.tokens.TokenKindManager;
import aterm.ATerm;
import aterm.ATermAppl;
import aterm.ATermInt;
import aterm.ATermList;
import aterm.pure.ATermListImpl;
/**
* Implodes an Asfix tree to AstNode nodes and IToken tokens.
*
* @author Lennart Kats <L.C.L.Kats add tudelft.nl>
*/
public class AsfixImploder {
private static final int EXPECTED_NODE_CHILDREN = 5;
protected static final int PARSE_TREE = 0;
protected static final int APPL_PROD = 0;
protected static final int APPL_CONTENTS = 1;
protected static final int PROD_LHS = 0;
protected static final int PROD_RHS = 1;
protected static final int PROD_ATTRS = 2;
private static final Map<ATerm, AstNode> implodedCache =
Collections.synchronizedMap(new WeakHashMap<ATerm, AstNode>());
protected final AstNodeFactory factory = new AstNodeFactory();
private final ProductionAttributeReader reader = new ProductionAttributeReader();
private final TokenKindManager tokenManager;
protected SGLRTokenizer tokenizer;
/** Character offset for the current implosion. */
protected int offset;
protected boolean lexicalContext;
public AsfixImploder(TokenKindManager tokenManager) {
this.tokenManager = tokenManager;
}
public AstNode implode(ATerm asfix, SGLRTokenizer tokenizer) {
this.tokenizer = tokenizer;
// TODO: Return null if imploded tree has null constructor??
AstNode result = implodedCache.get(asfix);
if (result != null) return result;
Debug.startTimer();
if (!(asfix instanceof ATermAppl || ((ATermAppl) asfix).getName().equals("parsetree")))
throw new IllegalArgumentException("Parse tree expected");
assert offset == 0 && tokenizer.getStartOffset() == 0 : "Race condition in AsfixImploder";
ATerm top = (ATerm) asfix.getChildAt(PARSE_TREE);
offset = 0;
lexicalContext = false;
try {
result = implodeAppl(top);
} finally {
tokenizer.endStream();
offset = 0;
}
if (Debug.ENABLED) {
Debug.stopTimer("Parse tree imploded");
Debug.log("Parsed " + result.toString());
}
implodedCache.put(asfix, result);
assert implodedCache.get(asfix) == result;
return result;
}
/**
* Implode any appl(_, _).
*/
protected AstNode implodeAppl(ATerm term) {
ATermAppl appl = resolveAmbiguities(term);
ATermAppl prod = termAt(appl, APPL_PROD);
ATermList lhs = termAt(prod, PROD_LHS);
ATermAppl rhs = termAt(prod, PROD_RHS);
ATermAppl attrs = termAt(prod, PROD_ATTRS);
ATermList contents = termAt(appl, APPL_CONTENTS);
IToken prevToken = tokenizer.currentToken();
// Enter lexical context if this is a lex node
boolean lexicalStart = !lexicalContext
&& ("lex".equals(rhs.getName()) || AsfixAnalyzer.isLiteral(rhs)
|| AsfixAnalyzer.isLayout(rhs));
if (lexicalStart) lexicalContext = true;
if (!lexicalContext && "sort".equals(rhs.getName()) && lhs.getLength() == 1 && termAt(contents, 0).getType() == ATerm.INT) {
return createIntTerminal(contents, rhs);
}
boolean isList = !lexicalContext && AsfixAnalyzer.isList(rhs);
boolean isVar = !lexicalContext && !isList && "varsym".equals(rhs.getName());
if (isVar) lexicalContext = true;
// Recurse the tree (and set children if applicable)
ArrayList<AstNode> children =
implodeChildNodes(contents);
if (lexicalStart || isVar) {
return createStringTerminal(lhs, rhs);
} else if (lexicalContext) {
return null; // don't create tokens inside lexical context; just create one big token at the top
} else {
return createNonTerminalOrInjection(lhs, rhs, attrs, prevToken, children, isList);
}
}
protected ArrayList<AstNode> implodeChildNodes(ATermList contents) {
ArrayList<AstNode> results = lexicalContext
? null
: new ArrayList<AstNode>(
min(EXPECTED_NODE_CHILDREN, contents.getChildCount()));
for (int i = 0; i < contents.getLength(); i++) {
ATerm child = contents.elementAt(i);
if (isInt(child)) {
implodeLexical((ATermInt) child);
} else {
// Recurse
AstNode childNode = implodeAppl(child);
if (childNode != null)
results.add(childNode);
}
}
return results;
}
private StringAstNode createStringTerminal(ATermList lhs, ATermAppl rhs) {
lexicalContext = false;
IToken token = tokenizer.makeToken(offset, tokenManager.getTokenKind(lhs, rhs), true);
String sort = reader.getSort(rhs);
if (sort == null) return null;
//Debug.log("Creating node ", sort, " from ", SGLRTokenizer.dumpToString(token));
return factory.createStringTerminal(sort, token);
}
private IntAstNode createIntTerminal(ATermList contents, ATermAppl rhs) {
IToken token = tokenizer.makeToken(offset, tokenManager.getTokenKind(contents, rhs), true);
String sort = reader.getSort(rhs);
int value = intAt(contents, 0);
return factory.createIntTerminal(sort, token, value);
}
private AstNode createNonTerminalOrInjection(ATermList lhs, ATermAppl rhs, ATermAppl attrs,
IToken prevToken, ArrayList<AstNode> children, boolean isList) {
String constructor = reader.getConsAttribute(attrs);
String sort = reader.getSort(rhs);
if(constructor == null) {
if (isList) {
return createNonTerminal(sort, null, prevToken, children, true);
}
ATerm ast = reader.getAstAttribute(attrs);
if (ast != null) {
return createAstNonTerminal(rhs, prevToken, children, ast);
} else if (children.size() == 0) {
return createNonTerminal(sort, "None", prevToken, children, false);
} else if ("opt".equals(applAt(rhs, 0).getName())) {
assert children.size() == 1;
AstNode child = children.get(0);
return new AstNode(sort, child.getLeftIToken(), child.getRightIToken(), "Some", children);
} else {
// Injection
assert children.size() == 1;
return children.get(0);
}
} else {
tokenizer.makeToken(offset, tokenManager.getTokenKind(lhs, rhs));
return createNonTerminal(sort, constructor, prevToken, children, isList);
}
}
/** Implode a context-free node. */
private AstNode createNonTerminal(String sort, String constructor, IToken prevToken,
ArrayList<AstNode> children, boolean isList) {
IToken left = getStartToken(prevToken);
IToken right = getEndToken(left, tokenizer.currentToken());
/*
if (Debug.ENABLED) {
String name = isList ? "list" : sort;
Debug.log("Creating node ", name, ":", constructor, AstNode.getSorts(children), " from ", SGLRTokenizer.dumpToString(left, right));
}
*/
if (isList) {
return factory.createList(sort, left, right, children);
} else if (constructor == null && children.size() == 1 && children.get(0).getSort() == AstNode.STRING_SORT) {
// Child node was a <string> node (rare case); unpack it and create a new terminal
assert left == right && children.get(0).getChildren().size() == 0;
return factory.createStringTerminal(sort, left);
} else {
return factory.createNonTerminal(sort, constructor, left, right, children);
}
}
/** Implode a context-free node with an {ast} annotation. */
private AstNode createAstNonTerminal(ATermAppl rhs, IToken prevToken, ArrayList<AstNode> children, ATerm ast) {
IToken left = getStartToken(prevToken);
IToken right = getEndToken(left, tokenizer.currentToken());
AstAnnoImploder imploder = new AstAnnoImploder(factory, children, left, right);
return imploder.implode(ast, reader.getSort(rhs));
}
/**
* Resolve or ignore any ambiguities in the parse tree.
*/
protected ATermAppl resolveAmbiguities(final ATerm node) {
if (!"amb".equals(((ATermAppl) node).getName()))
return (ATermAppl) node;
final ATermListImpl ambs = termAt(node, 0);
ATermAppl lastNonAvoid = null;
+ ATermAppl firstOption = null;
boolean multipleNonAvoids = false;
alts:
for (int i = 0; i < ambs.getLength(); i++) {
ATermAppl prod = resolveAmbiguities(termAt(ambs, i));
+ if (firstOption == null) firstOption = prod;
ATermAppl appl = termAt(prod, APPL_PROD);
ATermAppl attrs = termAt(appl, PROD_ATTRS);
if ("attrs".equals(attrs.getName())) {
ATermList attrList = termAt(attrs, 0);
for (int j = 0; j < attrList.getLength(); j++) {
ATerm attr = termAt(attrList, j);
if (isAppl(attr) && "prefer".equals(asAppl(attr).getName())) {
- return resolveAmbiguities(prod);
+ return prod;
} else if (isAppl(attr) && "avoid".equals(asAppl(attr).getName())) {
continue alts;
}
}
if (lastNonAvoid == null) {
lastNonAvoid = prod;
} else {
multipleNonAvoids = true;
}
}
}
if (!multipleNonAvoids) {
- return lastNonAvoid != null ? lastNonAvoid : applAt(ambs, 0);
+ return lastNonAvoid != null ? lastNonAvoid : firstOption;
} else {
if (Debug.ENABLED && !lexicalContext) reportUnresolvedAmb(ambs);
- return resolveAmbiguities(ambs.getFirst());
+ return firstOption;
}
}
private static void reportUnresolvedAmb(ATermList ambs) {
Debug.log("Ambiguity found during implosion: ");
for (ATerm amb : ambs) {
String ambString = amb.toString();
if (ambString.length() > 1000) ambString = ambString.substring(0, 1000) + "...";
Debug.log(" amb: ", ambString);
}
}
/** Get the token after the previous node's ending token, or null if N/A. */
private IToken getStartToken(IToken prevToken) {
PrsStream parseStream = tokenizer.getParseStream();
if (prevToken == null) {
return parseStream.getSize() == 0 ? null
: parseStream.getTokenAt(0);
} else {
int index = prevToken.getTokenIndex();
if (parseStream.getSize() - index <= 1) {
// Create new empty token
// HACK: Assume TK_LAYOUT kind for empty tokens in AST nodes
return tokenizer.makeToken(offset, TK_LAYOUT, true);
} else {
return parseStream.getTokenAt(index + 1);
}
}
}
/** Get the last no-layout token for an AST node. */
private IToken getEndToken(IToken startToken, IToken lastToken) {
PrsStream parseStream = tokenizer.getParseStream();
int begin = startToken.getTokenIndex();
for (int i = lastToken.getTokenIndex(); i > begin; i--) {
lastToken = parseStream.getTokenAt(i);
if (lastToken.getKind() != TK_LAYOUT.ordinal()
|| lastToken.getStartOffset() == lastToken.getEndOffset()-1)
break;
}
return lastToken;
}
/** Implode any appl(_, _) that constructs a lex terminal. */
protected void implodeLexical(ATermInt character) {
assert tokenizer.getLexStream().getInputChars().length > offset
&& character.getInt() == tokenizer.getLexStream().getCharValue(offset)
: "Character from asfix stream (" + character.getInt()
+ ") must be in lex stream ("
+ (tokenizer.getLexStream().getInputChars().length > offset
? (int) tokenizer.getLexStream().getCharValue(offset)
: "???") + ")";
offset++;
}
}
| false | true | protected ATermAppl resolveAmbiguities(final ATerm node) {
if (!"amb".equals(((ATermAppl) node).getName()))
return (ATermAppl) node;
final ATermListImpl ambs = termAt(node, 0);
ATermAppl lastNonAvoid = null;
boolean multipleNonAvoids = false;
alts:
for (int i = 0; i < ambs.getLength(); i++) {
ATermAppl prod = resolveAmbiguities(termAt(ambs, i));
ATermAppl appl = termAt(prod, APPL_PROD);
ATermAppl attrs = termAt(appl, PROD_ATTRS);
if ("attrs".equals(attrs.getName())) {
ATermList attrList = termAt(attrs, 0);
for (int j = 0; j < attrList.getLength(); j++) {
ATerm attr = termAt(attrList, j);
if (isAppl(attr) && "prefer".equals(asAppl(attr).getName())) {
return resolveAmbiguities(prod);
} else if (isAppl(attr) && "avoid".equals(asAppl(attr).getName())) {
continue alts;
}
}
if (lastNonAvoid == null) {
lastNonAvoid = prod;
} else {
multipleNonAvoids = true;
}
}
}
if (!multipleNonAvoids) {
return lastNonAvoid != null ? lastNonAvoid : applAt(ambs, 0);
} else {
if (Debug.ENABLED && !lexicalContext) reportUnresolvedAmb(ambs);
return resolveAmbiguities(ambs.getFirst());
}
}
| protected ATermAppl resolveAmbiguities(final ATerm node) {
if (!"amb".equals(((ATermAppl) node).getName()))
return (ATermAppl) node;
final ATermListImpl ambs = termAt(node, 0);
ATermAppl lastNonAvoid = null;
ATermAppl firstOption = null;
boolean multipleNonAvoids = false;
alts:
for (int i = 0; i < ambs.getLength(); i++) {
ATermAppl prod = resolveAmbiguities(termAt(ambs, i));
if (firstOption == null) firstOption = prod;
ATermAppl appl = termAt(prod, APPL_PROD);
ATermAppl attrs = termAt(appl, PROD_ATTRS);
if ("attrs".equals(attrs.getName())) {
ATermList attrList = termAt(attrs, 0);
for (int j = 0; j < attrList.getLength(); j++) {
ATerm attr = termAt(attrList, j);
if (isAppl(attr) && "prefer".equals(asAppl(attr).getName())) {
return prod;
} else if (isAppl(attr) && "avoid".equals(asAppl(attr).getName())) {
continue alts;
}
}
if (lastNonAvoid == null) {
lastNonAvoid = prod;
} else {
multipleNonAvoids = true;
}
}
}
if (!multipleNonAvoids) {
return lastNonAvoid != null ? lastNonAvoid : firstOption;
} else {
if (Debug.ENABLED && !lexicalContext) reportUnresolvedAmb(ambs);
return firstOption;
}
}
|
diff --git a/src/com/jpii/navalbattle/pavo/ProceduralLayeredMapGenerator.java b/src/com/jpii/navalbattle/pavo/ProceduralLayeredMapGenerator.java
index 97483de4..5aca38cb 100644
--- a/src/com/jpii/navalbattle/pavo/ProceduralLayeredMapGenerator.java
+++ b/src/com/jpii/navalbattle/pavo/ProceduralLayeredMapGenerator.java
@@ -1,236 +1,236 @@
/*
* Copyright (C) 2012 JPII and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jpii.navalbattle.pavo;
import maximusvladimir.dagen.Perlin;
import maximusvladimir.dagen.Rand;
/**
* Procedural-layer map generator for Pavo
*/
public class ProceduralLayeredMapGenerator {
private static $JSNAO9JW10SKJF194OI[] json;
private static Rand rand = Game.Settings.rand;
public static final int RIVERSIZE = 1024;
static {
doInit();
}
private static void doInit() {
berlin = new Perlin(Game.Settings.seed,0,0);
json = new $JSNAO9JW10SKJF194OI[15];
for (int c = 0; c < json.length; c++) {
json[c] = new $JSNAO9JW10SKJF194OI(PavoHelper.getGameWidth(WorldSize.WORLD_LARGE)*32,
PavoHelper.getGameHeight(WorldSize.WORLD_LARGE)*32);
}
}
private static Perlin berlin;
public static byte getValidHouse(int x, int z) {
return 0;
}
public static float getPointSafe(float x, float z) {
float lvl0 = getLevel0(x,z);
float lvl0b = getLevel0(z-512,x-512);
float lvl2 = getLevel2(x,z);
float lvl3 = getLevel3(x,z);
float lvl4 = getLevel4(x,z);
float lvl9 = getLevel9(x,z);
double mixer = (((lvl0*26.76f)+(lvl4*3.9f)+
(lvl2)+(lvl3)) * 0.03053435114503816793893129770992) + (lvl2*0.02);
double mixed = (((mixer+1)*0.5)-0.1);
//if (mixed > 0.57)
//mixed += 0.19;
float res = (float)((mixed - 0.3)*4.7619047619147619047619047619048) - 0.08f;
// NBBN
res = res * 0.5952f;
if (res >= 0.40 && res <= 0.55) {
float nb=(lvl9 * 0.02f);
if (nb > 0.0f && nb < 0.02f)
res += nb;
}
//else if (res >= 0.40)
//res += Game.Settings.rand.nextFloat(0.1f,0.3f);//(lvl9 * 0.13233f);
if (res >= 0.45) {
//float yn= (lvl0b * 0.545f) + (lvl9 * 0.12f);
float yn = ((res - 0.45f) * 1.75f) + (lvl0b * 0.2f);///Game.Settings.rand.nextFloat(0.2f,0.5f);
//System.out.println("g"+yn);
res += yn;
}
if (res < 0.2)
res += (lvl4+lvl0) * 0.081f;
// NBBN
if (res > 1)
res = 1;
if (res < 0)
res = 0;
return res;
}
public static float getPoint(float x, float z) {
float lvl0 = getLevel0(x,z);
float lvl0b = getLevel0(z-512,x-512);
float lvl2 = getLevel2(x,z);
float lvl3 = getLevel3(x,z);
float lvl4 = getLevel4(x,z);
float lvl9 = getLevel9(x,z);
double mixer = (((lvl0*26.76f)+(lvl4*3.9f)+
(lvl2)+(lvl3)) * 0.03053435114503816793893129770992) + (lvl2*0.02);
double mixed = (((mixer+1)*0.5)-0.1);
- mixed = ((mixed * 95.0) + (berlin.noise1((x*z)+z)*5.0))/100.0;
+ mixed = ((mixed * 60.0) + (berlin.noise1((x*z)+z)*40.0))/100.0;
//if (mixed > 0.57)
//mixed += 0.19;
float res = (float)((mixed - 0.3)*4.7619047619147619047619047619048) - 0.08f;
// NBBN
res = res * 0.5952f;
if (res >= 0.40 && res <= 0.55) {
float nb=(lvl9 * 0.02f);
if (nb > 0.0f && nb < 0.02f)
res += nb;
}
//else if (res >= 0.40)
//res += Game.Settings.rand.nextFloat(0.1f,0.3f);//(lvl9 * 0.13233f);
if (res >= 0.45) {
//float yn= (lvl0b * 0.545f) + (lvl9 * 0.12f);
float yn = ((res - 0.45f) * 1.75f) + (lvl0b * 0.2f);///Game.Settings.rand.nextFloat(0.2f,0.5f);
//System.out.println("g"+yn);
res += yn;
}
if (res < 0.2)
res += (lvl4+lvl0) * 0.081f;
// NBBN
if (res > 1)
res = 1;
if (res < 0)
res = 0;
if (blitRiver(x,z) && res > 0.4){
res = res * 0.3f;
if (res < 0.15f)
res += rand.nextDouble() * 0.15f;
if (res > 1)
res = 1;
if (res < 0)
res = 0;
}
//System.err.println(x + "," + z + ":" + res);
//float navalbattlesnapleft = 0.0f;
//float navalbattlesnapright = 0.7f;
return res;
}
private static float ld0 = 1024;
private static float ld2 = 32;
private static float ld3 = 64;
private static float ld4 = 512;
private static boolean blitRiver(float x, float z) {
for (int v = 0; v < json.length; v++) {
int cx = (int) (x - json[v].TInaOAJNqi0930142);
int cy = (int) (z - json[v].TIXXXXX93jOfna91);
if (cx < RIVERSIZE && cy < RIVERSIZE && cx >= 0 && cy >= 0) {
return json[v].c(cx,cy);
}
}
return false;
}
private static float getLevel0(float x, float z) {
return berlin.noise(x/ld0, z/ld0);
}
private static float getLevel2(float x, float z) {
return berlin.noise(x/ld2,z/ld2);
}
private static float getLevel3(float x, float z) {
return berlin.noise(x/ld3,z/ld3);
}
private static float getLevel4(float x, float z) {
return berlin.noise(x/ld4,z/ld4);
}
private static float getLevel9(float x, float z) {
return berlin.noise(x/16,z/16);
}
}
class $kdOWj20Janro2 {
public int x, z;
public byte size;
public $kdOWj20Janro2() {
}
}
class $JSNAO9JW10SKJF194OI {
private Rand r;
public boolean[][] ASOGLICAL_9201;
public int TInaOAJNqi0930142, TIXXXXX93jOfna91;
public $JSNAO9JW10SKJF194OI(int LEEsiILIE, int PLwmajwifKW) {
____b(PLwmajwifKW,LEEsiILIE);
try {
Thread.sleep(1);
} catch (Throwable t) {
}
a();
}
public void ____b(int UJ4DNw92IF34JAOfn29jnr0n, int JFNaoiwu2OAnq29nf) {
r = Game.Settings.rand;
boolean ghnIAn = false;
int Ienw = 0;
while (!ghnIAn && Ienw++ < 175) {
TInaOAJNqi0930142 = r.nextInt(0,JFNaoiwu2OAnq29nf);
TIXXXXX93jOfna91 = r.nextInt(0,UJ4DNw92IF34JAOfn29jnr0n);
if (ProceduralLayeredMapGenerator.getPointSafe(TInaOAJNqi0930142, TIXXXXX93jOfna91) > 0.4f)
ghnIAn = true;
}
ASOGLICAL_9201 = new boolean[ProceduralLayeredMapGenerator.RIVERSIZE][ProceduralLayeredMapGenerator.RIVERSIZE];
}
private void a() {
int lastx = ProceduralLayeredMapGenerator.RIVERSIZE/2;
int lasty = ProceduralLayeredMapGenerator.RIVERSIZE/2;
for (int y = 0; y < (ProceduralLayeredMapGenerator.RIVERSIZE/3)*2; y++) {
int dx = -1;
while (dx < 0 || dx >= ProceduralLayeredMapGenerator.RIVERSIZE)
dx = lastx+r.nextInt(-1,3);
int dy = -1;
while (dy < 0 || dy >= ProceduralLayeredMapGenerator.RIVERSIZE)
dy = lasty+r.nextInt(-1,3);
f(dx,dy);
lastx = dx;
lasty = dy;
}
}
private void f(int cx, int cy) {
ASOGLICAL_9201[cx][cy] = true;
if (cx >= 2 && cx < ProceduralLayeredMapGenerator.RIVERSIZE - 2 && cy >= 2 && cy < ProceduralLayeredMapGenerator.RIVERSIZE - 2) {
ASOGLICAL_9201[cx-1][cy-1] = true;
ASOGLICAL_9201[cx+1][cy-1] = true;
ASOGLICAL_9201[cx-1][cy+1] = true;
ASOGLICAL_9201[cx+1][cy+1] = true;
ASOGLICAL_9201[cx-1][cy] = true;
ASOGLICAL_9201[cx+1][cy] = true;
ASOGLICAL_9201[cx][cy+1] = true;
ASOGLICAL_9201[cx][cy-1] = true;
}
}
public boolean c(int CKasnaOwn, int USJaimw) {
return ASOGLICAL_9201[CKasnaOwn][USJaimw];
}
}
| true | true | public static float getPoint(float x, float z) {
float lvl0 = getLevel0(x,z);
float lvl0b = getLevel0(z-512,x-512);
float lvl2 = getLevel2(x,z);
float lvl3 = getLevel3(x,z);
float lvl4 = getLevel4(x,z);
float lvl9 = getLevel9(x,z);
double mixer = (((lvl0*26.76f)+(lvl4*3.9f)+
(lvl2)+(lvl3)) * 0.03053435114503816793893129770992) + (lvl2*0.02);
double mixed = (((mixer+1)*0.5)-0.1);
mixed = ((mixed * 95.0) + (berlin.noise1((x*z)+z)*5.0))/100.0;
//if (mixed > 0.57)
//mixed += 0.19;
float res = (float)((mixed - 0.3)*4.7619047619147619047619047619048) - 0.08f;
// NBBN
res = res * 0.5952f;
if (res >= 0.40 && res <= 0.55) {
float nb=(lvl9 * 0.02f);
if (nb > 0.0f && nb < 0.02f)
res += nb;
}
//else if (res >= 0.40)
//res += Game.Settings.rand.nextFloat(0.1f,0.3f);//(lvl9 * 0.13233f);
if (res >= 0.45) {
//float yn= (lvl0b * 0.545f) + (lvl9 * 0.12f);
float yn = ((res - 0.45f) * 1.75f) + (lvl0b * 0.2f);///Game.Settings.rand.nextFloat(0.2f,0.5f);
//System.out.println("g"+yn);
res += yn;
}
if (res < 0.2)
res += (lvl4+lvl0) * 0.081f;
// NBBN
if (res > 1)
res = 1;
if (res < 0)
res = 0;
if (blitRiver(x,z) && res > 0.4){
res = res * 0.3f;
if (res < 0.15f)
res += rand.nextDouble() * 0.15f;
if (res > 1)
res = 1;
if (res < 0)
res = 0;
}
//System.err.println(x + "," + z + ":" + res);
//float navalbattlesnapleft = 0.0f;
//float navalbattlesnapright = 0.7f;
return res;
}
| public static float getPoint(float x, float z) {
float lvl0 = getLevel0(x,z);
float lvl0b = getLevel0(z-512,x-512);
float lvl2 = getLevel2(x,z);
float lvl3 = getLevel3(x,z);
float lvl4 = getLevel4(x,z);
float lvl9 = getLevel9(x,z);
double mixer = (((lvl0*26.76f)+(lvl4*3.9f)+
(lvl2)+(lvl3)) * 0.03053435114503816793893129770992) + (lvl2*0.02);
double mixed = (((mixer+1)*0.5)-0.1);
mixed = ((mixed * 60.0) + (berlin.noise1((x*z)+z)*40.0))/100.0;
//if (mixed > 0.57)
//mixed += 0.19;
float res = (float)((mixed - 0.3)*4.7619047619147619047619047619048) - 0.08f;
// NBBN
res = res * 0.5952f;
if (res >= 0.40 && res <= 0.55) {
float nb=(lvl9 * 0.02f);
if (nb > 0.0f && nb < 0.02f)
res += nb;
}
//else if (res >= 0.40)
//res += Game.Settings.rand.nextFloat(0.1f,0.3f);//(lvl9 * 0.13233f);
if (res >= 0.45) {
//float yn= (lvl0b * 0.545f) + (lvl9 * 0.12f);
float yn = ((res - 0.45f) * 1.75f) + (lvl0b * 0.2f);///Game.Settings.rand.nextFloat(0.2f,0.5f);
//System.out.println("g"+yn);
res += yn;
}
if (res < 0.2)
res += (lvl4+lvl0) * 0.081f;
// NBBN
if (res > 1)
res = 1;
if (res < 0)
res = 0;
if (blitRiver(x,z) && res > 0.4){
res = res * 0.3f;
if (res < 0.15f)
res += rand.nextDouble() * 0.15f;
if (res > 1)
res = 1;
if (res < 0)
res = 0;
}
//System.err.println(x + "," + z + ":" + res);
//float navalbattlesnapleft = 0.0f;
//float navalbattlesnapright = 0.7f;
return res;
}
|
diff --git a/src/org/group1f/izuna/GameComponents/Enemy.java b/src/org/group1f/izuna/GameComponents/Enemy.java
index 9e75c7c..c593695 100644
--- a/src/org/group1f/izuna/GameComponents/Enemy.java
+++ b/src/org/group1f/izuna/GameComponents/Enemy.java
@@ -1,113 +1,113 @@
package org.group1f.izuna.GameComponents;
import java.awt.Point;
import org.group1f.izuna.GameComponents.Drawing.*;
public class Enemy extends AIControllable implements SpaceShip {
private String weaponKey;
private boolean isDying;
private Animation rollLeft;
private Animation rollRight;
private SoundEffect enteringSound;
private int health;
private float oldvY = 0.0f;
private boolean isRFinished = true;
public Enemy(Animation still, Animation rollLeft, Animation rollRight, SoundEffect enteringSound) {
super(null, still);
this.rollLeft = rollLeft;
this.rollRight = rollRight;
this.enteringSound = enteringSound;
isDying = false;
}
public Enemy clone() {
return null;
}
@Override
public void checkStateToAnimate() {
Animation newAnim = currentAnimation;
if (!isRFinished) {
isRFinished = currentAnimation.finished();
}
if (getvY() < 0) {
if (oldvY > 0) { //
isRFinished = currentAnimation.refine();
} else {
newAnim = rollLeft;
- // rollSound.play();
+ rollSound.play();
}
} else if (getvY() > 0) {
if (oldvY < 0) { //
isRFinished = currentAnimation.refine();
} else {
newAnim = rollRight;
- // rollSound.play();
+ rollSound.play();
}
} else { // vy = 0
if (getvY() != 0) {
isRFinished = currentAnimation.refine();
} else {
newAnim = getStillAnimation();
}
}
if (health < 1) {
setState();
if (!isDying) {
- // super.getDieSound().play(); // Current sound a bunu eşitleyip çalmanın pek farkı yok
+ getDieSound().play();
}
isDying = true;
}
if (isDying && currentAnimation.getElapsedTime() >= getDieTime()) {
setVisible(false);
}
if (isRFinished && currentAnimation != newAnim) {
currentAnimation = newAnim;
currentAnimation.startOver();
}
oldvY = getvY();
}
@Override
public void update(long elapsedTime) {
checkStateToAnimate();
super.update(elapsedTime);
}
private void setState() {
if (health < 1) {
setvX(0.0f);
setvY(0.0f);
}
}
@Override
public int getDieTime() {
return 1000;
}
@Override
public void setHealth(int newValue) {
if (newValue > 100) {
health = 100;
} else {
health = newValue;
}
}
@Override
public int getHealth() {
return health;
}
@Override
public float getMaxSpeed() {
return 1.0f;
}
}
| false | true | public void checkStateToAnimate() {
Animation newAnim = currentAnimation;
if (!isRFinished) {
isRFinished = currentAnimation.finished();
}
if (getvY() < 0) {
if (oldvY > 0) { //
isRFinished = currentAnimation.refine();
} else {
newAnim = rollLeft;
// rollSound.play();
}
} else if (getvY() > 0) {
if (oldvY < 0) { //
isRFinished = currentAnimation.refine();
} else {
newAnim = rollRight;
// rollSound.play();
}
} else { // vy = 0
if (getvY() != 0) {
isRFinished = currentAnimation.refine();
} else {
newAnim = getStillAnimation();
}
}
if (health < 1) {
setState();
if (!isDying) {
// super.getDieSound().play(); // Current sound a bunu eşitleyip çalmanın pek farkı yok
}
isDying = true;
}
if (isDying && currentAnimation.getElapsedTime() >= getDieTime()) {
setVisible(false);
}
if (isRFinished && currentAnimation != newAnim) {
currentAnimation = newAnim;
currentAnimation.startOver();
}
oldvY = getvY();
}
| public void checkStateToAnimate() {
Animation newAnim = currentAnimation;
if (!isRFinished) {
isRFinished = currentAnimation.finished();
}
if (getvY() < 0) {
if (oldvY > 0) { //
isRFinished = currentAnimation.refine();
} else {
newAnim = rollLeft;
rollSound.play();
}
} else if (getvY() > 0) {
if (oldvY < 0) { //
isRFinished = currentAnimation.refine();
} else {
newAnim = rollRight;
rollSound.play();
}
} else { // vy = 0
if (getvY() != 0) {
isRFinished = currentAnimation.refine();
} else {
newAnim = getStillAnimation();
}
}
if (health < 1) {
setState();
if (!isDying) {
getDieSound().play();
}
isDying = true;
}
if (isDying && currentAnimation.getElapsedTime() >= getDieTime()) {
setVisible(false);
}
if (isRFinished && currentAnimation != newAnim) {
currentAnimation = newAnim;
currentAnimation.startOver();
}
oldvY = getvY();
}
|
diff --git a/dslab2/src/at/ac/tuwien/dslab2/service/loadTest/AuctionBiddingHandler.java b/dslab2/src/at/ac/tuwien/dslab2/service/loadTest/AuctionBiddingHandler.java
index 5322235..fe79561 100644
--- a/dslab2/src/at/ac/tuwien/dslab2/service/loadTest/AuctionBiddingHandler.java
+++ b/dslab2/src/at/ac/tuwien/dslab2/service/loadTest/AuctionBiddingHandler.java
@@ -1,74 +1,75 @@
package at.ac.tuwien.dslab2.service.loadTest;
import at.ac.tuwien.dslab2.service.biddingClient.BiddingClientService;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Pattern;
public class AuctionBiddingHandler extends TimerTask {
private final BiddingClientService biddingClientService;
private final long currentTime;
private final BlockingQueue<String> listQueue;
private final BlockingQueue<String> biddingQueue;
private Thread timerThread;
private final TimerNotifications timerNotifications;
private Random random;
public AuctionBiddingHandler(BiddingClientService biddingClientService, BlockingQueue<String> listQueue, BlockingQueue<String> biddingQueue, TimerNotifications timerNotifications, Random random) throws IOException {
this.biddingClientService = biddingClientService;
this.listQueue = listQueue;
this.biddingQueue = biddingQueue;
this.currentTime = System.currentTimeMillis();
this.timerNotifications = timerNotifications;
this.random = random;
}
@Override
public void run() {
try {
this.timerThread = Thread.currentThread();
biddingClientService.submitCommand("!list");
String reply = listQueue.take();
Scanner scanner = new Scanner(reply.trim());
scanner.useDelimiter(Pattern.compile("\\.\\s+.*\\n?\\s*"));
scanner.skip(Pattern.compile("\\s*"));
List<Integer> auctions = new ArrayList<Integer>();
double price = (System.currentTimeMillis() - currentTime) / 1000;
while (scanner.hasNextInt()) {
int auctionId = scanner.nextInt();
auctions.add(auctionId);
}
int index = 0;
//here special case because random.nextInt(0)
//would throw IllegalArgumentException
if (auctions.size() > 1) {
index = random.nextInt(auctions.size() - 1);
}
int auctionId = auctions.get(index);
biddingClientService.submitCommand("!bid " + auctionId + " " + String.format("%.2f", price));
String response = biddingQueue.take();
this.timerNotifications.newBid(response);
- } catch (Exception e) {
+ } catch (InterruptedException ignored) {
+ } catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean cancel() {
if (this.timerThread != null && this.timerThread.isAlive()) {
this.timerThread.interrupt();
}
return super.cancel();
}
}
| true | true | public void run() {
try {
this.timerThread = Thread.currentThread();
biddingClientService.submitCommand("!list");
String reply = listQueue.take();
Scanner scanner = new Scanner(reply.trim());
scanner.useDelimiter(Pattern.compile("\\.\\s+.*\\n?\\s*"));
scanner.skip(Pattern.compile("\\s*"));
List<Integer> auctions = new ArrayList<Integer>();
double price = (System.currentTimeMillis() - currentTime) / 1000;
while (scanner.hasNextInt()) {
int auctionId = scanner.nextInt();
auctions.add(auctionId);
}
int index = 0;
//here special case because random.nextInt(0)
//would throw IllegalArgumentException
if (auctions.size() > 1) {
index = random.nextInt(auctions.size() - 1);
}
int auctionId = auctions.get(index);
biddingClientService.submitCommand("!bid " + auctionId + " " + String.format("%.2f", price));
String response = biddingQueue.take();
this.timerNotifications.newBid(response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
| public void run() {
try {
this.timerThread = Thread.currentThread();
biddingClientService.submitCommand("!list");
String reply = listQueue.take();
Scanner scanner = new Scanner(reply.trim());
scanner.useDelimiter(Pattern.compile("\\.\\s+.*\\n?\\s*"));
scanner.skip(Pattern.compile("\\s*"));
List<Integer> auctions = new ArrayList<Integer>();
double price = (System.currentTimeMillis() - currentTime) / 1000;
while (scanner.hasNextInt()) {
int auctionId = scanner.nextInt();
auctions.add(auctionId);
}
int index = 0;
//here special case because random.nextInt(0)
//would throw IllegalArgumentException
if (auctions.size() > 1) {
index = random.nextInt(auctions.size() - 1);
}
int auctionId = auctions.get(index);
biddingClientService.submitCommand("!bid " + auctionId + " " + String.format("%.2f", price));
String response = biddingQueue.take();
this.timerNotifications.newBid(response);
} catch (InterruptedException ignored) {
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/luciddb/test/src/com/lucidera/luciddb/test/udr/TestRemoteRowsUDX.java b/luciddb/test/src/com/lucidera/luciddb/test/udr/TestRemoteRowsUDX.java
index 02a812e76..0bc595727 100644
--- a/luciddb/test/src/com/lucidera/luciddb/test/udr/TestRemoteRowsUDX.java
+++ b/luciddb/test/src/com/lucidera/luciddb/test/udr/TestRemoteRowsUDX.java
@@ -1,324 +1,334 @@
/*
// $Id$
// Farrago is an extensible data management system.
// Copyright (C) 2006-2007 LucidEra, Inc.
// Copyright (C) 2006-2007 The Eigenbase Project
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.lucidera.luciddb.test.udr;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.zip.GZIPOutputStream;
import org.luciddb.test.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.jdbc.*;
import net.sf.farrago.test.*;
import net.sf.farrago.util.*;
import org.eigenbase.util.property.*;
import com.lucidera.luciddb.test.udr.SQLRunner;
/**
* LucidDB JDBC test for testing Remote rows UDX.
*
* @author Ray Zhang
*
*/
public class TestRemoteRowsUDX
extends FarragoTestCase
{
//~ Constructors -----------------------------------------------------------
public TestRemoteRowsUDX(String testname)
throws Exception
{
super(testname);
}
//~ Methods ----------------------------------------------------------------
public void setUp()
throws Exception
{
// TODO jvs 12-Jun-2010: factor out common test harness code
// from wherever this was copied from.
// Set the properties so the LucidDB session factory and LucidDB data
// files are used. The LucidDB data files need to be used; otherwise,
// we won't use versioned data segment pages.
//
// REVIEW zfong 7/11/08 - Is there a better way of doing this?
FarragoProperties farragoPropInstance = FarragoProperties.instance();
StringProperty sessionFactory =
farragoPropInstance.defaultSessionFactoryLibraryName;
System.setProperty(
sessionFactory.getPath(),
"class:org.luciddb.session.LucidDbSessionFactory");
String homeDirString = farragoPropInstance.homeDir.get(true);
String catalogDir = homeDirString + "/../luciddb/catalog";
farragoPropInstance.catalogDir.set(catalogDir);
// Create a new connection so we're sure we have the right session
// factory and db
if (connection != null) {
connection.close();
}
connection = newConnection();
repos = getSession().getRepos();
saveParameters();
runCleanup();
super.setUp();
}
public static void runCleanup()
throws Exception
{
// Use the special LucidDB cleanup factory to avoid dropping schemas
// like APPLIB
FarragoTestCase.CleanupFactory.setFactory(new LucidDbCleanupFactory());
FarragoTestCase.runCleanup();
}
public void tearDown()
throws Exception
{
// Close the connection created by this test.
if (connection != null) {
connection.close();
connection = null;
}
}
public void testRemoteRowsUDX()
throws Exception
{
final String driverURI = "jdbc:luciddb:";
FarragoAbstractJdbcDriver driver =
FarragoTestCase.newJdbcEngineDriver();
Properties props = newProperties();
//Create a test table.
Connection conn = driver.connect(driverURI, props);
Statement stmt = conn.createStatement();
stmt.executeUpdate("create schema s");
stmt.executeUpdate("set schema 's'");
stmt.executeUpdate("create table t(id int, name varchar(255),is_married boolean)");
stmt.close();
conn.close();
// Case1: Header mismatch
conn = driver.connect(driverURI, props);
PreparedStatement ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,FALSE) " + ")");
SQLRunner runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
Socket client = new Socket("localhost", 7778);
ObjectOutputStream objOut = new ObjectOutputStream(
client.getOutputStream());
List<Object> header = new ArrayList<Object>();
header.add("1"); // version
List format = new ArrayList();
+ // KS 10-APR-2011
+ // The "Mismatch" here is on types, but the RemoteRowsUDX only checks
+ // for column count. Thus the final STRING is what triggers the
+ // mismatch as of this date.
+ // Also, the indexOf message match below was initially wrong with what
+ // the UDX produces.
format.add("STRING"); // Mismatch
format.add("STRING");
format.add("BOOLEAN");
+ format.add("STRING"); // mismatched columns
header.add(format);
objOut.writeObject(header);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
String errorMsg = runner.getErrorMsg();
+ if (errorMsg == null) {
+ errorMsg = "";
+ }
boolean test = false;
- if(errorMsg.indexOf("Header Info was unmatched")!=-1){
+ if(errorMsg.indexOf("Header Mismatch:")!=-1){
test = true;
}
assertTrue("Header mismatch test is not passed: ",test);
//Case2: Bad objects sent across (wrong datatypes in actual rows)
conn = driver.connect(driverURI, props);
ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,FALSE) " + ")");
runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
client = new Socket("localhost", 7778);
objOut = new ObjectOutputStream(
client.getOutputStream());
header = new ArrayList<Object>();
header.add("1"); // version
format = new ArrayList();
format.add("INTEGER");
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.reset();
objOut.flush();
List<Object> list = new ArrayList<Object>();
list.add("Test1"); // wrong type.
list.add(111); // wrong type.
list.add(true);
objOut.writeObject(list);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
errorMsg = runner.getErrorMsg();
test = false;
if(errorMsg.indexOf("Value 'Test1' cannot be converted to parameter of type INTEGER")!=-1){
test = true;
}
assertTrue("Bad objects sent across: ",test);
//Casee3: Compress stream
conn = driver.connect(driverURI, props);
ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,TRUE) " + ")"); // TRUE
runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
client = new Socket("localhost", 7778);
GZIPOutputStream gzOut = new GZIPOutputStream(client.getOutputStream());
objOut = new ObjectOutputStream(
gzOut);
header = new ArrayList<Object>();
header.add("1"); // version
format = new ArrayList();
format.add("INTEGER");
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.reset();
objOut.flush();
list = new ArrayList<Object>();
list.add(111);
list.add("Test1");
list.add(true);
objOut.writeObject(list);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
errorMsg = runner.getErrorMsg();
test = false;
if(errorMsg == null){
test = true;
}
assertTrue("Compress stream test is not passed: ",test);
//Case4: Premature end of stream (cancel object stream)
//Case5: Unique constraints on server (ie, server based exception on JDBC connection)
}
/**
* Creates test connection properties.
*/
private static Properties newProperties()
{
Properties props = new Properties();
props.put("user", FarragoCatalogInit.SA_USER_NAME);
props.put("password", "");
return props;
}
/**
* Cleanup factory that uses LucidDbTestCleanup
*/
private static class LucidDbCleanupFactory
extends FarragoTestCase.CleanupFactory
{
public Cleanup newCleanup(String name)
throws Exception
{
return new LucidDbTestCleanup(connection);
}
}
}
// End LucidDbJdbcLabelTest.java
| false | true | public void testRemoteRowsUDX()
throws Exception
{
final String driverURI = "jdbc:luciddb:";
FarragoAbstractJdbcDriver driver =
FarragoTestCase.newJdbcEngineDriver();
Properties props = newProperties();
//Create a test table.
Connection conn = driver.connect(driverURI, props);
Statement stmt = conn.createStatement();
stmt.executeUpdate("create schema s");
stmt.executeUpdate("set schema 's'");
stmt.executeUpdate("create table t(id int, name varchar(255),is_married boolean)");
stmt.close();
conn.close();
// Case1: Header mismatch
conn = driver.connect(driverURI, props);
PreparedStatement ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,FALSE) " + ")");
SQLRunner runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
Socket client = new Socket("localhost", 7778);
ObjectOutputStream objOut = new ObjectOutputStream(
client.getOutputStream());
List<Object> header = new ArrayList<Object>();
header.add("1"); // version
List format = new ArrayList();
format.add("STRING"); // Mismatch
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
String errorMsg = runner.getErrorMsg();
boolean test = false;
if(errorMsg.indexOf("Header Info was unmatched")!=-1){
test = true;
}
assertTrue("Header mismatch test is not passed: ",test);
//Case2: Bad objects sent across (wrong datatypes in actual rows)
conn = driver.connect(driverURI, props);
ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,FALSE) " + ")");
runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
client = new Socket("localhost", 7778);
objOut = new ObjectOutputStream(
client.getOutputStream());
header = new ArrayList<Object>();
header.add("1"); // version
format = new ArrayList();
format.add("INTEGER");
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.reset();
objOut.flush();
List<Object> list = new ArrayList<Object>();
list.add("Test1"); // wrong type.
list.add(111); // wrong type.
list.add(true);
objOut.writeObject(list);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
errorMsg = runner.getErrorMsg();
test = false;
if(errorMsg.indexOf("Value 'Test1' cannot be converted to parameter of type INTEGER")!=-1){
test = true;
}
assertTrue("Bad objects sent across: ",test);
//Casee3: Compress stream
conn = driver.connect(driverURI, props);
ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,TRUE) " + ")"); // TRUE
runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
client = new Socket("localhost", 7778);
GZIPOutputStream gzOut = new GZIPOutputStream(client.getOutputStream());
objOut = new ObjectOutputStream(
gzOut);
header = new ArrayList<Object>();
header.add("1"); // version
format = new ArrayList();
format.add("INTEGER");
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.reset();
objOut.flush();
list = new ArrayList<Object>();
list.add(111);
list.add("Test1");
list.add(true);
objOut.writeObject(list);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
errorMsg = runner.getErrorMsg();
test = false;
if(errorMsg == null){
test = true;
}
assertTrue("Compress stream test is not passed: ",test);
//Case4: Premature end of stream (cancel object stream)
//Case5: Unique constraints on server (ie, server based exception on JDBC connection)
}
| public void testRemoteRowsUDX()
throws Exception
{
final String driverURI = "jdbc:luciddb:";
FarragoAbstractJdbcDriver driver =
FarragoTestCase.newJdbcEngineDriver();
Properties props = newProperties();
//Create a test table.
Connection conn = driver.connect(driverURI, props);
Statement stmt = conn.createStatement();
stmt.executeUpdate("create schema s");
stmt.executeUpdate("set schema 's'");
stmt.executeUpdate("create table t(id int, name varchar(255),is_married boolean)");
stmt.close();
conn.close();
// Case1: Header mismatch
conn = driver.connect(driverURI, props);
PreparedStatement ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,FALSE) " + ")");
SQLRunner runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
Socket client = new Socket("localhost", 7778);
ObjectOutputStream objOut = new ObjectOutputStream(
client.getOutputStream());
List<Object> header = new ArrayList<Object>();
header.add("1"); // version
List format = new ArrayList();
// KS 10-APR-2011
// The "Mismatch" here is on types, but the RemoteRowsUDX only checks
// for column count. Thus the final STRING is what triggers the
// mismatch as of this date.
// Also, the indexOf message match below was initially wrong with what
// the UDX produces.
format.add("STRING"); // Mismatch
format.add("STRING");
format.add("BOOLEAN");
format.add("STRING"); // mismatched columns
header.add(format);
objOut.writeObject(header);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
String errorMsg = runner.getErrorMsg();
if (errorMsg == null) {
errorMsg = "";
}
boolean test = false;
if(errorMsg.indexOf("Header Mismatch:")!=-1){
test = true;
}
assertTrue("Header mismatch test is not passed: ",test);
//Case2: Bad objects sent across (wrong datatypes in actual rows)
conn = driver.connect(driverURI, props);
ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,FALSE) " + ")");
runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
client = new Socket("localhost", 7778);
objOut = new ObjectOutputStream(
client.getOutputStream());
header = new ArrayList<Object>();
header.add("1"); // version
format = new ArrayList();
format.add("INTEGER");
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.reset();
objOut.flush();
List<Object> list = new ArrayList<Object>();
list.add("Test1"); // wrong type.
list.add(111); // wrong type.
list.add(true);
objOut.writeObject(list);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
errorMsg = runner.getErrorMsg();
test = false;
if(errorMsg.indexOf("Value 'Test1' cannot be converted to parameter of type INTEGER")!=-1){
test = true;
}
assertTrue("Bad objects sent across: ",test);
//Casee3: Compress stream
conn = driver.connect(driverURI, props);
ps = conn.prepareStatement(
"insert into s.t " +
"select * from table( "
+ "APPLIB.REMOTE_ROWS(cursor( "
+ "select cast(null as int) as id, cast(null as varchar(255)) as name, "
+ "cast(null as boolean) as is_married " + "from (values(0)) "
+ "),7778,TRUE) " + ")"); // TRUE
runner = new SQLRunner(ps);
runner.start();
Thread.sleep(5000);
client = new Socket("localhost", 7778);
GZIPOutputStream gzOut = new GZIPOutputStream(client.getOutputStream());
objOut = new ObjectOutputStream(
gzOut);
header = new ArrayList<Object>();
header.add("1"); // version
format = new ArrayList();
format.add("INTEGER");
format.add("STRING");
format.add("BOOLEAN");
header.add(format);
objOut.writeObject(header);
objOut.reset();
objOut.flush();
list = new ArrayList<Object>();
list.add(111);
list.add("Test1");
list.add(true);
objOut.writeObject(list);
objOut.close();
client.close();
runner.join();
ps.close();
conn.close();
errorMsg = runner.getErrorMsg();
test = false;
if(errorMsg == null){
test = true;
}
assertTrue("Compress stream test is not passed: ",test);
//Case4: Premature end of stream (cancel object stream)
//Case5: Unique constraints on server (ie, server based exception on JDBC connection)
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java
index d0e50efc6..396e382b5 100644
--- a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java
+++ b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java
@@ -1,211 +1,211 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.internal.core.mixin;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.DLTKLanguageManager;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IProjectFragment;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.builder.IScriptBuilder;
import org.eclipse.dltk.core.mixin.IMixinParser;
import org.eclipse.dltk.core.search.SearchEngine;
import org.eclipse.dltk.core.search.SearchParticipant;
import org.eclipse.dltk.core.search.index.Index;
import org.eclipse.dltk.core.search.indexing.IndexManager;
import org.eclipse.dltk.core.search.indexing.InternalSearchDocument;
import org.eclipse.dltk.core.search.indexing.ReadWriteMonitor;
import org.eclipse.dltk.internal.core.BuiltinProjectFragment;
import org.eclipse.dltk.internal.core.BuiltinSourceModule;
import org.eclipse.dltk.internal.core.ExternalProjectFragment;
import org.eclipse.dltk.internal.core.ExternalSourceModule;
import org.eclipse.dltk.internal.core.ModelManager;
import org.eclipse.dltk.internal.core.SourceModule;
import org.eclipse.dltk.internal.core.search.DLTKSearchDocument;
public class MixinBuilder implements IScriptBuilder {
public IStatus[] buildResources(IScriptProject project, List resources,
IProgressMonitor monitor) {
return null;
}
public List getDependencies(IScriptProject project, List resources) {
return null;
}
public IStatus[] buildModelElements(IScriptProject project, List elements,
IProgressMonitor monitor) {
return this.buildModelElements(project, elements, monitor, true);
}
public IStatus[] buildModelElements(IScriptProject project, List elements,
final IProgressMonitor monitor, boolean saveIndex) {
IndexManager manager = ModelManager.getModelManager().getIndexManager();
final int elementsSize = elements.size();
IDLTKLanguageToolkit toolkit = null;
IMixinParser parser = null;
try {
toolkit = DLTKLanguageManager.getLanguageToolkit(project);
if (toolkit != null) {
parser = MixinManager.getMixinParser(toolkit.getNatureId());
}
} catch (CoreException e1) {
if (DLTKCore.DEBUG) {
e1.printStackTrace();
}
}
if (parser == null || toolkit == null) {
return null;
}
Map indexes = new HashMap();
// Map imons = new HashMap();
Index mixinIndex = null;
ReadWriteMonitor imon = null;
try {
// waitUntilIndexReady(toolkit);
IPath fullPath = project.getProject().getFullPath();
mixinIndex = manager.getSpecialIndex("mixin", /* project.getProject() */
fullPath.toString(), fullPath.toOSString());
imon = mixinIndex.monitor;
imon.enterWrite();
String name = "Building runtime model for "
+ project.getElementName();
monitor.beginTask(name, elementsSize);
int fileIndex = 0;
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
ISourceModule element = (ISourceModule) iterator.next();
Index currentIndex = mixinIndex;
if (monitor.isCanceled()) {
return null;
}
String taskTitle = "Building runtime model for "
+ project.getElementName() + " ("
+ (elements.size() - fileIndex) + "):"
+ element.getElementName();
++fileIndex;
monitor.subTask(taskTitle);
// monitor.beginTask(taskTitle, 1);
IProjectFragment projectFragment = (IProjectFragment) element
.getAncestor(IModelElement.PROJECT_FRAGMENT);
IPath containerPath = project.getPath();
if (projectFragment instanceof ExternalProjectFragment
|| projectFragment instanceof BuiltinProjectFragment) {
IPath path = projectFragment.getPath();
if (indexes.containsKey(path)) {
currentIndex = (Index) indexes.get(path);
containerPath = path;
} else {
Index index = manager.getSpecialIndex("mixin", path
.toString(), path.toOSString());
if (index != null) {
currentIndex = index;
if (!indexes.values().contains(index)) {
index.monitor.enterWrite();
indexes.put(path, index);
}
containerPath = path;
}
}
}
char[] source = element.getSourceAsCharArray();
SearchParticipant participant = SearchEngine
.getDefaultSearchParticipant();
DLTKSearchDocument document;
document = new DLTKSearchDocument(element.getPath()
.toOSString(), containerPath, source, participant,
element instanceof ExternalSourceModule);
// System.out.println("mixin indexing:" + document.getPath());
((InternalSearchDocument) document).toolkit = toolkit;
String containerRelativePath = null;
if (element instanceof ExternalSourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(containerPath.segmentCount())
.setDevice(null).toString());
} else if (element instanceof SourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(1).toOSString());
} else if (element instanceof BuiltinSourceModule) {
containerRelativePath = document.getPath();
// (element.getPath()
// .removeFirstSegments().toOSString());
}
((InternalSearchDocument) document)
.setContainerRelativePath(containerRelativePath);
currentIndex.remove(containerRelativePath);
((InternalSearchDocument) document).setIndex(currentIndex);
-// new MixinIndexer(document, element,
-// currentIndex).indexDocument();
+ new MixinIndexer(document, element,
+ currentIndex).indexDocument();
monitor.worked(1);
}
monitor.done();
} catch (CoreException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
if (mixinIndex != null) {
imon.exitWrite();
if (saveIndex) {
try {
manager.saveIndex(mixinIndex);
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
Iterator iterator = indexes.values().iterator();
while (iterator.hasNext()) {
Index index = (Index) iterator.next();
index.monitor.exitWrite();
if (saveIndex) {
try {
manager.saveIndex(index);
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
}
return null;
}
private static MixinBuilder builder = new MixinBuilder();
public static MixinBuilder getDefault() {
return builder;
}
}
| true | true | public IStatus[] buildModelElements(IScriptProject project, List elements,
final IProgressMonitor monitor, boolean saveIndex) {
IndexManager manager = ModelManager.getModelManager().getIndexManager();
final int elementsSize = elements.size();
IDLTKLanguageToolkit toolkit = null;
IMixinParser parser = null;
try {
toolkit = DLTKLanguageManager.getLanguageToolkit(project);
if (toolkit != null) {
parser = MixinManager.getMixinParser(toolkit.getNatureId());
}
} catch (CoreException e1) {
if (DLTKCore.DEBUG) {
e1.printStackTrace();
}
}
if (parser == null || toolkit == null) {
return null;
}
Map indexes = new HashMap();
// Map imons = new HashMap();
Index mixinIndex = null;
ReadWriteMonitor imon = null;
try {
// waitUntilIndexReady(toolkit);
IPath fullPath = project.getProject().getFullPath();
mixinIndex = manager.getSpecialIndex("mixin", /* project.getProject() */
fullPath.toString(), fullPath.toOSString());
imon = mixinIndex.monitor;
imon.enterWrite();
String name = "Building runtime model for "
+ project.getElementName();
monitor.beginTask(name, elementsSize);
int fileIndex = 0;
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
ISourceModule element = (ISourceModule) iterator.next();
Index currentIndex = mixinIndex;
if (monitor.isCanceled()) {
return null;
}
String taskTitle = "Building runtime model for "
+ project.getElementName() + " ("
+ (elements.size() - fileIndex) + "):"
+ element.getElementName();
++fileIndex;
monitor.subTask(taskTitle);
// monitor.beginTask(taskTitle, 1);
IProjectFragment projectFragment = (IProjectFragment) element
.getAncestor(IModelElement.PROJECT_FRAGMENT);
IPath containerPath = project.getPath();
if (projectFragment instanceof ExternalProjectFragment
|| projectFragment instanceof BuiltinProjectFragment) {
IPath path = projectFragment.getPath();
if (indexes.containsKey(path)) {
currentIndex = (Index) indexes.get(path);
containerPath = path;
} else {
Index index = manager.getSpecialIndex("mixin", path
.toString(), path.toOSString());
if (index != null) {
currentIndex = index;
if (!indexes.values().contains(index)) {
index.monitor.enterWrite();
indexes.put(path, index);
}
containerPath = path;
}
}
}
char[] source = element.getSourceAsCharArray();
SearchParticipant participant = SearchEngine
.getDefaultSearchParticipant();
DLTKSearchDocument document;
document = new DLTKSearchDocument(element.getPath()
.toOSString(), containerPath, source, participant,
element instanceof ExternalSourceModule);
// System.out.println("mixin indexing:" + document.getPath());
((InternalSearchDocument) document).toolkit = toolkit;
String containerRelativePath = null;
if (element instanceof ExternalSourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(containerPath.segmentCount())
.setDevice(null).toString());
} else if (element instanceof SourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(1).toOSString());
} else if (element instanceof BuiltinSourceModule) {
containerRelativePath = document.getPath();
// (element.getPath()
// .removeFirstSegments().toOSString());
}
((InternalSearchDocument) document)
.setContainerRelativePath(containerRelativePath);
currentIndex.remove(containerRelativePath);
((InternalSearchDocument) document).setIndex(currentIndex);
// new MixinIndexer(document, element,
// currentIndex).indexDocument();
monitor.worked(1);
}
monitor.done();
} catch (CoreException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
if (mixinIndex != null) {
imon.exitWrite();
if (saveIndex) {
try {
manager.saveIndex(mixinIndex);
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
Iterator iterator = indexes.values().iterator();
while (iterator.hasNext()) {
Index index = (Index) iterator.next();
index.monitor.exitWrite();
if (saveIndex) {
try {
manager.saveIndex(index);
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
}
return null;
}
| public IStatus[] buildModelElements(IScriptProject project, List elements,
final IProgressMonitor monitor, boolean saveIndex) {
IndexManager manager = ModelManager.getModelManager().getIndexManager();
final int elementsSize = elements.size();
IDLTKLanguageToolkit toolkit = null;
IMixinParser parser = null;
try {
toolkit = DLTKLanguageManager.getLanguageToolkit(project);
if (toolkit != null) {
parser = MixinManager.getMixinParser(toolkit.getNatureId());
}
} catch (CoreException e1) {
if (DLTKCore.DEBUG) {
e1.printStackTrace();
}
}
if (parser == null || toolkit == null) {
return null;
}
Map indexes = new HashMap();
// Map imons = new HashMap();
Index mixinIndex = null;
ReadWriteMonitor imon = null;
try {
// waitUntilIndexReady(toolkit);
IPath fullPath = project.getProject().getFullPath();
mixinIndex = manager.getSpecialIndex("mixin", /* project.getProject() */
fullPath.toString(), fullPath.toOSString());
imon = mixinIndex.monitor;
imon.enterWrite();
String name = "Building runtime model for "
+ project.getElementName();
monitor.beginTask(name, elementsSize);
int fileIndex = 0;
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
ISourceModule element = (ISourceModule) iterator.next();
Index currentIndex = mixinIndex;
if (monitor.isCanceled()) {
return null;
}
String taskTitle = "Building runtime model for "
+ project.getElementName() + " ("
+ (elements.size() - fileIndex) + "):"
+ element.getElementName();
++fileIndex;
monitor.subTask(taskTitle);
// monitor.beginTask(taskTitle, 1);
IProjectFragment projectFragment = (IProjectFragment) element
.getAncestor(IModelElement.PROJECT_FRAGMENT);
IPath containerPath = project.getPath();
if (projectFragment instanceof ExternalProjectFragment
|| projectFragment instanceof BuiltinProjectFragment) {
IPath path = projectFragment.getPath();
if (indexes.containsKey(path)) {
currentIndex = (Index) indexes.get(path);
containerPath = path;
} else {
Index index = manager.getSpecialIndex("mixin", path
.toString(), path.toOSString());
if (index != null) {
currentIndex = index;
if (!indexes.values().contains(index)) {
index.monitor.enterWrite();
indexes.put(path, index);
}
containerPath = path;
}
}
}
char[] source = element.getSourceAsCharArray();
SearchParticipant participant = SearchEngine
.getDefaultSearchParticipant();
DLTKSearchDocument document;
document = new DLTKSearchDocument(element.getPath()
.toOSString(), containerPath, source, participant,
element instanceof ExternalSourceModule);
// System.out.println("mixin indexing:" + document.getPath());
((InternalSearchDocument) document).toolkit = toolkit;
String containerRelativePath = null;
if (element instanceof ExternalSourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(containerPath.segmentCount())
.setDevice(null).toString());
} else if (element instanceof SourceModule) {
containerRelativePath = (element.getPath()
.removeFirstSegments(1).toOSString());
} else if (element instanceof BuiltinSourceModule) {
containerRelativePath = document.getPath();
// (element.getPath()
// .removeFirstSegments().toOSString());
}
((InternalSearchDocument) document)
.setContainerRelativePath(containerRelativePath);
currentIndex.remove(containerRelativePath);
((InternalSearchDocument) document).setIndex(currentIndex);
new MixinIndexer(document, element,
currentIndex).indexDocument();
monitor.worked(1);
}
monitor.done();
} catch (CoreException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
} finally {
if (mixinIndex != null) {
imon.exitWrite();
if (saveIndex) {
try {
manager.saveIndex(mixinIndex);
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
Iterator iterator = indexes.values().iterator();
while (iterator.hasNext()) {
Index index = (Index) iterator.next();
index.monitor.exitWrite();
if (saveIndex) {
try {
manager.saveIndex(index);
} catch (IOException e) {
if (DLTKCore.DEBUG) {
e.printStackTrace();
}
}
}
}
}
return null;
}
|
diff --git a/keratin-core/src/ca/szc/keratin/core/net/io/InputThread.java b/keratin-core/src/ca/szc/keratin/core/net/io/InputThread.java
index df65391..dabb5ff 100644
--- a/keratin-core/src/ca/szc/keratin/core/net/io/InputThread.java
+++ b/keratin-core/src/ca/szc/keratin/core/net/io/InputThread.java
@@ -1,235 +1,238 @@
/**
* Copyright (C) 2013 Alexander Szczuczko
*
* This file may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package ca.szc.keratin.core.net.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
import org.pmw.tinylog.Logger;
import ca.szc.keratin.core.event.IrcEvent;
import ca.szc.keratin.core.event.IrcMessageEvent;
import ca.szc.keratin.core.event.connection.IrcConnect;
import ca.szc.keratin.core.event.connection.IrcDisconnect;
import ca.szc.keratin.core.event.message.recieve.ReceiveChannelMode;
import ca.szc.keratin.core.event.message.recieve.ReceiveInvite;
import ca.szc.keratin.core.event.message.recieve.ReceiveJoin;
import ca.szc.keratin.core.event.message.recieve.ReceiveKick;
import ca.szc.keratin.core.event.message.recieve.ReceiveMode;
import ca.szc.keratin.core.event.message.recieve.ReceiveNick;
import ca.szc.keratin.core.event.message.recieve.ReceiveNotice;
import ca.szc.keratin.core.event.message.recieve.ReceivePart;
import ca.szc.keratin.core.event.message.recieve.ReceivePing;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import ca.szc.keratin.core.event.message.recieve.ReceiveQuit;
import ca.szc.keratin.core.event.message.recieve.ReceiveReply;
import ca.szc.keratin.core.event.message.recieve.ReceiveTopic;
import ca.szc.keratin.core.event.message.recieve.ReceiveUserMode;
import ca.szc.keratin.core.net.message.InvalidMessageCommandException;
import ca.szc.keratin.core.net.message.InvalidMessageException;
import ca.szc.keratin.core.net.message.InvalidMessageParamException;
import ca.szc.keratin.core.net.message.InvalidMessagePrefixException;
import ca.szc.keratin.core.net.message.IrcMessage;
/**
* Receives lines from the socket and sends out MessageRecieve events
*/
public class InputThread
extends Thread
{
private final MBassador<IrcEvent> bus;
private volatile boolean connected;
private BufferedReader input = null;
private Socket socket;
public InputThread( MBassador<IrcEvent> bus )
{
this.bus = bus;
connected = false;
}
@Override
public void run()
{
Thread.currentThread().setName( "InputThread" );
Logger.trace( "Input thread running" );
bus.subscribe( this );
while ( !Thread.interrupted() )
{
if ( connected )
{
// Logger.trace( "Reading line from input" );
try
{
String line = input.readLine();
if ( line != null )
{
Logger.trace( "Got line " + line );
IrcMessage message = null;
try
{
message = IrcMessage.parseMessage( line );
// String prefix = message.getPrefix();
String command = message.getCommand();
// String[] params = message.getParams();
IrcMessageEvent messageEvent = null;
// INVITE
if ( ReceiveInvite.COMMAND.equals( command ) )
messageEvent = new ReceiveInvite( bus, message );
// JOIN
else if ( ReceiveJoin.COMMAND.equals( command ) )
messageEvent = new ReceiveJoin( bus, message );
// KICK
else if ( ReceiveKick.COMMAND.equals( command ) )
messageEvent = new ReceiveKick( bus, message );
// MODE
else if ( ReceiveMode.COMMAND.equals( command ) )
{
if ( message.getParams().length == 2 )
messageEvent = new ReceiveUserMode( bus, message );
else
messageEvent = new ReceiveChannelMode( bus, message );
}
// NICK
else if ( ReceiveNick.COMMAND.equals( command ) )
messageEvent = new ReceiveNick( bus, message );
// NOTICE
else if ( ReceiveNotice.COMMAND.equals( command ) )
messageEvent = new ReceiveNotice( bus, message );
// PART
else if ( ReceivePart.COMMAND.equals( command ) )
messageEvent = new ReceivePart( bus, message );
// PING
else if ( ReceivePing.COMMAND.equals( command ) )
messageEvent = new ReceivePing( bus, message );
// PRIVMSG
else if ( ReceivePrivmsg.COMMAND.equals( command ) )
messageEvent = new ReceivePrivmsg( bus, message );
// QUIT
else if ( ReceiveQuit.COMMAND.equals( command ) )
messageEvent = new ReceiveQuit( bus, message );
// replies
else if ( isDigits( command ) )
messageEvent = new ReceiveReply( bus, message );
// TOPIC
else if ( ReceiveTopic.COMMAND.equals( command ) )
messageEvent = new ReceiveTopic( bus, message );
// others
else
+ {
Logger.error( "Unknown message '" + message.toString().replace( "\n", "\\n" ) + "'" );
+ message = null;
+ }
if ( message != null )
{
bus.publishAsync( messageEvent );
}
// Logger.trace( "Done sending parsed message to bus" );
}
catch ( IndexOutOfBoundsException | InvalidMessagePrefixException
| InvalidMessageCommandException | InvalidMessageParamException e )
{
Logger.error( e, "Couldn't publish parsed message '{0}' from line '{1}'", message, line );
}
catch ( InvalidMessageException e )
{
Logger.error( e, "Couldn't parse line '{0}'", line );
}
// Logger.trace( "Line processed from input" );
}
else
{
Logger.error( "Input end of stream" );
connected = false;
bus.publishAsync( new IrcDisconnect( bus, socket ) );
}
}
catch ( IOException e )
{
Logger.error( e, "Could not read line" );
try
{
Thread.sleep( IoConfig.WAIT_TIME );
}
catch ( InterruptedException e1 )
{
}
}
}
else
{
Logger.trace( "Socket is not connected. Sleeping." );
try
{
Thread.sleep( IoConfig.WAIT_TIME );
}
catch ( InterruptedException e )
{
}
}
}
Logger.trace( "Interrupted, exiting" );
}
private boolean isDigits( String str )
{
try
{
Integer.parseInt( str );
return true;
}
catch ( NumberFormatException e )
{
return false;
}
}
@Handler( priority = Integer.MIN_VALUE )
public void handleConnect( IrcConnect event )
{
socket = event.getSocket();
Logger.trace( "Creating input stream" );
try
{
InputStream inputStream = socket.getInputStream();
input = new BufferedReader( new InputStreamReader( inputStream, IoConfig.CHARSET ) );
Logger.trace( "Input stream created" );
}
catch ( IOException e )
{
Logger.error( e, "Could not open input stream" );
}
connected = true;
}
}
| false | true | public void run()
{
Thread.currentThread().setName( "InputThread" );
Logger.trace( "Input thread running" );
bus.subscribe( this );
while ( !Thread.interrupted() )
{
if ( connected )
{
// Logger.trace( "Reading line from input" );
try
{
String line = input.readLine();
if ( line != null )
{
Logger.trace( "Got line " + line );
IrcMessage message = null;
try
{
message = IrcMessage.parseMessage( line );
// String prefix = message.getPrefix();
String command = message.getCommand();
// String[] params = message.getParams();
IrcMessageEvent messageEvent = null;
// INVITE
if ( ReceiveInvite.COMMAND.equals( command ) )
messageEvent = new ReceiveInvite( bus, message );
// JOIN
else if ( ReceiveJoin.COMMAND.equals( command ) )
messageEvent = new ReceiveJoin( bus, message );
// KICK
else if ( ReceiveKick.COMMAND.equals( command ) )
messageEvent = new ReceiveKick( bus, message );
// MODE
else if ( ReceiveMode.COMMAND.equals( command ) )
{
if ( message.getParams().length == 2 )
messageEvent = new ReceiveUserMode( bus, message );
else
messageEvent = new ReceiveChannelMode( bus, message );
}
// NICK
else if ( ReceiveNick.COMMAND.equals( command ) )
messageEvent = new ReceiveNick( bus, message );
// NOTICE
else if ( ReceiveNotice.COMMAND.equals( command ) )
messageEvent = new ReceiveNotice( bus, message );
// PART
else if ( ReceivePart.COMMAND.equals( command ) )
messageEvent = new ReceivePart( bus, message );
// PING
else if ( ReceivePing.COMMAND.equals( command ) )
messageEvent = new ReceivePing( bus, message );
// PRIVMSG
else if ( ReceivePrivmsg.COMMAND.equals( command ) )
messageEvent = new ReceivePrivmsg( bus, message );
// QUIT
else if ( ReceiveQuit.COMMAND.equals( command ) )
messageEvent = new ReceiveQuit( bus, message );
// replies
else if ( isDigits( command ) )
messageEvent = new ReceiveReply( bus, message );
// TOPIC
else if ( ReceiveTopic.COMMAND.equals( command ) )
messageEvent = new ReceiveTopic( bus, message );
// others
else
Logger.error( "Unknown message '" + message.toString().replace( "\n", "\\n" ) + "'" );
if ( message != null )
{
bus.publishAsync( messageEvent );
}
// Logger.trace( "Done sending parsed message to bus" );
}
catch ( IndexOutOfBoundsException | InvalidMessagePrefixException
| InvalidMessageCommandException | InvalidMessageParamException e )
{
Logger.error( e, "Couldn't publish parsed message '{0}' from line '{1}'", message, line );
}
catch ( InvalidMessageException e )
{
Logger.error( e, "Couldn't parse line '{0}'", line );
}
// Logger.trace( "Line processed from input" );
}
else
{
Logger.error( "Input end of stream" );
connected = false;
bus.publishAsync( new IrcDisconnect( bus, socket ) );
}
}
catch ( IOException e )
{
Logger.error( e, "Could not read line" );
try
{
Thread.sleep( IoConfig.WAIT_TIME );
}
catch ( InterruptedException e1 )
{
}
}
}
else
{
Logger.trace( "Socket is not connected. Sleeping." );
try
{
Thread.sleep( IoConfig.WAIT_TIME );
}
catch ( InterruptedException e )
{
}
}
}
Logger.trace( "Interrupted, exiting" );
}
| public void run()
{
Thread.currentThread().setName( "InputThread" );
Logger.trace( "Input thread running" );
bus.subscribe( this );
while ( !Thread.interrupted() )
{
if ( connected )
{
// Logger.trace( "Reading line from input" );
try
{
String line = input.readLine();
if ( line != null )
{
Logger.trace( "Got line " + line );
IrcMessage message = null;
try
{
message = IrcMessage.parseMessage( line );
// String prefix = message.getPrefix();
String command = message.getCommand();
// String[] params = message.getParams();
IrcMessageEvent messageEvent = null;
// INVITE
if ( ReceiveInvite.COMMAND.equals( command ) )
messageEvent = new ReceiveInvite( bus, message );
// JOIN
else if ( ReceiveJoin.COMMAND.equals( command ) )
messageEvent = new ReceiveJoin( bus, message );
// KICK
else if ( ReceiveKick.COMMAND.equals( command ) )
messageEvent = new ReceiveKick( bus, message );
// MODE
else if ( ReceiveMode.COMMAND.equals( command ) )
{
if ( message.getParams().length == 2 )
messageEvent = new ReceiveUserMode( bus, message );
else
messageEvent = new ReceiveChannelMode( bus, message );
}
// NICK
else if ( ReceiveNick.COMMAND.equals( command ) )
messageEvent = new ReceiveNick( bus, message );
// NOTICE
else if ( ReceiveNotice.COMMAND.equals( command ) )
messageEvent = new ReceiveNotice( bus, message );
// PART
else if ( ReceivePart.COMMAND.equals( command ) )
messageEvent = new ReceivePart( bus, message );
// PING
else if ( ReceivePing.COMMAND.equals( command ) )
messageEvent = new ReceivePing( bus, message );
// PRIVMSG
else if ( ReceivePrivmsg.COMMAND.equals( command ) )
messageEvent = new ReceivePrivmsg( bus, message );
// QUIT
else if ( ReceiveQuit.COMMAND.equals( command ) )
messageEvent = new ReceiveQuit( bus, message );
// replies
else if ( isDigits( command ) )
messageEvent = new ReceiveReply( bus, message );
// TOPIC
else if ( ReceiveTopic.COMMAND.equals( command ) )
messageEvent = new ReceiveTopic( bus, message );
// others
else
{
Logger.error( "Unknown message '" + message.toString().replace( "\n", "\\n" ) + "'" );
message = null;
}
if ( message != null )
{
bus.publishAsync( messageEvent );
}
// Logger.trace( "Done sending parsed message to bus" );
}
catch ( IndexOutOfBoundsException | InvalidMessagePrefixException
| InvalidMessageCommandException | InvalidMessageParamException e )
{
Logger.error( e, "Couldn't publish parsed message '{0}' from line '{1}'", message, line );
}
catch ( InvalidMessageException e )
{
Logger.error( e, "Couldn't parse line '{0}'", line );
}
// Logger.trace( "Line processed from input" );
}
else
{
Logger.error( "Input end of stream" );
connected = false;
bus.publishAsync( new IrcDisconnect( bus, socket ) );
}
}
catch ( IOException e )
{
Logger.error( e, "Could not read line" );
try
{
Thread.sleep( IoConfig.WAIT_TIME );
}
catch ( InterruptedException e1 )
{
}
}
}
else
{
Logger.trace( "Socket is not connected. Sleeping." );
try
{
Thread.sleep( IoConfig.WAIT_TIME );
}
catch ( InterruptedException e )
{
}
}
}
Logger.trace( "Interrupted, exiting" );
}
|
diff --git a/src/at/junction/transmission/Transmission.java b/src/at/junction/transmission/Transmission.java
index d39f5bb..459c631 100644
--- a/src/at/junction/transmission/Transmission.java
+++ b/src/at/junction/transmission/Transmission.java
@@ -1,127 +1,143 @@
package at.junction.transmission;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Transmission extends JavaPlugin {
TransmissionListener listener = new TransmissionListener(this);
Configuration config = new Configuration(this);
List<String> staffChatters = new ArrayList<>();
HashMap<String, String> replyList = new HashMap<String, String>();
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(listener, this);
File cfile = new File(getDataFolder(), "config.yml");
if (!cfile.exists()) {
getConfig().options().copyDefaults(true);
saveConfig();
}
config.load();
}
@Override
public void onDisable() {
}
@Override
public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
if (command.getName().equalsIgnoreCase("staffchat")) {
- if (staffChatters.contains(sender.getName())) { //Leave staff chat
- sender.sendMessage(ChatColor.GOLD + "You are no longer talking in staff chat.");
- staffChatters.remove(sender.getName());
- } else { //Enter staff chat
- sender.sendMessage(ChatColor.GOLD + "You are now chatting in staff! Use /staffchat to swap back.");
- staffChatters.add(sender.getName());
+ if (args.length == 0){ //Switch into StaffChat Mode
+ if (staffChatters.contains(sender.getName())) { //Leave staff chat
+ sender.sendMessage(ChatColor.GOLD + "You are no longer talking in staff chat.");
+ staffChatters.remove(sender.getName());
+ } else { //Enter staff chat
+ sender.sendMessage(ChatColor.GOLD + "You are now chatting in staff! Use /staffchat to swap back.");
+ staffChatters.add(sender.getName());
+ }
+ } else { //Send a single message to staff chat
+ StringBuilder message = new StringBuilder();
+ String playerName = (sender instanceof Player)? ((Player) sender).getDisplayName() : sender.getName();
+ for (int i=0; i<args.length; i++){
+ message.append(args[i]);
+ if (i != args.length - 1){
+ message.append(" ");
+ }
+ }
+ for(Player p : getServer().getOnlinePlayers()) {
+ if(p.hasPermission("transmission.staffchat")) {
+ p.sendMessage(String.format(ChatColor.DARK_AQUA + "[S]<" + ChatColor.WHITE + "%1$s" + ChatColor.DARK_AQUA + "> " + ChatColor.RESET + "%2$s", playerName, message));
+ }
+ }
}
} else if (command.getName().equalsIgnoreCase("broadcast")) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Usage: /o <message>. For official server business only.");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
getServer().broadcastMessage(ChatColor.WHITE + "<" + ChatColor.RED + sender.getName() + ChatColor.WHITE + "> " + ChatColor.GREEN + message.toString());
} else if (command.getName().equalsIgnoreCase("ircsay")) {
if (sender instanceof Player) {
sender.sendMessage(ChatColor.RED + "ERROR: " + ChatColor.MAGIC + "-------------------------------");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
getServer().broadcastMessage(ChatColor.GREEN + "[IRC] " + ChatColor.WHITE + message);
} else if (command.getName().equalsIgnoreCase("reply")) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Usage: /r <message>");
return true;
}
//They have recieved a message, send this message to the last person
if (replyList.containsKey(sender.getName())) {
Player reciever;
if ((reciever = getServer().getPlayer(replyList.get(sender.getName()))) == null) { //If reciever is null, send message and return.
sender.sendMessage(ChatColor.RED + "That player is no longer online");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
sendMessage(sender, reciever, message.toString().substring(0, message.length() - 1));
} else { //They have recieved messages, return.
sender.sendMessage(ChatColor.RED + "You haven't recieved any messages, therefore you can't reply.");
}
} else if (command.getName().equalsIgnoreCase("msg")) {
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + "Usage: /msg <player> <message>");
return true;
}
Player reciever;
if ((reciever = getServer().getPlayer(args[0])) == null) {
sender.sendMessage("That player is not online");
}
StringBuilder message = new StringBuilder();
for (int i = 1; i < args.length; i++) {
message.append(args[i]).append(" ");
}
sendMessage(sender, reciever, message.toString().substring(0, message.length() - 1));
replyList.put(sender.getName(), reciever.getName());
} else if (command.getName().equalsIgnoreCase("list")) {
StringBuilder players = new StringBuilder();
for (Player p : getServer().getOnlinePlayers()) {
players.append(p.getName()).append(", ");
}
sender.sendMessage("There are " + getServer().getOnlinePlayers().length + "/" + getServer().getMaxPlayers() + " players online:");
sender.sendMessage(players.substring(0, players.length()-2));
sender.sendMessage(ChatColor.GREEN + "Please type /staff to see online staff members.");
}
return true;
}
public void sendMessage(CommandSender from, CommandSender to, String message) {
String niceMessage = ChatColor.GRAY + "["
+ ChatColor.RED + "%s"
+ ChatColor.GRAY + " -> "
+ ChatColor.GOLD + "%s"
+ ChatColor.GRAY + "] "
+ ChatColor.WHITE + message;
from.sendMessage(String.format(niceMessage, "Me", to.getName()));
to.sendMessage(String.format(niceMessage, from.getName(), "Me"));
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
if (command.getName().equalsIgnoreCase("staffchat")) {
if (staffChatters.contains(sender.getName())) { //Leave staff chat
sender.sendMessage(ChatColor.GOLD + "You are no longer talking in staff chat.");
staffChatters.remove(sender.getName());
} else { //Enter staff chat
sender.sendMessage(ChatColor.GOLD + "You are now chatting in staff! Use /staffchat to swap back.");
staffChatters.add(sender.getName());
}
} else if (command.getName().equalsIgnoreCase("broadcast")) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Usage: /o <message>. For official server business only.");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
getServer().broadcastMessage(ChatColor.WHITE + "<" + ChatColor.RED + sender.getName() + ChatColor.WHITE + "> " + ChatColor.GREEN + message.toString());
} else if (command.getName().equalsIgnoreCase("ircsay")) {
if (sender instanceof Player) {
sender.sendMessage(ChatColor.RED + "ERROR: " + ChatColor.MAGIC + "-------------------------------");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
getServer().broadcastMessage(ChatColor.GREEN + "[IRC] " + ChatColor.WHITE + message);
} else if (command.getName().equalsIgnoreCase("reply")) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Usage: /r <message>");
return true;
}
//They have recieved a message, send this message to the last person
if (replyList.containsKey(sender.getName())) {
Player reciever;
if ((reciever = getServer().getPlayer(replyList.get(sender.getName()))) == null) { //If reciever is null, send message and return.
sender.sendMessage(ChatColor.RED + "That player is no longer online");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
sendMessage(sender, reciever, message.toString().substring(0, message.length() - 1));
} else { //They have recieved messages, return.
sender.sendMessage(ChatColor.RED + "You haven't recieved any messages, therefore you can't reply.");
}
} else if (command.getName().equalsIgnoreCase("msg")) {
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + "Usage: /msg <player> <message>");
return true;
}
Player reciever;
if ((reciever = getServer().getPlayer(args[0])) == null) {
sender.sendMessage("That player is not online");
}
StringBuilder message = new StringBuilder();
for (int i = 1; i < args.length; i++) {
message.append(args[i]).append(" ");
}
sendMessage(sender, reciever, message.toString().substring(0, message.length() - 1));
replyList.put(sender.getName(), reciever.getName());
} else if (command.getName().equalsIgnoreCase("list")) {
StringBuilder players = new StringBuilder();
for (Player p : getServer().getOnlinePlayers()) {
players.append(p.getName()).append(", ");
}
sender.sendMessage("There are " + getServer().getOnlinePlayers().length + "/" + getServer().getMaxPlayers() + " players online:");
sender.sendMessage(players.substring(0, players.length()-2));
sender.sendMessage(ChatColor.GREEN + "Please type /staff to see online staff members.");
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
if (command.getName().equalsIgnoreCase("staffchat")) {
if (args.length == 0){ //Switch into StaffChat Mode
if (staffChatters.contains(sender.getName())) { //Leave staff chat
sender.sendMessage(ChatColor.GOLD + "You are no longer talking in staff chat.");
staffChatters.remove(sender.getName());
} else { //Enter staff chat
sender.sendMessage(ChatColor.GOLD + "You are now chatting in staff! Use /staffchat to swap back.");
staffChatters.add(sender.getName());
}
} else { //Send a single message to staff chat
StringBuilder message = new StringBuilder();
String playerName = (sender instanceof Player)? ((Player) sender).getDisplayName() : sender.getName();
for (int i=0; i<args.length; i++){
message.append(args[i]);
if (i != args.length - 1){
message.append(" ");
}
}
for(Player p : getServer().getOnlinePlayers()) {
if(p.hasPermission("transmission.staffchat")) {
p.sendMessage(String.format(ChatColor.DARK_AQUA + "[S]<" + ChatColor.WHITE + "%1$s" + ChatColor.DARK_AQUA + "> " + ChatColor.RESET + "%2$s", playerName, message));
}
}
}
} else if (command.getName().equalsIgnoreCase("broadcast")) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Usage: /o <message>. For official server business only.");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
getServer().broadcastMessage(ChatColor.WHITE + "<" + ChatColor.RED + sender.getName() + ChatColor.WHITE + "> " + ChatColor.GREEN + message.toString());
} else if (command.getName().equalsIgnoreCase("ircsay")) {
if (sender instanceof Player) {
sender.sendMessage(ChatColor.RED + "ERROR: " + ChatColor.MAGIC + "-------------------------------");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
getServer().broadcastMessage(ChatColor.GREEN + "[IRC] " + ChatColor.WHITE + message);
} else if (command.getName().equalsIgnoreCase("reply")) {
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Usage: /r <message>");
return true;
}
//They have recieved a message, send this message to the last person
if (replyList.containsKey(sender.getName())) {
Player reciever;
if ((reciever = getServer().getPlayer(replyList.get(sender.getName()))) == null) { //If reciever is null, send message and return.
sender.sendMessage(ChatColor.RED + "That player is no longer online");
return true;
}
StringBuilder message = new StringBuilder();
for (String t : args) {
message.append(t).append(" ");
}
sendMessage(sender, reciever, message.toString().substring(0, message.length() - 1));
} else { //They have recieved messages, return.
sender.sendMessage(ChatColor.RED + "You haven't recieved any messages, therefore you can't reply.");
}
} else if (command.getName().equalsIgnoreCase("msg")) {
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + "Usage: /msg <player> <message>");
return true;
}
Player reciever;
if ((reciever = getServer().getPlayer(args[0])) == null) {
sender.sendMessage("That player is not online");
}
StringBuilder message = new StringBuilder();
for (int i = 1; i < args.length; i++) {
message.append(args[i]).append(" ");
}
sendMessage(sender, reciever, message.toString().substring(0, message.length() - 1));
replyList.put(sender.getName(), reciever.getName());
} else if (command.getName().equalsIgnoreCase("list")) {
StringBuilder players = new StringBuilder();
for (Player p : getServer().getOnlinePlayers()) {
players.append(p.getName()).append(", ");
}
sender.sendMessage("There are " + getServer().getOnlinePlayers().length + "/" + getServer().getMaxPlayers() + " players online:");
sender.sendMessage(players.substring(0, players.length()-2));
sender.sendMessage(ChatColor.GREEN + "Please type /staff to see online staff members.");
}
return true;
}
|
diff --git a/sokoban/solvers/BidirectionalIDS.java b/sokoban/solvers/BidirectionalIDS.java
index 5d285b9..b25f8c7 100644
--- a/sokoban/solvers/BidirectionalIDS.java
+++ b/sokoban/solvers/BidirectionalIDS.java
@@ -1,106 +1,106 @@
package sokoban.solvers;
import java.util.HashMap;
import java.util.HashSet;
import sokoban.Board;
import sokoban.SearchInfo;
import sokoban.SearchStatus;
/**
* This solver performs a bidirectional search using the IDSPusher and IDSPuller.
*/
public class BidirectionalIDS implements Solver
{
private IDSPuller puller;
private IDSPusher pusher;
@Override
public String solve(final Board startBoard)
{
HashSet<Long> failedBoardsPuller = new HashSet<Long>();
HashSet<Long> failedBoardsPusher = new HashSet<Long>();
HashMap<Long, BoxPosDir> pullerStatesMap = new HashMap<Long, BoxPosDir>();
HashMap<Long, BoxPosDir> pusherStatesMap = new HashMap<Long, BoxPosDir>();
pusher = new IDSPusher(startBoard, failedBoardsPuller, pusherStatesMap,
pullerStatesMap);
puller = new IDSPuller(startBoard, failedBoardsPusher, pullerStatesMap,
pusherStatesMap);
boolean runPuller = true;
int lowerBound = IDSCommon.lowerBound(startBoard);
SearchInfo result;
// IDS loop
boolean pullerFailed = false;
boolean pusherFailed = false;
int pullerDepth = lowerBound;
int pusherDepth = lowerBound;
while (true) {
result = SearchInfo.Failed;
// Puller
if (runPuller && pullerDepth < IDSCommon.DEPTH_LIMIT) {
System.out.print("puller (depth " + pullerDepth + "): ");
result = puller.dfs(pullerDepth);
pullerDepth = puller.nextDepth(lowerBound);
System.out.println(result.status);
}
// Pusher
if (!runPuller && pullerDepth < IDSCommon.DEPTH_LIMIT) {
System.out.print("pusher (depth " + pusherDepth + "): ");
result = pusher.dfs(pusherDepth);
pusherDepth = pusher.nextDepth(lowerBound);
System.out.println(result.status);
}
if (result.solution != null) {
System.out.println();
return Board.solutionToString(result.solution);
}
- else if (pullerDepth >= IDSCommon.DEPTH_LIMIT
+ else if (pusherDepth >= IDSCommon.DEPTH_LIMIT
&& pullerDepth >= IDSCommon.DEPTH_LIMIT) {
System.out.println("Maximum depth reached!");
return null;
}
else if (result.status == SearchStatus.Failed) {
if (runPuller)
pullerFailed = true;
if (!runPuller)
pusherFailed = true;
}
if (pullerFailed && pusherFailed) {
System.out.println("no solution!");
return null;
}
// Run the other solver if only one of them failed
// in case it failed because of a bug or hash collision
if (pullerFailed) {
runPuller = false;
}
else if (pusherFailed) {
runPuller = true;
}
else if (runPuller && 2*pusher.numLeafNodes < puller.numLeafNodes) {
runPuller = false;
}
else {
runPuller = true;
}
}
}
@Override
public int getIterationsCount()
{
// TODO
return pusher.getIterationsCount() + puller.getIterationsCount();
}
}
| true | true | public String solve(final Board startBoard)
{
HashSet<Long> failedBoardsPuller = new HashSet<Long>();
HashSet<Long> failedBoardsPusher = new HashSet<Long>();
HashMap<Long, BoxPosDir> pullerStatesMap = new HashMap<Long, BoxPosDir>();
HashMap<Long, BoxPosDir> pusherStatesMap = new HashMap<Long, BoxPosDir>();
pusher = new IDSPusher(startBoard, failedBoardsPuller, pusherStatesMap,
pullerStatesMap);
puller = new IDSPuller(startBoard, failedBoardsPusher, pullerStatesMap,
pusherStatesMap);
boolean runPuller = true;
int lowerBound = IDSCommon.lowerBound(startBoard);
SearchInfo result;
// IDS loop
boolean pullerFailed = false;
boolean pusherFailed = false;
int pullerDepth = lowerBound;
int pusherDepth = lowerBound;
while (true) {
result = SearchInfo.Failed;
// Puller
if (runPuller && pullerDepth < IDSCommon.DEPTH_LIMIT) {
System.out.print("puller (depth " + pullerDepth + "): ");
result = puller.dfs(pullerDepth);
pullerDepth = puller.nextDepth(lowerBound);
System.out.println(result.status);
}
// Pusher
if (!runPuller && pullerDepth < IDSCommon.DEPTH_LIMIT) {
System.out.print("pusher (depth " + pusherDepth + "): ");
result = pusher.dfs(pusherDepth);
pusherDepth = pusher.nextDepth(lowerBound);
System.out.println(result.status);
}
if (result.solution != null) {
System.out.println();
return Board.solutionToString(result.solution);
}
else if (pullerDepth >= IDSCommon.DEPTH_LIMIT
&& pullerDepth >= IDSCommon.DEPTH_LIMIT) {
System.out.println("Maximum depth reached!");
return null;
}
else if (result.status == SearchStatus.Failed) {
if (runPuller)
pullerFailed = true;
if (!runPuller)
pusherFailed = true;
}
if (pullerFailed && pusherFailed) {
System.out.println("no solution!");
return null;
}
// Run the other solver if only one of them failed
// in case it failed because of a bug or hash collision
if (pullerFailed) {
runPuller = false;
}
else if (pusherFailed) {
runPuller = true;
}
else if (runPuller && 2*pusher.numLeafNodes < puller.numLeafNodes) {
runPuller = false;
}
else {
runPuller = true;
}
}
}
| public String solve(final Board startBoard)
{
HashSet<Long> failedBoardsPuller = new HashSet<Long>();
HashSet<Long> failedBoardsPusher = new HashSet<Long>();
HashMap<Long, BoxPosDir> pullerStatesMap = new HashMap<Long, BoxPosDir>();
HashMap<Long, BoxPosDir> pusherStatesMap = new HashMap<Long, BoxPosDir>();
pusher = new IDSPusher(startBoard, failedBoardsPuller, pusherStatesMap,
pullerStatesMap);
puller = new IDSPuller(startBoard, failedBoardsPusher, pullerStatesMap,
pusherStatesMap);
boolean runPuller = true;
int lowerBound = IDSCommon.lowerBound(startBoard);
SearchInfo result;
// IDS loop
boolean pullerFailed = false;
boolean pusherFailed = false;
int pullerDepth = lowerBound;
int pusherDepth = lowerBound;
while (true) {
result = SearchInfo.Failed;
// Puller
if (runPuller && pullerDepth < IDSCommon.DEPTH_LIMIT) {
System.out.print("puller (depth " + pullerDepth + "): ");
result = puller.dfs(pullerDepth);
pullerDepth = puller.nextDepth(lowerBound);
System.out.println(result.status);
}
// Pusher
if (!runPuller && pullerDepth < IDSCommon.DEPTH_LIMIT) {
System.out.print("pusher (depth " + pusherDepth + "): ");
result = pusher.dfs(pusherDepth);
pusherDepth = pusher.nextDepth(lowerBound);
System.out.println(result.status);
}
if (result.solution != null) {
System.out.println();
return Board.solutionToString(result.solution);
}
else if (pusherDepth >= IDSCommon.DEPTH_LIMIT
&& pullerDepth >= IDSCommon.DEPTH_LIMIT) {
System.out.println("Maximum depth reached!");
return null;
}
else if (result.status == SearchStatus.Failed) {
if (runPuller)
pullerFailed = true;
if (!runPuller)
pusherFailed = true;
}
if (pullerFailed && pusherFailed) {
System.out.println("no solution!");
return null;
}
// Run the other solver if only one of them failed
// in case it failed because of a bug or hash collision
if (pullerFailed) {
runPuller = false;
}
else if (pusherFailed) {
runPuller = true;
}
else if (runPuller && 2*pusher.numLeafNodes < puller.numLeafNodes) {
runPuller = false;
}
else {
runPuller = true;
}
}
}
|
diff --git a/src/GCParser/OperationNameResolver.java b/src/GCParser/OperationNameResolver.java
index 879a1c0..8c6fce4 100644
--- a/src/GCParser/OperationNameResolver.java
+++ b/src/GCParser/OperationNameResolver.java
@@ -1,58 +1,57 @@
// Copyright (C) Billy Melicher 2012 [email protected]
package GCParser;
import java.util.*;
import YaoGC.*;
import GCParser.Operation.*;
public class OperationNameResolver {
private static boolean isInitialized = false;
private static Map<String,OpDirections> resolver = new HashMap<String,OpDirections>();
public static void initOperations() {
if( isInitialized )
return;
isInitialized = true;
new AddOperation();
new XorOperation();
new ConcatOperation();
new MaxOperation();
new MinOperation();
new AndOperation();
new SubOperation();
new GteuOperation();
new GtuOperation();
new LteuOperation();
new LtuOperation();
new GtsOperation();
new GtesOperation();
new LtsOperation();
new LtesOperation();
new MinsOperation();
new MaxsOperation();
new SelectOperation();
new EquOperation();
new NequOperation();
new NotOperation();
new NegateOperation();
new OrOperation();
new TruncOperation();
new SextendOperation();
new ZextendOperation();
new SetOperation();
new ChoseOperation();
new ConcatlsOperation();
new ShiftLeftOperation();
new ShiftRightOperation();
- new SboxOperation();
}
public static State executeFromName( String op_name, State[] operands ) throws Exception {
return get(op_name).execute(operands);
}
public static OpDirections get( String op_name ) {
return resolver.get( op_name );
}
public static void registerOp(String op, OpDirections dir){
resolver.put(op, dir);
}
}
| true | true | public static void initOperations() {
if( isInitialized )
return;
isInitialized = true;
new AddOperation();
new XorOperation();
new ConcatOperation();
new MaxOperation();
new MinOperation();
new AndOperation();
new SubOperation();
new GteuOperation();
new GtuOperation();
new LteuOperation();
new LtuOperation();
new GtsOperation();
new GtesOperation();
new LtsOperation();
new LtesOperation();
new MinsOperation();
new MaxsOperation();
new SelectOperation();
new EquOperation();
new NequOperation();
new NotOperation();
new NegateOperation();
new OrOperation();
new TruncOperation();
new SextendOperation();
new ZextendOperation();
new SetOperation();
new ChoseOperation();
new ConcatlsOperation();
new ShiftLeftOperation();
new ShiftRightOperation();
new SboxOperation();
}
| public static void initOperations() {
if( isInitialized )
return;
isInitialized = true;
new AddOperation();
new XorOperation();
new ConcatOperation();
new MaxOperation();
new MinOperation();
new AndOperation();
new SubOperation();
new GteuOperation();
new GtuOperation();
new LteuOperation();
new LtuOperation();
new GtsOperation();
new GtesOperation();
new LtsOperation();
new LtesOperation();
new MinsOperation();
new MaxsOperation();
new SelectOperation();
new EquOperation();
new NequOperation();
new NotOperation();
new NegateOperation();
new OrOperation();
new TruncOperation();
new SextendOperation();
new ZextendOperation();
new SetOperation();
new ChoseOperation();
new ConcatlsOperation();
new ShiftLeftOperation();
new ShiftRightOperation();
}
|
diff --git a/viewer3d/src/org/jcae/viewer3d/FPSBehavior.java b/viewer3d/src/org/jcae/viewer3d/FPSBehavior.java
index bc9ae8eb..d8e8d0d3 100644
--- a/viewer3d/src/org/jcae/viewer3d/FPSBehavior.java
+++ b/viewer3d/src/org/jcae/viewer3d/FPSBehavior.java
@@ -1,144 +1,144 @@
/*
* Project Info: http://jcae.sourceforge.net
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* (C) Copyright 2007, by EADS France
*/
package org.jcae.viewer3d;
import javax.media.j3d.Behavior;
import javax.media.j3d.WakeupOnElapsedFrames;
/**
* A behavior to measure FPS.
* It's a very simplified version of the class found here
* http://www.java-tips.org/other-api-tips/java3d/how-to-create-a-frames-per-second-counter.html
* @author Jerome Robert
*/
public class FPSBehavior extends Behavior
{
// Wakeup condition - framecount = 0 -> wakeup on every frame
private WakeupOnElapsedFrames FPSwakeup = new WakeupOnElapsedFrames(0);
// Counter for number of frames rendered
private int numframes = 0;
// Report frame rate after maxframe number of frames have been rendered
private int maxframes = 50;
private long lasttime = 0;
private double currentFPS;
public FPSBehavior()
{
setEnable(true);
}
/**
* Called to init the behavior
* @see Behavior.initialize
*/
public void initialize()
{
numframes=-1;
// Set the trigger for the behavior to wakeup on every frame rendered
wakeupOn(FPSwakeup);
}
/**
* Called every time the behavior is activated
* @see Behavior.processStimulus
*/
public void processStimulus(java.util.Enumeration critera)
{
long currtime=System.currentTimeMillis();
numframes++;
//init
if(numframes==0)
{
lasttime=currtime;
}
else
{
if(numframes>=maxframes)
{
currentFPS=numframes/((double)currtime-lasttime)*1000;
- firePropertyChangeListenerPropertyChange(this, null, null, null);
+ firePropertyChangeListenerPropertyChange(this, null, null, currentFPS);
numframes=0;
lasttime=currtime;
}
}
// Set the trigger for the behavior
wakeupOn(FPSwakeup);
}
/**
* Utility field holding list of PropertyChangeListeners.
*/
private transient java.util.ArrayList propertyChangeListenerList;
/**
* Registers PropertyChangeListener to receive events.
* @param listener The listener to register.
*/
public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener listener)
{
if (propertyChangeListenerList == null ) {
propertyChangeListenerList = new java.util.ArrayList ();
}
propertyChangeListenerList.add (listener);
}
/**
* Removes PropertyChangeListener from the list of listeners.
* @param listener The listener to remove.
*/
public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener listener)
{
if (propertyChangeListenerList != null ) {
propertyChangeListenerList.remove (listener);
}
}
/**
* Notifies all registered listeners about the event.
*
* @param object Parameter #1 of the <CODE>PropertyChangeEvent<CODE> constructor.
* @param string Parameter #2 of the <CODE>PropertyChangeEvent<CODE> constructor.
* @param object0 Parameter #3 of the <CODE>PropertyChangeEvent<CODE> constructor.
* @param object1 Parameter #4 of the <CODE>PropertyChangeEvent<CODE> constructor.
*/
private void firePropertyChangeListenerPropertyChange(java.lang.Object object, java.lang.String string, java.lang.Object object0, java.lang.Object object1)
{
java.util.ArrayList list;
java.beans.PropertyChangeEvent e = new java.beans.PropertyChangeEvent (object, string, object0, object1);
synchronized (this) {
if (propertyChangeListenerList == null) return;
list = (java.util.ArrayList)propertyChangeListenerList.clone ();
}
for (int i = 0; i < list.size (); i++) {
((java.beans.PropertyChangeListener)list.get (i)).propertyChange (e);
}
}
/**
* Return the last measurement
*/
public double getFPS()
{
return currentFPS;
}
}
| true | true | public void processStimulus(java.util.Enumeration critera)
{
long currtime=System.currentTimeMillis();
numframes++;
//init
if(numframes==0)
{
lasttime=currtime;
}
else
{
if(numframes>=maxframes)
{
currentFPS=numframes/((double)currtime-lasttime)*1000;
firePropertyChangeListenerPropertyChange(this, null, null, null);
numframes=0;
lasttime=currtime;
}
}
// Set the trigger for the behavior
wakeupOn(FPSwakeup);
}
| public void processStimulus(java.util.Enumeration critera)
{
long currtime=System.currentTimeMillis();
numframes++;
//init
if(numframes==0)
{
lasttime=currtime;
}
else
{
if(numframes>=maxframes)
{
currentFPS=numframes/((double)currtime-lasttime)*1000;
firePropertyChangeListenerPropertyChange(this, null, null, currentFPS);
numframes=0;
lasttime=currtime;
}
}
// Set the trigger for the behavior
wakeupOn(FPSwakeup);
}
|
diff --git a/src/main/java/com/tek42/perforce/parse/CounterBuilder.java b/src/main/java/com/tek42/perforce/parse/CounterBuilder.java
index 3ad206b..1022093 100644
--- a/src/main/java/com/tek42/perforce/parse/CounterBuilder.java
+++ b/src/main/java/com/tek42/perforce/parse/CounterBuilder.java
@@ -1,61 +1,63 @@
package com.tek42.perforce.parse;
import java.io.Writer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.tek42.perforce.PerforceException;
import com.tek42.perforce.model.Counter;
/**
* Responsible for building and saving counters.
*
* @author Kamlesh Sangani
*/
public class CounterBuilder implements Builder<Counter> {
/*
* (non-Javadoc)
* @see com.tek42.perforce.parse.Builder#getBuildCmd(java.lang.String)
*/
public String[] getBuildCmd(String p4exe, String id) {
return new String[] { p4exe, "counter", id };
}
/*
* (non-Javadoc)
* @see com.tek42.perforce.parse.Builder#getSaveCmd()
*/
public String[] getSaveCmd(String p4exe, Counter obj) {
return new String[] { p4exe, "counter", obj.getName(), String.valueOf(obj.getValue()) };
}
/*
* (non-Javadoc)
* @see com.tek42.perforce.parse.Builder#build(java.lang.StringBuilder)
*/
public Counter build(StringBuilder sb) throws PerforceException {
- final Pattern p = Pattern.compile("^([0-9])*", Pattern.DOTALL | Pattern.MULTILINE);
+ final Pattern p = Pattern.compile("^([0-9]+)", Pattern.DOTALL | Pattern.MULTILINE);
final Matcher m = p.matcher(sb.toString());
final Counter counter = new Counter();
counter.setName("");
if(m.find()) {
- counter.setValue(Integer.parseInt(m.group(0).trim()));
- }
+ counter.setValue(Integer.parseInt(m.group(0).trim()));
+ } else {
+ throw new PerforceException("Could not get value of counter!");
+ }
return counter;
}
/*
* (non-Javadoc)
* @see com.tek42.perforce.parse.Builder#save(java.lang.Object, java.io.Writer)
*/
public void save(Counter counter, Writer writer) throws PerforceException {}
/*
* (non-Javadoc)
* @see com.tek42.perforce.parse.Builder#getSaveCmd(T obj)
*/
public boolean requiresStandardInput() {
return false;
}
}
| false | true | public Counter build(StringBuilder sb) throws PerforceException {
final Pattern p = Pattern.compile("^([0-9])*", Pattern.DOTALL | Pattern.MULTILINE);
final Matcher m = p.matcher(sb.toString());
final Counter counter = new Counter();
counter.setName("");
if(m.find()) {
counter.setValue(Integer.parseInt(m.group(0).trim()));
}
return counter;
}
| public Counter build(StringBuilder sb) throws PerforceException {
final Pattern p = Pattern.compile("^([0-9]+)", Pattern.DOTALL | Pattern.MULTILINE);
final Matcher m = p.matcher(sb.toString());
final Counter counter = new Counter();
counter.setName("");
if(m.find()) {
counter.setValue(Integer.parseInt(m.group(0).trim()));
} else {
throw new PerforceException("Could not get value of counter!");
}
return counter;
}
|
diff --git a/src/uk/org/ponder/rsf/components/UIBranchContainer.java b/src/uk/org/ponder/rsf/components/UIBranchContainer.java
index f46a013..fda17dd 100644
--- a/src/uk/org/ponder/rsf/components/UIBranchContainer.java
+++ b/src/uk/org/ponder/rsf/components/UIBranchContainer.java
@@ -1,235 +1,235 @@
/*
* Created on Aug 8, 2005
*/
package uk.org.ponder.rsf.components;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import uk.org.ponder.rsf.util.RSFUtil;
import uk.org.ponder.rsf.util.SplitID;
import uk.org.ponder.stringutil.CharWrap;
/**
* UIBranchContainer represents a "branch point" in the IKAT rendering process,
* rather than simply just a level of component containment.
* <p>
* UIBranchContainer has responsibility for managing naming of child components,
* as well as separate and parallel responsibility for forms. The key to the
* child map is the ID prefix - if the ID has no suffix, the value is the single
* component with that ID at this level. If the ID has a suffix, indicating a
* repetitive domain, the value is an ordered list of components provided by the
* producer which will drive the rendering at this recursion level.
* <p>
* It is assumed that an ID prefix is globally unique within the tree, not just
* within its own recursion level - i.e. IKAT resolution takes place over ALL
* components sharing a prefix throughout the template. This is "safe" since
* "execution" will always return to the call site once the base (XML) nesting
* level at the target is reached again.
* <p>
* "Leaf" rendering classes <it>may</it> be derived from UISimpleContainer -
* only concrete instances of UIBranchContainer will be considered as
* representatives of pure branch points. By the time fixups have concluded, all
* non-branching containers (e.g. UIForms) MUST have been removed from non-leaf
* positions in the component hierarchy.
*
* @author Antranig Basman ([email protected])
*/
public class UIBranchContainer extends UIContainer {
/**
* The localID allows clients to distinguish between multiple instantiations
* of the "same" (by rsf:id) component within the same scope. It forms part of
* the global path constructed by getFullID() which uniquely identifies the
* component.
*/
public String localID = "";
// This is a map to either the single component with a given ID prefix, or a
// list in the case of a repetitive domain (non-null suffix)
private Map childmap = new HashMap();
// this is created by the first call to flatChildren() which is assumed to
// occur during the render phase. Implicit model that component tree is
// i) constructed, ii) rendered, iii) discarded.
// It is worth caching this since it is iterated over up to 4n times during
// rendering, for each HTMLLump headlump that matches the requested call
// in the 4 scopes.
private transient UIComponent[] flatchildren;
/**
* Constructs a "repeating" BranchContainer, uniquely identified by the
* "localID" passed as the 3rd argument. Suitable, for example, for creating a
* table row.
*
* @param parent The parent container to which the returned branch should be
* added.
* @param ID The RSF ID for the branch (must contain a colon character)
* @param localID The local ID identifying this branch instance (must be
* unique for each branch with the same ID in this branch)
*/
public static UIBranchContainer make(UIContainer parent, String ID,
String localID) {
if (ID.indexOf(':') == -1) {
throw new IllegalArgumentException(
"Branch container ID must contain a colon character :");
}
UIBranchContainer togo = new UIBranchContainer();
togo.ID = ID;
togo.localID = localID;
parent.addComponent(togo);
return togo;
}
/**
* Constructs a simple BranchContainer, used to group components or to cause a
* rendering switch. Suitable where there will be just one branch with this ID
* within its container. Where BranchContainers are created in a loop, supply
* a localID by using the {@link #make(UIContainer, String, String)}
* constructor.
*
* @see #make(UIContainer, String, String)
*/
public static UIBranchContainer make(UIContainer parent, String ID) {
return make(parent, ID, "");
}
/**
* Return the single component with the given ID. This should be an ID without
* colon designating a leaf child.
*/
public UIComponent getComponent(String id) {
if (childmap == null)
return null;
Object togo = childmap.get(id);
if (togo != null && !(togo instanceof UIComponent)) {
throw new IllegalArgumentException(
"Error in view tree: component with id " + id
+ " was expected to be a leaf component but was a branch."
+ "\n (did you forget to use a colon in the view template?)");
}
return (UIComponent) togo;
}
/**
* Return all child components with the given prefix. This should be an ID
* containing colon designating a child container.
*/
public List getComponents(String id) {
Object togo = childmap.get(id);
if (togo != null && !(togo instanceof List)) {
throw new IllegalArgumentException(
"Error in view tree: component with id " + id
+ " was expected to be a branch container but was a leaf."
+ "\n (did you forget to use a colon in the component ID?)");
}
return (List) togo;
}
public String debugChildren() {
CharWrap togo = new CharWrap();
togo.append("Child IDs: (");
UIComponent[] children = flatChildren();
for (int i = 0; i < children.length; ++i) {
if (i != 0) {
togo.append(", ");
}
togo.append(children[i].ID);
}
togo.append(")");
return togo.toString();
}
/**
* Returns a flattened array of all children of this container. Note that this
* method will trigger the creation of a cached internal array on its first
* use, which cannot be recreated. It is essential therefore that it only be
* used once ALL modifications to the component tree have concluded (i.e. once
* rendering starts).
*/
public UIComponent[] flatChildren() {
if (flatchildren == null) {
ComponentList children = flattenChildren();
flatchildren = (UIComponent[]) children.toArray(new UIComponent[children
.size()]);
}
return flatchildren;
}
/**
* Returns a list of all CURRENT children of this container. This method is
* safe to use at any time.
*/
// There are now two calls to this in the codebase, firstly from ViewProcessor
// and then from BasicFormFixer. The VP call is necessary since it needs to
// fossilize
// the list up front, but if another call arises as in BFF we ought to write a
// multi-iterator.
public ComponentList flattenChildren() {
ComponentList children = new ComponentList();
for (Iterator childit = childmap.values().iterator(); childit.hasNext();) {
Object child = childit.next();
if (child instanceof UIComponent) {
children.add(child);
}
else if (child instanceof List) {
children.addAll((List) child);
}
}
return children;
}
/** Add a component as a new child of this container */
public void addComponent(UIComponent toadd) {
toadd.parent = this;
SplitID split = new SplitID(toadd.ID);
String childkey = split.prefix;
if (toadd.ID != null && split.suffix == null) {
childmap.put(childkey, toadd);
}
else {
List children = (List) childmap.get(childkey);
if (children == null) {
children = new ArrayList();
childmap.put(childkey, children);
}
else if (toadd instanceof UIBranchContainer) {
UIBranchContainer addbranch = (UIBranchContainer) toadd;
if (addbranch.localID == "") {
throw new IllegalArgumentException(
"Error in component tree: duplicate branch added with full ID " + addbranch.getFullID()
- +": make sure to use the 3-argument UIBranchContainer.make() method when creating branch containers in a loop");
+ +" - make sure to use the 3-argument UIBranchContainer.make() method when creating branch containers in a loop");
// We can't adjust this here in general since when UIBranchContainers are added to a form,
// their IDs will
// addbranch.localID = Integer.toString(children.size());
}
}
children.add(toadd);
}
}
public void remove(UIComponent tomove) {
SplitID split = new SplitID(tomove.ID);
String childkey = split.prefix;
if (split.suffix == null) {
Object tomovetest = childmap.remove(childkey);
if (tomove != tomovetest) {
RSFUtil.failRemove(tomove);
}
}
else {
List children = (List) childmap.get(childkey);
if (children == null) {
RSFUtil.failRemove(tomove);
}
boolean removed = children.remove(tomove);
if (!removed)
RSFUtil.failRemove(tomove);
}
tomove.updateFullID(null); // remove cached ID
}
}
| true | true | public void addComponent(UIComponent toadd) {
toadd.parent = this;
SplitID split = new SplitID(toadd.ID);
String childkey = split.prefix;
if (toadd.ID != null && split.suffix == null) {
childmap.put(childkey, toadd);
}
else {
List children = (List) childmap.get(childkey);
if (children == null) {
children = new ArrayList();
childmap.put(childkey, children);
}
else if (toadd instanceof UIBranchContainer) {
UIBranchContainer addbranch = (UIBranchContainer) toadd;
if (addbranch.localID == "") {
throw new IllegalArgumentException(
"Error in component tree: duplicate branch added with full ID " + addbranch.getFullID()
+": make sure to use the 3-argument UIBranchContainer.make() method when creating branch containers in a loop");
// We can't adjust this here in general since when UIBranchContainers are added to a form,
// their IDs will
// addbranch.localID = Integer.toString(children.size());
}
}
children.add(toadd);
}
}
| public void addComponent(UIComponent toadd) {
toadd.parent = this;
SplitID split = new SplitID(toadd.ID);
String childkey = split.prefix;
if (toadd.ID != null && split.suffix == null) {
childmap.put(childkey, toadd);
}
else {
List children = (List) childmap.get(childkey);
if (children == null) {
children = new ArrayList();
childmap.put(childkey, children);
}
else if (toadd instanceof UIBranchContainer) {
UIBranchContainer addbranch = (UIBranchContainer) toadd;
if (addbranch.localID == "") {
throw new IllegalArgumentException(
"Error in component tree: duplicate branch added with full ID " + addbranch.getFullID()
+" - make sure to use the 3-argument UIBranchContainer.make() method when creating branch containers in a loop");
// We can't adjust this here in general since when UIBranchContainers are added to a form,
// their IDs will
// addbranch.localID = Integer.toString(children.size());
}
}
children.add(toadd);
}
}
|
diff --git a/mpicbg/ij/CLAHE.java b/mpicbg/ij/CLAHE.java
index 5bc2070..510b30d 100644
--- a/mpicbg/ij/CLAHE.java
+++ b/mpicbg/ij/CLAHE.java
@@ -1,450 +1,465 @@
/**
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package mpicbg.ij;
import java.awt.Rectangle;
import java.util.ArrayList;
import ij.IJ;
import ij.ImagePlus;
import ij.Undo;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.gui.Roi;
import ij.plugin.PlugIn;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
/**
* &lsquot;Contrast Limited Adaptive Histogram Equalization&rsquot; as
* described in
*
* <br />BibTeX:
* <pre>
* @article{zuiderveld94,
* author = {Zuiderveld, Karel},
* title = {Contrast limited adaptive histogram equalization},
* book = {Graphics gems IV},
* year = {1994},
* isbn = {0-12-336155-9},
* pages = {474--485},
* publisher = {Academic Press Professional, Inc.},
* address = {San Diego, CA, USA},
* }
* </pre>
*
* @author Stephan Saalfeld <[email protected]>
* @version 0.1b
*/
public class CLAHE implements PlugIn
{
static private int blockRadius = 63;
static private int bins = 255;
static private float slope = 3;
static private ByteProcessor mask = null;
/**
* Clip histogram and redistribute clipped entries.
*
* @param hist source
* @param clippedHist target
* @param limit clip limit
* @param bins number of bins
*/
final static private void clipHistogram(
final int[] hist,
final int[] clippedHist,
final int limit,
final int bins )
{
System.arraycopy( hist, 0, clippedHist, 0, hist.length );
int clippedEntries = 0, clippedEntriesBefore;
do
{
clippedEntriesBefore = clippedEntries;
clippedEntries = 0;
for ( int i = 0; i <= bins; ++i )
{
final int d = clippedHist[ i ] - limit;
if ( d > 0 )
{
clippedEntries += d;
clippedHist[ i ] = limit;
}
}
final int d = clippedEntries / ( bins + 1 );
final int m = clippedEntries % ( bins + 1 );
for ( int i = 0; i <= bins; ++i)
clippedHist[ i ] += d;
if ( m != 0 )
{
final int s = bins / m;
for ( int i = s / 2; i <= bins; i += s )
++clippedHist[ i ];
}
}
while ( clippedEntries != clippedEntriesBefore );
}
/**
* Get the CDF entry of a value.
*
* @param v the value
* @param hist the histogram from which the CDF is collected
* @param bins
* @return
*/
final static private float transferValue(
final int v,
final int[] hist,
final int bins )
{
int hMin = bins;
for ( int i = 0; i < hMin; ++i )
if ( hist[ i ] != 0 ) hMin = i;
int cdf = 0;
for ( int i = hMin; i <= v; ++i )
cdf += hist[ i ];
int cdfMax = cdf;
for ( int i = v + 1; i <= bins; ++i )
cdfMax += hist[ i ];
final int cdfMin = hist[ hMin ];
return ( cdf - cdfMin ) / ( float )( cdfMax - cdfMin );
}
/**
* Transfer a value through contrast limited histogram equalization.
* For efficiency, the histograms to be used are passed as parameters.
*
* @param v
* @param hist
* @param clippedHist
* @param limit
* @param bins
* @return
*/
final static public float transferValue(
final int v,
final int[] hist,
final int[] clippedHist,
final int limit,
final int bins )
{
clipHistogram( hist, clippedHist, limit, bins );
return transferValue( v, clippedHist, bins );
}
final static private boolean setup( final ImagePlus imp )
{
final ArrayList< Integer > ids = new ArrayList< Integer >();
final ArrayList< String > titles = new ArrayList< String >();
titles.add( "*None*" );
ids.add( -1 );
for ( final int id : WindowManager.getIDList() )
{
final ImagePlus impId = WindowManager.getImage( id );
if ( impId.getWidth() == imp.getWidth() && impId.getHeight() == imp.getHeight() )
{
titles.add( impId.getTitle() );
ids.add( id );
}
}
final GenericDialog gd = new GenericDialog( "CLAHE" );
gd.addNumericField( "blocksize : ", blockRadius * 2 + 1, 0 );
gd.addNumericField( "histogram bins : ", bins + 1, 0 );
gd.addNumericField( "maximum slope : ", slope, 2 );
gd.addChoice( "mask : ", titles.toArray( new String[ 0 ] ), titles.get( 0 ) );
gd.addHelp( "http://pacific.mpi-cbg.de/wiki/index.php/Enhance_Local_Contrast_(CLAHE)" );
gd.showDialog();
if ( gd.wasCanceled() ) return false;
blockRadius = ( ( int )gd.getNextNumber() - 1 ) / 2;
bins = ( int )gd.getNextNumber() - 1;
slope = ( float )gd.getNextNumber();
final int maskId = ids.get( gd.getNextChoiceIndex() );
if ( maskId != -1 ) mask = ( ByteProcessor )WindowManager.getImage( maskId ).getProcessor().convertToByte( true );
else mask = null;
return true;
}
final public void run( final String arg )
{
final ImagePlus imp = IJ.getImage();
synchronized ( imp )
{
if ( !imp.isLocked() )
imp.lock();
else
{
IJ.error( "The image '" + imp.getTitle() + "' is in use currently.\nPlease wait until the process is done and try again." );
return;
}
}
if ( !setup( imp ) )
{
imp.unlock();
return;
}
Undo.setup( Undo.TRANSFORM, imp );
run( imp );
imp.unlock();
}
/**
* Process an {@link ImagePlus} with the static parameters. Create mask
* and bounding box from the {@link Roi} of that {@link ImagePlus}.
*
* @param imp
*/
final static public void run( final ImagePlus imp )
{
run( imp, blockRadius, bins, slope, mask );
}
/**
* Process and {@link ImagePlus} with a given set of parameters. Create
* mask and bounding box from the {@link Roi} of that {@link ImagePlus}.
*
* @param imp
* @param blockRadius
* @param bins
* @param slope
*/
final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final ByteProcessor mask )
{
final Roi roi = imp.getRoi();
if ( roi == null )
run( imp, blockRadius, bins, slope, null, mask );
else
{
final Rectangle roiBox = roi.getBounds();
final ImageProcessor roiMask = roi.getMask();
if ( mask != null )
{
final Rectangle oldRoi = mask.getRoi();
mask.setRoi( roi );
final ByteProcessor cropMask = ( ByteProcessor )mask.crop().convertToByte( true );
if ( roiMask != null )
{
final byte[] roiMaskPixels = ( byte[] )roiMask.getPixels();
final byte[] cropMaskPixels = ( byte[] )cropMask.getPixels();
for ( int i = 0; i < roiMaskPixels.length; ++i )
cropMaskPixels[ i ] = ( byte )roundPositive( ( cropMaskPixels[ i ] & 0xff ) * ( roiMaskPixels[ i ] & 0xff ) / 255.0f );
}
run( imp, blockRadius, bins, slope, roiBox, cropMask );
mask.setRoi( oldRoi );
}
else if ( roiMask == null )
run( imp, blockRadius, bins, slope, roiBox, null );
else
run( imp, blockRadius, bins, slope, roiBox, ( ByteProcessor )roiMask.convertToByte( false ) );
}
}
/**
* Process and {@link ImagePlus} with a given set of parameters including
* the bounding box and mask.
*
* @param imp
* @param blockRadius
* @param bins
* @param slope
* @param roiBox can be null
* @param mask can be null
*/
final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final java.awt.Rectangle roiBox,
final ByteProcessor mask )
{
/* initialize box if necessary */
final Rectangle box;
if ( roiBox == null )
{
if ( mask == null )
box = new Rectangle( 0, 0, imp.getWidth(), imp.getHeight() );
else
box = new Rectangle( 0, 0, Math.min( imp.getWidth(), mask.getWidth() ), Math.min( imp.getHeight(), mask.getHeight() ) );
}
else
box = roiBox;
/* make sure that the box is not larger than the mask */
if ( mask != null )
{
box.width = Math.min( mask.getWidth(), box.width );
box.height = Math.min( mask.getHeight(), box.height );
}
/* make sure that the box is not larger than the image */
box.width = Math.min( imp.getWidth() - box.x, box.width );
box.height = Math.min( imp.getHeight() - box.y, box.height );
final int boxXMax = box.x + box.width;
final int boxYMax = box.y + box.height;
/* convert 8bit processors with a LUT to RGB and create Undo-step */
final ImageProcessor ip;
if ( imp.getType() == ImagePlus.COLOR_256 )
{
ip = imp.getProcessor().convertToRGB();
imp.setProcessor( imp.getTitle(), ip );
}
else
ip = imp.getProcessor();
/* work on ByteProcessors that reflect the user defined intensity range */
final ByteProcessor src;
if ( imp.getType() == ImagePlus.GRAY8 )
src = ( ByteProcessor )ip.convertToByte( true ).duplicate();
else
src = ( ByteProcessor )ip.convertToByte( true );
final ByteProcessor dst = ( ByteProcessor )src.duplicate();
for ( int y = box.y; y < boxYMax; ++y )
{
final int yMin = Math.max( 0, y - blockRadius );
final int yMax = Math.min( imp.getHeight(), y + blockRadius + 1 );
final int h = yMax - yMin;
final int xMin0 = Math.max( 0, box.x - blockRadius );
final int xMax0 = Math.min( imp.getWidth() - 1, box.x + blockRadius );
/* initially fill histogram */
final int[] hist = new int[ bins + 1 ];
final int[] clippedHist = new int[ bins + 1 ];
for ( int yi = yMin; yi < yMax; ++yi )
for ( int xi = xMin0; xi < xMax0; ++xi )
++hist[ roundPositive( src.get( xi, yi ) / 255.0f * bins ) ];
for ( int x = box.x; x < boxXMax; ++x )
{
final int v = roundPositive( src.get( x, y ) / 255.0f * bins );
final int xMin = Math.max( 0, x - blockRadius );
final int xMax = x + blockRadius + 1;
final int w = Math.min( imp.getWidth(), xMax ) - xMin;
final int n = h * w;
final int limit;
if ( mask == null )
limit = ( int )( slope * n / bins + 0.5f );
else
limit = ( int )( ( 1 + mask.get( x - box.x, y - box.y ) / 255.0f * ( slope - 1 ) ) * n / bins + 0.5f );
/* remove left behind values from histogram */
if ( xMin > 0 )
{
final int xMin1 = xMin - 1;
for ( int yi = yMin; yi < yMax; ++yi )
--hist[ roundPositive( src.get( xMin1, yi ) / 255.0f * bins ) ];
}
/* add newly included values to histogram */
if ( xMax <= imp.getWidth() )
{
final int xMax1 = xMax - 1;
for ( int yi = yMin; yi < yMax; ++yi )
++hist[ roundPositive( src.get( xMax1, yi ) / 255.0f * bins ) ];
}
dst.set( x, y, roundPositive( transferValue( v, hist, clippedHist, limit, bins ) * 255.0f ) );
}
/* multiply the current row into ip */
final int t = y * imp.getWidth();
if ( imp.getType() == ImagePlus.GRAY8 )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
ip.set( i, dst.get( i ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY16 )
{
final int min = ( int )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int v = ip.get( i );
- final float a = ( float )dst.get( i ) / src.get( i );
+ final float vSrc = src.get( i );
+ final float a;
+ if ( vSrc == 0 )
+ a = 1.0f;
+ else
+ a = ( float )dst.get( i ) / vSrc;
ip.set( i, Math.max( 0, Math.min( 65535, roundPositive( a * ( v - min ) + min ) ) ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY32 )
{
final float min = ( float )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final float v = ip.getf( i );
- final float a = ( float )dst.get( i ) / src.get( i );
+ final float vSrc = src.get( i );
+ final float a;
+ if ( vSrc == 0 )
+ a = 1.0f;
+ else
+ a = ( float )dst.get( i ) / vSrc;
ip.setf( i, a * ( v - min ) + min );
}
}
else if ( imp.getType() == ImagePlus.COLOR_RGB )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int argb = ip.get( i );
- final float a = ( float )dst.get( i ) / src.get( i );
+ final float vSrc = src.get( i );
+ final float a;
+ if ( vSrc == 0 )
+ a = 1.0f;
+ else
+ a = ( float )dst.get( i ) / vSrc;
final int r = Math.max( 0, Math.min( 255, roundPositive( a * ( ( argb >> 16 ) & 0xff ) ) ) );
final int g = Math.max( 0, Math.min( 255, roundPositive( a * ( ( argb >> 8 ) & 0xff ) ) ) );
final int b = Math.max( 0, Math.min( 255, roundPositive( a * ( argb & 0xff ) ) ) );
ip.set( i, ( r << 16 ) | ( g << 8 ) | b );
}
}
imp.updateAndDraw();
}
}
final static private int roundPositive( float a )
{
return ( int )( a + 0.5f );
}
}
| false | true | final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final java.awt.Rectangle roiBox,
final ByteProcessor mask )
{
/* initialize box if necessary */
final Rectangle box;
if ( roiBox == null )
{
if ( mask == null )
box = new Rectangle( 0, 0, imp.getWidth(), imp.getHeight() );
else
box = new Rectangle( 0, 0, Math.min( imp.getWidth(), mask.getWidth() ), Math.min( imp.getHeight(), mask.getHeight() ) );
}
else
box = roiBox;
/* make sure that the box is not larger than the mask */
if ( mask != null )
{
box.width = Math.min( mask.getWidth(), box.width );
box.height = Math.min( mask.getHeight(), box.height );
}
/* make sure that the box is not larger than the image */
box.width = Math.min( imp.getWidth() - box.x, box.width );
box.height = Math.min( imp.getHeight() - box.y, box.height );
final int boxXMax = box.x + box.width;
final int boxYMax = box.y + box.height;
/* convert 8bit processors with a LUT to RGB and create Undo-step */
final ImageProcessor ip;
if ( imp.getType() == ImagePlus.COLOR_256 )
{
ip = imp.getProcessor().convertToRGB();
imp.setProcessor( imp.getTitle(), ip );
}
else
ip = imp.getProcessor();
/* work on ByteProcessors that reflect the user defined intensity range */
final ByteProcessor src;
if ( imp.getType() == ImagePlus.GRAY8 )
src = ( ByteProcessor )ip.convertToByte( true ).duplicate();
else
src = ( ByteProcessor )ip.convertToByte( true );
final ByteProcessor dst = ( ByteProcessor )src.duplicate();
for ( int y = box.y; y < boxYMax; ++y )
{
final int yMin = Math.max( 0, y - blockRadius );
final int yMax = Math.min( imp.getHeight(), y + blockRadius + 1 );
final int h = yMax - yMin;
final int xMin0 = Math.max( 0, box.x - blockRadius );
final int xMax0 = Math.min( imp.getWidth() - 1, box.x + blockRadius );
/* initially fill histogram */
final int[] hist = new int[ bins + 1 ];
final int[] clippedHist = new int[ bins + 1 ];
for ( int yi = yMin; yi < yMax; ++yi )
for ( int xi = xMin0; xi < xMax0; ++xi )
++hist[ roundPositive( src.get( xi, yi ) / 255.0f * bins ) ];
for ( int x = box.x; x < boxXMax; ++x )
{
final int v = roundPositive( src.get( x, y ) / 255.0f * bins );
final int xMin = Math.max( 0, x - blockRadius );
final int xMax = x + blockRadius + 1;
final int w = Math.min( imp.getWidth(), xMax ) - xMin;
final int n = h * w;
final int limit;
if ( mask == null )
limit = ( int )( slope * n / bins + 0.5f );
else
limit = ( int )( ( 1 + mask.get( x - box.x, y - box.y ) / 255.0f * ( slope - 1 ) ) * n / bins + 0.5f );
/* remove left behind values from histogram */
if ( xMin > 0 )
{
final int xMin1 = xMin - 1;
for ( int yi = yMin; yi < yMax; ++yi )
--hist[ roundPositive( src.get( xMin1, yi ) / 255.0f * bins ) ];
}
/* add newly included values to histogram */
if ( xMax <= imp.getWidth() )
{
final int xMax1 = xMax - 1;
for ( int yi = yMin; yi < yMax; ++yi )
++hist[ roundPositive( src.get( xMax1, yi ) / 255.0f * bins ) ];
}
dst.set( x, y, roundPositive( transferValue( v, hist, clippedHist, limit, bins ) * 255.0f ) );
}
/* multiply the current row into ip */
final int t = y * imp.getWidth();
if ( imp.getType() == ImagePlus.GRAY8 )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
ip.set( i, dst.get( i ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY16 )
{
final int min = ( int )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int v = ip.get( i );
final float a = ( float )dst.get( i ) / src.get( i );
ip.set( i, Math.max( 0, Math.min( 65535, roundPositive( a * ( v - min ) + min ) ) ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY32 )
{
final float min = ( float )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final float v = ip.getf( i );
final float a = ( float )dst.get( i ) / src.get( i );
ip.setf( i, a * ( v - min ) + min );
}
}
else if ( imp.getType() == ImagePlus.COLOR_RGB )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int argb = ip.get( i );
final float a = ( float )dst.get( i ) / src.get( i );
final int r = Math.max( 0, Math.min( 255, roundPositive( a * ( ( argb >> 16 ) & 0xff ) ) ) );
final int g = Math.max( 0, Math.min( 255, roundPositive( a * ( ( argb >> 8 ) & 0xff ) ) ) );
final int b = Math.max( 0, Math.min( 255, roundPositive( a * ( argb & 0xff ) ) ) );
ip.set( i, ( r << 16 ) | ( g << 8 ) | b );
}
}
imp.updateAndDraw();
}
}
| final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final java.awt.Rectangle roiBox,
final ByteProcessor mask )
{
/* initialize box if necessary */
final Rectangle box;
if ( roiBox == null )
{
if ( mask == null )
box = new Rectangle( 0, 0, imp.getWidth(), imp.getHeight() );
else
box = new Rectangle( 0, 0, Math.min( imp.getWidth(), mask.getWidth() ), Math.min( imp.getHeight(), mask.getHeight() ) );
}
else
box = roiBox;
/* make sure that the box is not larger than the mask */
if ( mask != null )
{
box.width = Math.min( mask.getWidth(), box.width );
box.height = Math.min( mask.getHeight(), box.height );
}
/* make sure that the box is not larger than the image */
box.width = Math.min( imp.getWidth() - box.x, box.width );
box.height = Math.min( imp.getHeight() - box.y, box.height );
final int boxXMax = box.x + box.width;
final int boxYMax = box.y + box.height;
/* convert 8bit processors with a LUT to RGB and create Undo-step */
final ImageProcessor ip;
if ( imp.getType() == ImagePlus.COLOR_256 )
{
ip = imp.getProcessor().convertToRGB();
imp.setProcessor( imp.getTitle(), ip );
}
else
ip = imp.getProcessor();
/* work on ByteProcessors that reflect the user defined intensity range */
final ByteProcessor src;
if ( imp.getType() == ImagePlus.GRAY8 )
src = ( ByteProcessor )ip.convertToByte( true ).duplicate();
else
src = ( ByteProcessor )ip.convertToByte( true );
final ByteProcessor dst = ( ByteProcessor )src.duplicate();
for ( int y = box.y; y < boxYMax; ++y )
{
final int yMin = Math.max( 0, y - blockRadius );
final int yMax = Math.min( imp.getHeight(), y + blockRadius + 1 );
final int h = yMax - yMin;
final int xMin0 = Math.max( 0, box.x - blockRadius );
final int xMax0 = Math.min( imp.getWidth() - 1, box.x + blockRadius );
/* initially fill histogram */
final int[] hist = new int[ bins + 1 ];
final int[] clippedHist = new int[ bins + 1 ];
for ( int yi = yMin; yi < yMax; ++yi )
for ( int xi = xMin0; xi < xMax0; ++xi )
++hist[ roundPositive( src.get( xi, yi ) / 255.0f * bins ) ];
for ( int x = box.x; x < boxXMax; ++x )
{
final int v = roundPositive( src.get( x, y ) / 255.0f * bins );
final int xMin = Math.max( 0, x - blockRadius );
final int xMax = x + blockRadius + 1;
final int w = Math.min( imp.getWidth(), xMax ) - xMin;
final int n = h * w;
final int limit;
if ( mask == null )
limit = ( int )( slope * n / bins + 0.5f );
else
limit = ( int )( ( 1 + mask.get( x - box.x, y - box.y ) / 255.0f * ( slope - 1 ) ) * n / bins + 0.5f );
/* remove left behind values from histogram */
if ( xMin > 0 )
{
final int xMin1 = xMin - 1;
for ( int yi = yMin; yi < yMax; ++yi )
--hist[ roundPositive( src.get( xMin1, yi ) / 255.0f * bins ) ];
}
/* add newly included values to histogram */
if ( xMax <= imp.getWidth() )
{
final int xMax1 = xMax - 1;
for ( int yi = yMin; yi < yMax; ++yi )
++hist[ roundPositive( src.get( xMax1, yi ) / 255.0f * bins ) ];
}
dst.set( x, y, roundPositive( transferValue( v, hist, clippedHist, limit, bins ) * 255.0f ) );
}
/* multiply the current row into ip */
final int t = y * imp.getWidth();
if ( imp.getType() == ImagePlus.GRAY8 )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
ip.set( i, dst.get( i ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY16 )
{
final int min = ( int )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int v = ip.get( i );
final float vSrc = src.get( i );
final float a;
if ( vSrc == 0 )
a = 1.0f;
else
a = ( float )dst.get( i ) / vSrc;
ip.set( i, Math.max( 0, Math.min( 65535, roundPositive( a * ( v - min ) + min ) ) ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY32 )
{
final float min = ( float )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final float v = ip.getf( i );
final float vSrc = src.get( i );
final float a;
if ( vSrc == 0 )
a = 1.0f;
else
a = ( float )dst.get( i ) / vSrc;
ip.setf( i, a * ( v - min ) + min );
}
}
else if ( imp.getType() == ImagePlus.COLOR_RGB )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int argb = ip.get( i );
final float vSrc = src.get( i );
final float a;
if ( vSrc == 0 )
a = 1.0f;
else
a = ( float )dst.get( i ) / vSrc;
final int r = Math.max( 0, Math.min( 255, roundPositive( a * ( ( argb >> 16 ) & 0xff ) ) ) );
final int g = Math.max( 0, Math.min( 255, roundPositive( a * ( ( argb >> 8 ) & 0xff ) ) ) );
final int b = Math.max( 0, Math.min( 255, roundPositive( a * ( argb & 0xff ) ) ) );
ip.set( i, ( r << 16 ) | ( g << 8 ) | b );
}
}
imp.updateAndDraw();
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java
index 0642621d6..952e91975 100644
--- a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java
+++ b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java
@@ -1,670 +1,670 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g2d;
import static com.badlogic.gdx.graphics.Texture.TextureWrap.*;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Page;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Region;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.Sort;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
/** Loads images from texture atlases created by TexturePacker.<br>
* <br>
* A TextureAtlas must be disposed to free up the resources consumed by the backing textures.
* @author Nathan Sweet */
public class TextureAtlas implements Disposable {
static final String[] tuple = new String[4];
private final HashSet<Texture> textures = new HashSet(4);
private final Array<AtlasRegion> regions = new Array<AtlasRegion>();
public static class TextureAtlasData {
public static class Page {
public final FileHandle textureFile;
public Texture texture;
public final boolean useMipMaps;
public final Format format;
public final TextureFilter minFilter;
public final TextureFilter magFilter;
public final TextureWrap uWrap;
public final TextureWrap vWrap;
public Page (FileHandle handle, boolean useMipMaps, Format format, TextureFilter minFilter, TextureFilter magFilter,
TextureWrap uWrap, TextureWrap vWrap) {
this.textureFile = handle;
this.useMipMaps = useMipMaps;
this.format = format;
this.minFilter = minFilter;
this.magFilter = magFilter;
this.uWrap = uWrap;
this.vWrap = vWrap;
}
}
public static class Region {
public Page page;
public int index;
public String name;
public float offsetX;
public float offsetY;
public int originalWidth;
public int originalHeight;
public boolean rotate;
public int left;
public int top;
public int width;
public int height;
public boolean flip;
public int[] splits;
public int[] pads;
}
final Array<Page> pages = new Array<Page>();
final Array<Region> regions = new Array<Region>();
public TextureAtlasData (FileHandle packFile, FileHandle imagesDir, boolean flip) {
BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64);
try {
Page pageImage = null;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.trim().length() == 0)
pageImage = null;
else if (pageImage == null) {
FileHandle file = imagesDir.child(line);
Format format = Format.valueOf(readValue(reader));
readTuple(reader);
TextureFilter min = TextureFilter.valueOf(tuple[0]);
TextureFilter max = TextureFilter.valueOf(tuple[1]);
String direction = readValue(reader);
TextureWrap repeatX = ClampToEdge;
TextureWrap repeatY = ClampToEdge;
if (direction.equals("x"))
repeatX = Repeat;
else if (direction.equals("y"))
repeatY = Repeat;
else if (direction.equals("xy")) {
repeatX = Repeat;
repeatY = Repeat;
}
pageImage = new Page(file, min.isMipMap(), format, min, max, repeatX, repeatY);
pages.add(pageImage);
} else {
boolean rotate = Boolean.valueOf(readValue(reader));
readTuple(reader);
int left = Integer.parseInt(tuple[0]);
int top = Integer.parseInt(tuple[1]);
readTuple(reader);
int width = Integer.parseInt(tuple[0]);
int height = Integer.parseInt(tuple[1]);
Region region = new Region();
region.page = pageImage;
region.left = left;
region.top = top;
region.width = width;
region.height = height;
region.name = line;
region.rotate = rotate;
if (readTuple(reader) == 4) { // split is optional
region.splits = new int[] {Integer.parseInt(tuple[0]), Integer.parseInt(tuple[1]),
Integer.parseInt(tuple[2]), Integer.parseInt(tuple[3])};
if (readTuple(reader) == 4) { // pad is optional, but only present with splits
region.pads = new int[] {Integer.parseInt(tuple[0]), Integer.parseInt(tuple[1]),
Integer.parseInt(tuple[2]), Integer.parseInt(tuple[3])};
readTuple(reader);
}
}
region.originalWidth = Integer.parseInt(tuple[0]);
region.originalHeight = Integer.parseInt(tuple[1]);
readTuple(reader);
region.offsetX = Integer.parseInt(tuple[0]);
region.offsetY = Integer.parseInt(tuple[1]);
region.index = Integer.parseInt(readValue(reader));
if (flip) region.flip = true;
regions.add(region);
}
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error reading pack file: " + packFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
- new Sort().sort(regions.items, indexComparator, 0, regions.size);
+ new Sort().sort((Object[])regions.items, (Comparator)indexComparator, 0, regions.size);
}
public Array<Page> getPages () {
return pages;
}
public Array<Region> getRegions () {
return regions;
}
}
/** Creates an empty atlas to which regions can be added. */
public TextureAtlas () {
}
/** Loads the specified pack file using {@link FileType#Internal}, using the parent directory of the pack file to find the page
* images. */
public TextureAtlas (String internalPackFile) {
this(Gdx.files.internal(internalPackFile));
}
/** Loads the specified pack file, using the parent directory of the pack file to find the page images. */
public TextureAtlas (FileHandle packFile) {
this(packFile, packFile.parent());
}
/** @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner.
* @see #TextureAtlas(FileHandle) */
public TextureAtlas (FileHandle packFile, boolean flip) {
this(packFile, packFile.parent(), flip);
}
public TextureAtlas (FileHandle packFile, FileHandle imagesDir) {
this(packFile, imagesDir, false);
}
/** @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. */
public TextureAtlas (FileHandle packFile, FileHandle imagesDir, boolean flip) {
this(new TextureAtlasData(packFile, imagesDir, flip));
}
/** @param data May be null. */
public TextureAtlas (TextureAtlasData data) {
if (data != null) load(data);
}
private void load (TextureAtlasData data) {
ObjectMap<Page, Texture> pageToTexture = new ObjectMap<Page, Texture>();
for (Page page : data.pages) {
Texture texture = null;
if (page.texture == null) {
texture = new Texture(page.textureFile, page.format, page.useMipMaps);
texture.setFilter(page.minFilter, page.magFilter);
texture.setWrap(page.uWrap, page.vWrap);
} else {
texture = page.texture;
texture.setFilter(page.minFilter, page.magFilter);
texture.setWrap(page.uWrap, page.vWrap);
}
textures.add(texture);
pageToTexture.put(page, texture);
}
for (Region region : data.regions) {
int width = region.width;
int height = region.height;
AtlasRegion atlasRegion = new AtlasRegion(pageToTexture.get(region.page), region.left, region.top,
region.rotate ? height : width, region.rotate ? width : height);
atlasRegion.index = region.index;
atlasRegion.name = region.name;
atlasRegion.offsetX = region.offsetX;
atlasRegion.offsetY = region.offsetY;
atlasRegion.originalHeight = region.originalHeight;
atlasRegion.originalWidth = region.originalWidth;
atlasRegion.rotate = region.rotate;
atlasRegion.splits = region.splits;
atlasRegion.pads = region.pads;
if (region.flip) atlasRegion.flip(false, true);
regions.add(atlasRegion);
}
}
/** Adds a region to the atlas. The specified texture will be disposed when the atlas is disposed. */
public AtlasRegion addRegion (String name, Texture texture, int x, int y, int width, int height) {
textures.add(texture);
AtlasRegion region = new AtlasRegion(texture, x, y, width, height);
region.name = name;
region.originalWidth = width;
region.originalHeight = height;
region.index = -1;
regions.add(region);
return region;
}
/** Adds a region to the atlas. The texture for the specified region will be disposed when the atlas is disposed. */
public AtlasRegion addRegion (String name, TextureRegion textureRegion) {
return addRegion(name, textureRegion.texture, textureRegion.getRegionX(), textureRegion.getRegionY(),
textureRegion.getRegionWidth(), textureRegion.getRegionHeight());
}
/** Returns all regions in the atlas. */
public Array<AtlasRegion> getRegions () {
return regions;
}
/** Returns the first region found with the specified name. This method uses string comparison to find the region, so the result
* should be cached rather than calling this method multiple times.
* @return The region, or null. */
public AtlasRegion findRegion (String name) {
for (int i = 0, n = regions.size; i < n; i++)
if (regions.get(i).name.equals(name)) return regions.get(i);
return null;
}
/** Returns the first region found with the specified name and index. This method uses string comparison to find the region, so
* the result should be cached rather than calling this method multiple times.
* @return The region, or null. */
public AtlasRegion findRegion (String name, int index) {
for (int i = 0, n = regions.size; i < n; i++) {
AtlasRegion region = regions.get(i);
if (!region.name.equals(name)) continue;
if (region.index != index) continue;
return region;
}
return null;
}
/** Returns all regions with the specified name, ordered by smallest to largest {@link AtlasRegion#index index}. This method
* uses string comparison to find the regions, so the result should be cached rather than calling this method multiple times. */
public Array<AtlasRegion> findRegions (String name) {
Array<AtlasRegion> matched = new Array();
for (int i = 0, n = regions.size; i < n; i++) {
AtlasRegion region = regions.get(i);
if (region.name.equals(name)) matched.add(new AtlasRegion(region));
}
return matched;
}
/** Returns all regions in the atlas as sprites. This method creates a new sprite for each region, so the result should be
* stored rather than calling this method multiple times.
* @see #createSprite(String) */
public Array<Sprite> createSprites () {
Array sprites = new Array(regions.size);
for (int i = 0, n = regions.size; i < n; i++)
sprites.add(newSprite(regions.get(i)));
return sprites;
}
/** Returns the first region found with the specified name as a sprite. If whitespace was stripped from the region when it was
* packed, the sprite is automatically positioned as if whitespace had not been stripped. This method uses string comparison to
* find the region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
* @return The sprite, or null. */
public Sprite createSprite (String name) {
for (int i = 0, n = regions.size; i < n; i++)
if (regions.get(i).name.equals(name)) return newSprite(regions.get(i));
return null;
}
/** Returns the first region found with the specified name and index as a sprite. This method uses string comparison to find the
* region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
* @return The sprite, or null.
* @see #createSprite(String) */
public Sprite createSprite (String name, int index) {
for (int i = 0, n = regions.size; i < n; i++) {
AtlasRegion region = regions.get(i);
if (!region.name.equals(name)) continue;
if (region.index != index) continue;
return newSprite(regions.get(i));
}
return null;
}
/** Returns all regions with the specified name as sprites, ordered by smallest to largest {@link AtlasRegion#index index}. This
* method uses string comparison to find the regions and constructs new sprites, so the result should be cached rather than
* calling this method multiple times.
* @see #createSprite(String) */
public Array<Sprite> createSprites (String name) {
Array<Sprite> matched = new Array();
for (int i = 0, n = regions.size; i < n; i++) {
AtlasRegion region = regions.get(i);
if (region.name.equals(name)) matched.add(newSprite(region));
}
return matched;
}
private Sprite newSprite (AtlasRegion region) {
if (region.packedWidth == region.originalWidth && region.packedHeight == region.originalHeight) {
if (region.rotate) {
Sprite sprite = new Sprite(region);
sprite.setBounds(0, 0, region.getRegionHeight(), region.getRegionWidth());
sprite.rotate90(true);
return sprite;
}
return new Sprite(region);
}
return new AtlasSprite(region);
}
/** Returns the first region found with the specified name as a {@link NinePatch}. The region must have been packed with
* ninepatch splits. This method uses string comparison to find the region and constructs a new ninepatch, so the result should
* be cached rather than calling this method multiple times.
* @return The ninepatch, or null. */
public NinePatch createPatch (String name) {
for (int i = 0, n = regions.size; i < n; i++) {
AtlasRegion region = regions.get(i);
if (region.name.equals(name)) {
int[] splits = region.splits;
if (splits == null) throw new IllegalArgumentException("Region does not have ninepatch splits: " + name);
NinePatch patch = new NinePatch(region, splits[0], splits[1], splits[2], splits[3]);
if (region.pads != null) patch.setPadding(region.pads[0], region.pads[1], region.pads[2], region.pads[3]);
return patch;
}
}
return null;
}
/** @return the textures of the pages, unordered */
public Set<Texture> getTextures () {
return textures;
}
/** Releases all resources associated with this TextureAtlas instance. This releases all the textures backing all TextureRegions
* and Sprites, which should no longer be used after calling dispose. */
public void dispose () {
for (Texture texture : textures)
texture.dispose();
textures.clear();
}
static final Comparator<Region> indexComparator = new Comparator<Region>() {
public int compare (Region region1, Region region2) {
int i1 = region1.index;
if (i1 == -1) i1 = Integer.MAX_VALUE;
int i2 = region2.index;
if (i2 == -1) i2 = Integer.MAX_VALUE;
return i1 - i2;
}
};
static String readValue (BufferedReader reader) throws IOException {
String line = reader.readLine();
int colon = line.indexOf(':');
if (colon == -1) throw new GdxRuntimeException("Invalid line: " + line);
return line.substring(colon + 1).trim();
}
/** Returns the number of tuple values read (2 or 4). */
static int readTuple (BufferedReader reader) throws IOException {
String line = reader.readLine();
int colon = line.indexOf(':');
if (colon == -1) throw new GdxRuntimeException("Invalid line: " + line);
int i = 0, lastMatch = colon + 1;
for (i = 0; i < 3; i++) {
int comma = line.indexOf(',', lastMatch);
if (comma == -1) {
if (i == 0) throw new GdxRuntimeException("Invalid line: " + line);
break;
}
tuple[i] = line.substring(lastMatch, comma).trim();
lastMatch = comma + 1;
}
tuple[i] = line.substring(lastMatch).trim();
return i + 1;
}
/** Describes the region of a packed image and provides information about the original image before it was packed. */
static public class AtlasRegion extends TextureRegion {
/** The number at the end of the original image file name, or -1 if none.<br>
* <br>
* When sprites are packed, if the original file name ends with a number, it is stored as the index and is not considered as
* part of the sprite's name. This is useful for keeping animation frames in order.
* @see TextureAtlas#findRegions(String) */
public int index;
/** The name of the original image file, up to the first underscore. Underscores denote special instructions to the texture
* packer. */
public String name;
/** The offset from the left of the original image to the left of the packed image, after whitespace was removed for packing. */
public float offsetX;
/** The offset from the bottom of the original image to the bottom of the packed image, after whitespace was removed for
* packing. */
public float offsetY;
/** The width of the image, after whitespace was removed for packing. */
public int packedWidth;
/** The height of the image, after whitespace was removed for packing. */
public int packedHeight;
/** The width of the image, before whitespace was removed and rotation was applied for packing. */
public int originalWidth;
/** The height of the image, before whitespace was removed for packing. */
public int originalHeight;
/** If true, the region has been rotated 90 degrees counter clockwise. */
public boolean rotate;
/** The ninepatch splits, or null if not a ninepatch. Has 4 elements: left, right, top, bottom. */
public int[] splits;
/** The ninepatch pads, or null if not a ninepatch or the has no padding. Has 4 elements: left, right, top, bottom. */
public int[] pads;
public AtlasRegion (Texture texture, int x, int y, int width, int height) {
super(texture, x, y, width, height);
originalWidth = width;
originalHeight = height;
packedWidth = width;
packedHeight = height;
}
public AtlasRegion (AtlasRegion region) {
setRegion(region);
index = region.index;
name = region.name;
offsetX = region.offsetX;
offsetY = region.offsetY;
packedWidth = region.packedWidth;
packedHeight = region.packedHeight;
originalWidth = region.originalWidth;
originalHeight = region.originalHeight;
rotate = region.rotate;
splits = region.splits;
}
/** Flips the region, adjusting the offset so the image appears to be flip as if no whitespace has been removed for packing. */
public void flip (boolean x, boolean y) {
super.flip(x, y);
if (x) offsetX = originalWidth - offsetX - getRotatedPackedWidth();
if (y) offsetY = originalHeight - offsetY - getRotatedPackedHeight();
}
/** Returns the packed width considering the rotate value, if it is true then it returns the packedHeight, otherwise it
* returns the packedWidth. */
public float getRotatedPackedWidth () {
return rotate ? packedHeight : packedWidth;
}
/** Returns the packed height considering the rotate value, if it is true then it returns the packedWidth, otherwise it
* returns the packedHeight. */
public float getRotatedPackedHeight () {
return rotate ? packedWidth : packedHeight;
}
}
/** A sprite that, if whitespace was stripped from the region when it was packed, is automatically positioned as if whitespace
* had not been stripped. */
static public class AtlasSprite extends Sprite {
final AtlasRegion region;
float originalOffsetX, originalOffsetY;
public AtlasSprite (AtlasRegion region) {
this.region = new AtlasRegion(region);
originalOffsetX = region.offsetX;
originalOffsetY = region.offsetY;
setRegion(region);
setOrigin(region.originalWidth / 2f, region.originalHeight / 2f);
int width = region.getRegionWidth();
int height = region.getRegionHeight();
if (region.rotate) {
super.rotate90(true);
super.setBounds(region.offsetX, region.offsetY, height, width);
} else
super.setBounds(region.offsetX, region.offsetY, width, height);
setColor(1, 1, 1, 1);
}
public AtlasSprite (AtlasSprite sprite) {
region = sprite.region;
this.originalOffsetX = sprite.originalOffsetX;
this.originalOffsetY = sprite.originalOffsetY;
set(sprite);
}
public void setPosition (float x, float y) {
super.setPosition(x + region.offsetX, y + region.offsetY);
}
public void setBounds (float x, float y, float width, float height) {
float widthRatio = width / region.originalWidth;
float heightRatio = height / region.originalHeight;
region.offsetX = originalOffsetX * widthRatio;
region.offsetY = originalOffsetY * heightRatio;
int packedWidth = region.rotate ? region.packedHeight : region.packedWidth;
int packedHeight = region.rotate ? region.packedWidth : region.packedHeight;
super.setBounds(x + region.offsetX, y + region.offsetY, packedWidth * widthRatio, packedHeight * heightRatio);
}
public void setSize (float width, float height) {
setBounds(getX(), getY(), width, height);
}
public void setOrigin (float originX, float originY) {
super.setOrigin(originX - region.offsetX, originY - region.offsetY);
}
public void flip (boolean x, boolean y) {
// Flip texture.
super.flip(x, y);
float oldOriginX = getOriginX();
float oldOriginY = getOriginY();
float oldOffsetX = region.offsetX;
float oldOffsetY = region.offsetY;
float widthRatio = getWidthRatio();
float heightRatio = getHeightRatio();
region.offsetX = originalOffsetX;
region.offsetY = originalOffsetY;
region.flip(x, y); // Updates x and y offsets.
originalOffsetX = region.offsetX;
originalOffsetY = region.offsetY;
region.offsetX *= widthRatio;
region.offsetY *= heightRatio;
// Update position and origin with new offsets.
translate(region.offsetX - oldOffsetX, region.offsetY - oldOffsetY);
setOrigin(oldOriginX, oldOriginY);
}
public void rotate90 (boolean clockwise) {
// Rotate texture.
super.rotate90(clockwise);
float oldOriginX = getOriginX();
float oldOriginY = getOriginY();
float oldOffsetX = region.offsetX;
float oldOffsetY = region.offsetY;
float widthRatio = getWidthRatio();
float heightRatio = getHeightRatio();
if (clockwise) {
region.offsetX = oldOffsetY;
region.offsetY = region.originalHeight * heightRatio - oldOffsetX - region.packedWidth * widthRatio;
} else {
region.offsetX = region.originalWidth * widthRatio - oldOffsetY - region.packedHeight * heightRatio;
region.offsetY = oldOffsetX;
}
// Update position and origin with new offsets.
translate(region.offsetX - oldOffsetX, region.offsetY - oldOffsetY);
setOrigin(oldOriginX, oldOriginY);
}
public float getX () {
return super.getX() - region.offsetX;
}
public float getY () {
return super.getY() - region.offsetY;
}
public float getOriginX () {
return super.getOriginX() + region.offsetX;
}
public float getOriginY () {
return super.getOriginY() + region.offsetY;
}
public float getWidth () {
return super.getWidth() / region.getRotatedPackedWidth() * region.originalWidth;
}
public float getHeight () {
return super.getHeight() / region.getRotatedPackedHeight() * region.originalHeight;
}
public float getWidthRatio () {
return super.getWidth() / region.getRotatedPackedWidth();
}
public float getHeightRatio () {
return super.getHeight() / region.getRotatedPackedHeight();
}
public AtlasRegion getAtlasRegion () {
return region;
}
}
}
| true | true | public TextureAtlasData (FileHandle packFile, FileHandle imagesDir, boolean flip) {
BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64);
try {
Page pageImage = null;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.trim().length() == 0)
pageImage = null;
else if (pageImage == null) {
FileHandle file = imagesDir.child(line);
Format format = Format.valueOf(readValue(reader));
readTuple(reader);
TextureFilter min = TextureFilter.valueOf(tuple[0]);
TextureFilter max = TextureFilter.valueOf(tuple[1]);
String direction = readValue(reader);
TextureWrap repeatX = ClampToEdge;
TextureWrap repeatY = ClampToEdge;
if (direction.equals("x"))
repeatX = Repeat;
else if (direction.equals("y"))
repeatY = Repeat;
else if (direction.equals("xy")) {
repeatX = Repeat;
repeatY = Repeat;
}
pageImage = new Page(file, min.isMipMap(), format, min, max, repeatX, repeatY);
pages.add(pageImage);
} else {
boolean rotate = Boolean.valueOf(readValue(reader));
readTuple(reader);
int left = Integer.parseInt(tuple[0]);
int top = Integer.parseInt(tuple[1]);
readTuple(reader);
int width = Integer.parseInt(tuple[0]);
int height = Integer.parseInt(tuple[1]);
Region region = new Region();
region.page = pageImage;
region.left = left;
region.top = top;
region.width = width;
region.height = height;
region.name = line;
region.rotate = rotate;
if (readTuple(reader) == 4) { // split is optional
region.splits = new int[] {Integer.parseInt(tuple[0]), Integer.parseInt(tuple[1]),
Integer.parseInt(tuple[2]), Integer.parseInt(tuple[3])};
if (readTuple(reader) == 4) { // pad is optional, but only present with splits
region.pads = new int[] {Integer.parseInt(tuple[0]), Integer.parseInt(tuple[1]),
Integer.parseInt(tuple[2]), Integer.parseInt(tuple[3])};
readTuple(reader);
}
}
region.originalWidth = Integer.parseInt(tuple[0]);
region.originalHeight = Integer.parseInt(tuple[1]);
readTuple(reader);
region.offsetX = Integer.parseInt(tuple[0]);
region.offsetY = Integer.parseInt(tuple[1]);
region.index = Integer.parseInt(readValue(reader));
if (flip) region.flip = true;
regions.add(region);
}
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error reading pack file: " + packFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
new Sort().sort(regions.items, indexComparator, 0, regions.size);
}
| public TextureAtlasData (FileHandle packFile, FileHandle imagesDir, boolean flip) {
BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64);
try {
Page pageImage = null;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.trim().length() == 0)
pageImage = null;
else if (pageImage == null) {
FileHandle file = imagesDir.child(line);
Format format = Format.valueOf(readValue(reader));
readTuple(reader);
TextureFilter min = TextureFilter.valueOf(tuple[0]);
TextureFilter max = TextureFilter.valueOf(tuple[1]);
String direction = readValue(reader);
TextureWrap repeatX = ClampToEdge;
TextureWrap repeatY = ClampToEdge;
if (direction.equals("x"))
repeatX = Repeat;
else if (direction.equals("y"))
repeatY = Repeat;
else if (direction.equals("xy")) {
repeatX = Repeat;
repeatY = Repeat;
}
pageImage = new Page(file, min.isMipMap(), format, min, max, repeatX, repeatY);
pages.add(pageImage);
} else {
boolean rotate = Boolean.valueOf(readValue(reader));
readTuple(reader);
int left = Integer.parseInt(tuple[0]);
int top = Integer.parseInt(tuple[1]);
readTuple(reader);
int width = Integer.parseInt(tuple[0]);
int height = Integer.parseInt(tuple[1]);
Region region = new Region();
region.page = pageImage;
region.left = left;
region.top = top;
region.width = width;
region.height = height;
region.name = line;
region.rotate = rotate;
if (readTuple(reader) == 4) { // split is optional
region.splits = new int[] {Integer.parseInt(tuple[0]), Integer.parseInt(tuple[1]),
Integer.parseInt(tuple[2]), Integer.parseInt(tuple[3])};
if (readTuple(reader) == 4) { // pad is optional, but only present with splits
region.pads = new int[] {Integer.parseInt(tuple[0]), Integer.parseInt(tuple[1]),
Integer.parseInt(tuple[2]), Integer.parseInt(tuple[3])};
readTuple(reader);
}
}
region.originalWidth = Integer.parseInt(tuple[0]);
region.originalHeight = Integer.parseInt(tuple[1]);
readTuple(reader);
region.offsetX = Integer.parseInt(tuple[0]);
region.offsetY = Integer.parseInt(tuple[1]);
region.index = Integer.parseInt(readValue(reader));
if (flip) region.flip = true;
regions.add(region);
}
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error reading pack file: " + packFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
new Sort().sort((Object[])regions.items, (Comparator)indexComparator, 0, regions.size);
}
|
diff --git a/source/de/anomic/crawler/CrawlStacker.java b/source/de/anomic/crawler/CrawlStacker.java
index bebe0f788..c3cf24db4 100644
--- a/source/de/anomic/crawler/CrawlStacker.java
+++ b/source/de/anomic/crawler/CrawlStacker.java
@@ -1,358 +1,355 @@
// plasmaCrawlStacker.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
//
// This file was contributed by Martin Thelian
// ([MC] removed all multithreading and thread pools, this is not necessary here; complete renovation 2007)
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.crawler;
import java.net.UnknownHostException;
import java.util.Date;
import de.anomic.index.indexReferenceBlacklist;
import de.anomic.index.indexURLReference;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaWordIndex;
import de.anomic.server.serverDomains;
import de.anomic.server.serverProcessor;
import de.anomic.server.logging.serverLog;
import de.anomic.yacy.yacyURL;
public final class CrawlStacker {
final serverLog log = new serverLog("STACKCRAWL");
private serverProcessor<CrawlEntry> fastQueue, slowQueue;
private long dnsHit, dnsMiss;
private CrawlQueues nextQueue;
private plasmaWordIndex wordIndex;
private boolean acceptLocalURLs, acceptGlobalURLs;
// this is the process that checks url for double-occurrences and for allowance/disallowance by robots.txt
public CrawlStacker(CrawlQueues cq, plasmaWordIndex wordIndex, boolean acceptLocalURLs, boolean acceptGlobalURLs) {
this.nextQueue = cq;
this.wordIndex = wordIndex;
this.dnsHit = 0;
this.dnsMiss = 0;
this.acceptLocalURLs = acceptLocalURLs;
this.acceptGlobalURLs = acceptGlobalURLs;
this.fastQueue = new serverProcessor<CrawlEntry>("CrawlStackerFast", "This process checks new urls before they are enqueued into the balancer (proper, double-check, correct domain, filter)", new String[]{"Balancer"}, this, "job", 10000, null, 2);
this.slowQueue = new serverProcessor<CrawlEntry>("CrawlStackerSlow", "This is like CrawlStackerFast, but does additionaly a DNS lookup. The CrawlStackerFast does not need this because it can use the DNS cache.", new String[]{"Balancer"}, this, "job", 1000, null, 5);
this.log.logInfo("STACKCRAWL thread initialized.");
}
public int size() {
return this.fastQueue.queueSize() + this.slowQueue.queueSize();
}
public void clear() {
this.fastQueue.clear();
this.slowQueue.clear();
}
public void announceClose() {
this.log.logInfo("Flushing remaining " + size() + " crawl stacker job entries.");
this.fastQueue.announceShutdown();
this.slowQueue.announceShutdown();
}
public void close() {
this.log.logInfo("Shutdown. waiting for remaining " + size() + " crawl stacker job entries. please wait.");
this.fastQueue.announceShutdown();
this.slowQueue.announceShutdown();
this.fastQueue.awaitShutdown(2000);
this.slowQueue.awaitShutdown(2000);
this.log.logInfo("Shutdown. Closing stackCrawl queue.");
clear();
}
private boolean prefetchHost(final String host) {
// returns true when the host was known in the dns cache.
// If not, the host is stacked on the fetch stack and false is returned
try {
if (serverDomains.dnsResolveFromCache(host) != null) return true; // found entry
} catch (final UnknownHostException e) {
// we know that this is unknown
return false;
}
// we just don't know anything about that host
return false;
}
/*
public boolean job() {
if (this.fastQueue.queueSize() > 0 && job(this.fastQueue)) return true;
if (this.slowQueue.queueSize() == 0) return false;
return job(this.slowQueue);
}
*/
public CrawlEntry job(CrawlEntry entry) {
// this is the method that is called by the busy thread from outside
if (entry == null) return null;
try {
final String rejectReason = stackCrawl(entry);
// if the url was rejected we store it into the error URL db
if (rejectReason != null) {
final ZURL.Entry ee = nextQueue.errorURL.newEntry(entry, wordIndex.seedDB.mySeed().hash, new Date(), 1, rejectReason);
ee.store();
nextQueue.errorURL.push(ee);
}
} catch (final Exception e) {
CrawlStacker.this.log.logWarning("Error while processing stackCrawl entry.\n" + "Entry: " + entry.toString() + "Error: " + e.toString(), e);
return null;
}
return null;
}
public void enqueueEntry(final CrawlEntry entry) {
// DEBUG
if (log.isFinest()) log.logFinest("ENQUEUE "+ entry.url() +", referer="+entry.referrerhash() +", initiator="+entry.initiator() +", name="+entry.name() +", load="+entry.loaddate() +", depth="+entry.depth());
if (prefetchHost(entry.url().getHost())) {
try {
this.fastQueue.enQueue(entry);
this.dnsHit++;
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
this.slowQueue.enQueue(entry);
this.dnsMiss++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String stackCrawl(final CrawlEntry entry) {
// stacks a crawl item. The position can also be remote
// returns null if successful, a reason string if not successful
//this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
final long startTime = System.currentTimeMillis();
String reason = null; // failure reason
// check if the protocol is supported
final String urlProtocol = entry.url().getProtocol();
if (!nextQueue.isSupportedProtocol(urlProtocol)) {
reason = "unsupported protocol";
this.log.logSevere("Unsupported protocol in URL '" + entry.url().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check if ip is local ip address
final String urlRejectReason = urlInAcceptedDomain(entry.url());
if (urlRejectReason != null) {
reason = "denied_(" + urlRejectReason + ")";
if (this.log.isFine()) this.log.logFine(reason + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check blacklist
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_CRAWLER, entry.url())) {
reason = "url in blacklist";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is in blacklist. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
final CrawlProfile.entry profile = wordIndex.profilesActiveCrawls.getEntry(entry.profileHandle());
if (profile == null) {
final String errorMsg = "LOST STACKER PROFILE HANDLE '" + entry.profileHandle() + "' for URL " + entry.url();
log.logWarning(errorMsg);
return errorMsg;
}
// filter with must-match
if ((entry.depth() > 0) && !profile.mustMatchPattern().matcher(entry.url().toString()).matches()) {
reason = "url does not match must-match filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' does not match must-match crawling filter '" + profile.mustMatchPattern().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// filter with must-not-match
if ((entry.depth() > 0) && profile.mustNotMatchPattern().matcher(entry.url().toString()).matches()) {
reason = "url matches must-not-match filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' does matches do-not-match crawling filter '" + profile.mustNotMatchPattern().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny cgi
if (entry.url().isCGI()) {
reason = "cgi url not allowed";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is CGI URL. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny post properties
if (entry.url().isPOST() && !(profile.crawlingQ())) {
reason = "post url not allowed";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is post URL. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
final yacyURL referrerURL = (entry.referrerhash() == null) ? null : nextQueue.getURL(entry.referrerhash());
// add domain to profile domain list
if ((profile.domFilterDepth() != Integer.MAX_VALUE) || (profile.domMaxPages() != Integer.MAX_VALUE)) {
profile.domInc(entry.url().getHost(), (referrerURL == null) ? null : referrerURL.getHost().toLowerCase(), entry.depth());
}
// deny urls that do not match with the profile domain list
if (!(profile.grantedDomAppearance(entry.url().getHost()))) {
reason = "url does not match domain filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is not listed in granted domains. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny urls that exceed allowed number of occurrences
if (!(profile.grantedDomCount(entry.url().getHost()))) {
reason = "domain counter exceeded";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' appeared too often, a maximum of " + profile.domMaxPages() + " is allowed. "+
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check if the url is double registered
final String dbocc = nextQueue.urlExists(entry.url().hash());
if (dbocc != null || wordIndex.existsURL(entry.url().hash())) {
final indexURLReference oldEntry = wordIndex.getURL(entry.url().hash(), null, 0);
final boolean recrawl = (oldEntry != null) && (profile.recrawlIfOlder() > oldEntry.loaddate().getTime());
// do double-check
if ((dbocc != null) && (!recrawl)) {
reason = "double " + dbocc + ")";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is double registered in '" + dbocc + "'. " + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
if ((oldEntry != null) && (!recrawl)) {
reason = "double " + "LURL)";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is double registered in 'LURL'. " + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// show potential re-crawl
if (recrawl && oldEntry != null) {
if (this.log.isFine()) this.log.logFine("RE-CRAWL of URL '" + entry.url().toString() + "': this url was crawled " +
((System.currentTimeMillis() - oldEntry.loaddate().getTime()) / 60000 / 60 / 24) + " days ago.");
}
}
// store information
final boolean local = entry.initiator().equals(wordIndex.seedDB.mySeed().hash);
final boolean proxy = (entry.initiator() == null || entry.initiator().equals("------------")) && profile.handle().equals(wordIndex.defaultProxyProfile.handle());
final boolean remote = profile.handle().equals(wordIndex.defaultRemoteProfile.handle());
final boolean global =
(profile.remoteIndexing()) /* granted */ &&
(entry.depth() == profile.depth()) /* leaf node */ &&
//(initiatorHash.equals(yacyCore.seedDB.mySeed.hash)) /* not proxy */ &&
(
(wordIndex.seedDB.mySeed().isSenior()) ||
(wordIndex.seedDB.mySeed().isPrincipal())
) /* qualified */;
if (!local && !global && !remote && !proxy) {
this.log.logSevere("URL '" + entry.url().toString() + "' cannot be crawled. initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
} else {
if (global) {
// it may be possible that global == true and local == true, so do not check an error case against it
if (proxy) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: global = true, proxy = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: global = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_LIMIT, entry);
- }
- if (local) {
+ } else if (local) {
if (proxy) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: local = true, proxy = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: local = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_CORE, entry);
- }
- if (proxy) {
+ } else if (proxy) {
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: proxy = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_CORE, entry);
- }
- if (remote) {
+ } else if (remote) {
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_REMOTE, entry);
}
}
return null;
}
/**
* Test a url if it can be used for crawling/indexing
* This mainly checks if the url is in the declared domain (local/global)
* @param url
* @return null if the url can be accepted, a string containing a rejection reason if the url cannot be accepted
*/
public String urlInAcceptedDomain(final yacyURL url) {
// returns true if the url can be accepted accoring to network.unit.domain
if (url == null) return "url is null";
final String host = url.getHost();
if (host == null) return "url.host is null";
if (this.acceptGlobalURLs && this.acceptLocalURLs) return null; // fast shortcut to avoid dnsResolve
/*
InetAddress hostAddress = serverDomains.dnsResolve(host);
// if we don't know the host, we cannot load that resource anyway.
// But in case we use a proxy, it is possible that we dont have a DNS service.
final httpRemoteProxyConfig remoteProxyConfig = httpdProxyHandler.getRemoteProxyConfig();
if (hostAddress == null) {
if ((remoteProxyConfig != null) && (remoteProxyConfig.useProxy())) return null; else return "the dns of the host '" + host + "' cannot be resolved";
}
*/
// check if this is a local address and we are allowed to index local pages:
//boolean local = hostAddress.isSiteLocalAddress() || hostAddress.isLoopbackAddress();
final boolean local = url.isLocal();
//assert local == yacyURL.isLocalDomain(url.hash()); // TODO: remove the dnsResolve above!
if ((this.acceptGlobalURLs && !local) || (this.acceptLocalURLs && local)) return null;
return (local) ?
("the host '" + host + "' is local, but local addresses are not accepted") :
("the host '" + host + "' is global, but global addresses are not accepted");
}
public boolean acceptLocalURLs() {
return this.acceptLocalURLs;
}
public boolean acceptGlobalURLs() {
return this.acceptGlobalURLs;
}
}
| false | true | public String stackCrawl(final CrawlEntry entry) {
// stacks a crawl item. The position can also be remote
// returns null if successful, a reason string if not successful
//this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
final long startTime = System.currentTimeMillis();
String reason = null; // failure reason
// check if the protocol is supported
final String urlProtocol = entry.url().getProtocol();
if (!nextQueue.isSupportedProtocol(urlProtocol)) {
reason = "unsupported protocol";
this.log.logSevere("Unsupported protocol in URL '" + entry.url().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check if ip is local ip address
final String urlRejectReason = urlInAcceptedDomain(entry.url());
if (urlRejectReason != null) {
reason = "denied_(" + urlRejectReason + ")";
if (this.log.isFine()) this.log.logFine(reason + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check blacklist
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_CRAWLER, entry.url())) {
reason = "url in blacklist";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is in blacklist. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
final CrawlProfile.entry profile = wordIndex.profilesActiveCrawls.getEntry(entry.profileHandle());
if (profile == null) {
final String errorMsg = "LOST STACKER PROFILE HANDLE '" + entry.profileHandle() + "' for URL " + entry.url();
log.logWarning(errorMsg);
return errorMsg;
}
// filter with must-match
if ((entry.depth() > 0) && !profile.mustMatchPattern().matcher(entry.url().toString()).matches()) {
reason = "url does not match must-match filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' does not match must-match crawling filter '" + profile.mustMatchPattern().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// filter with must-not-match
if ((entry.depth() > 0) && profile.mustNotMatchPattern().matcher(entry.url().toString()).matches()) {
reason = "url matches must-not-match filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' does matches do-not-match crawling filter '" + profile.mustNotMatchPattern().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny cgi
if (entry.url().isCGI()) {
reason = "cgi url not allowed";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is CGI URL. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny post properties
if (entry.url().isPOST() && !(profile.crawlingQ())) {
reason = "post url not allowed";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is post URL. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
final yacyURL referrerURL = (entry.referrerhash() == null) ? null : nextQueue.getURL(entry.referrerhash());
// add domain to profile domain list
if ((profile.domFilterDepth() != Integer.MAX_VALUE) || (profile.domMaxPages() != Integer.MAX_VALUE)) {
profile.domInc(entry.url().getHost(), (referrerURL == null) ? null : referrerURL.getHost().toLowerCase(), entry.depth());
}
// deny urls that do not match with the profile domain list
if (!(profile.grantedDomAppearance(entry.url().getHost()))) {
reason = "url does not match domain filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is not listed in granted domains. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny urls that exceed allowed number of occurrences
if (!(profile.grantedDomCount(entry.url().getHost()))) {
reason = "domain counter exceeded";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' appeared too often, a maximum of " + profile.domMaxPages() + " is allowed. "+
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check if the url is double registered
final String dbocc = nextQueue.urlExists(entry.url().hash());
if (dbocc != null || wordIndex.existsURL(entry.url().hash())) {
final indexURLReference oldEntry = wordIndex.getURL(entry.url().hash(), null, 0);
final boolean recrawl = (oldEntry != null) && (profile.recrawlIfOlder() > oldEntry.loaddate().getTime());
// do double-check
if ((dbocc != null) && (!recrawl)) {
reason = "double " + dbocc + ")";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is double registered in '" + dbocc + "'. " + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
if ((oldEntry != null) && (!recrawl)) {
reason = "double " + "LURL)";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is double registered in 'LURL'. " + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// show potential re-crawl
if (recrawl && oldEntry != null) {
if (this.log.isFine()) this.log.logFine("RE-CRAWL of URL '" + entry.url().toString() + "': this url was crawled " +
((System.currentTimeMillis() - oldEntry.loaddate().getTime()) / 60000 / 60 / 24) + " days ago.");
}
}
// store information
final boolean local = entry.initiator().equals(wordIndex.seedDB.mySeed().hash);
final boolean proxy = (entry.initiator() == null || entry.initiator().equals("------------")) && profile.handle().equals(wordIndex.defaultProxyProfile.handle());
final boolean remote = profile.handle().equals(wordIndex.defaultRemoteProfile.handle());
final boolean global =
(profile.remoteIndexing()) /* granted */ &&
(entry.depth() == profile.depth()) /* leaf node */ &&
//(initiatorHash.equals(yacyCore.seedDB.mySeed.hash)) /* not proxy */ &&
(
(wordIndex.seedDB.mySeed().isSenior()) ||
(wordIndex.seedDB.mySeed().isPrincipal())
) /* qualified */;
if (!local && !global && !remote && !proxy) {
this.log.logSevere("URL '" + entry.url().toString() + "' cannot be crawled. initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
} else {
if (global) {
// it may be possible that global == true and local == true, so do not check an error case against it
if (proxy) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: global = true, proxy = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: global = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_LIMIT, entry);
}
if (local) {
if (proxy) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: local = true, proxy = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: local = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_CORE, entry);
}
if (proxy) {
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: proxy = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_CORE, entry);
}
if (remote) {
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_REMOTE, entry);
}
}
return null;
}
| public String stackCrawl(final CrawlEntry entry) {
// stacks a crawl item. The position can also be remote
// returns null if successful, a reason string if not successful
//this.log.logFinest("stackCrawl: nexturlString='" + nexturlString + "'");
final long startTime = System.currentTimeMillis();
String reason = null; // failure reason
// check if the protocol is supported
final String urlProtocol = entry.url().getProtocol();
if (!nextQueue.isSupportedProtocol(urlProtocol)) {
reason = "unsupported protocol";
this.log.logSevere("Unsupported protocol in URL '" + entry.url().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check if ip is local ip address
final String urlRejectReason = urlInAcceptedDomain(entry.url());
if (urlRejectReason != null) {
reason = "denied_(" + urlRejectReason + ")";
if (this.log.isFine()) this.log.logFine(reason + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check blacklist
if (plasmaSwitchboard.urlBlacklist.isListed(indexReferenceBlacklist.BLACKLIST_CRAWLER, entry.url())) {
reason = "url in blacklist";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is in blacklist. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
final CrawlProfile.entry profile = wordIndex.profilesActiveCrawls.getEntry(entry.profileHandle());
if (profile == null) {
final String errorMsg = "LOST STACKER PROFILE HANDLE '" + entry.profileHandle() + "' for URL " + entry.url();
log.logWarning(errorMsg);
return errorMsg;
}
// filter with must-match
if ((entry.depth() > 0) && !profile.mustMatchPattern().matcher(entry.url().toString()).matches()) {
reason = "url does not match must-match filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' does not match must-match crawling filter '" + profile.mustMatchPattern().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// filter with must-not-match
if ((entry.depth() > 0) && profile.mustNotMatchPattern().matcher(entry.url().toString()).matches()) {
reason = "url matches must-not-match filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' does matches do-not-match crawling filter '" + profile.mustNotMatchPattern().toString() + "'. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny cgi
if (entry.url().isCGI()) {
reason = "cgi url not allowed";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is CGI URL. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny post properties
if (entry.url().isPOST() && !(profile.crawlingQ())) {
reason = "post url not allowed";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is post URL. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
final yacyURL referrerURL = (entry.referrerhash() == null) ? null : nextQueue.getURL(entry.referrerhash());
// add domain to profile domain list
if ((profile.domFilterDepth() != Integer.MAX_VALUE) || (profile.domMaxPages() != Integer.MAX_VALUE)) {
profile.domInc(entry.url().getHost(), (referrerURL == null) ? null : referrerURL.getHost().toLowerCase(), entry.depth());
}
// deny urls that do not match with the profile domain list
if (!(profile.grantedDomAppearance(entry.url().getHost()))) {
reason = "url does not match domain filter";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is not listed in granted domains. " +
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// deny urls that exceed allowed number of occurrences
if (!(profile.grantedDomCount(entry.url().getHost()))) {
reason = "domain counter exceeded";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' appeared too often, a maximum of " + profile.domMaxPages() + " is allowed. "+
"Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// check if the url is double registered
final String dbocc = nextQueue.urlExists(entry.url().hash());
if (dbocc != null || wordIndex.existsURL(entry.url().hash())) {
final indexURLReference oldEntry = wordIndex.getURL(entry.url().hash(), null, 0);
final boolean recrawl = (oldEntry != null) && (profile.recrawlIfOlder() > oldEntry.loaddate().getTime());
// do double-check
if ((dbocc != null) && (!recrawl)) {
reason = "double " + dbocc + ")";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is double registered in '" + dbocc + "'. " + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
if ((oldEntry != null) && (!recrawl)) {
reason = "double " + "LURL)";
if (this.log.isFine()) this.log.logFine("URL '" + entry.url().toString() + "' is double registered in 'LURL'. " + "Stack processing time: " + (System.currentTimeMillis()-startTime) + "ms");
return reason;
}
// show potential re-crawl
if (recrawl && oldEntry != null) {
if (this.log.isFine()) this.log.logFine("RE-CRAWL of URL '" + entry.url().toString() + "': this url was crawled " +
((System.currentTimeMillis() - oldEntry.loaddate().getTime()) / 60000 / 60 / 24) + " days ago.");
}
}
// store information
final boolean local = entry.initiator().equals(wordIndex.seedDB.mySeed().hash);
final boolean proxy = (entry.initiator() == null || entry.initiator().equals("------------")) && profile.handle().equals(wordIndex.defaultProxyProfile.handle());
final boolean remote = profile.handle().equals(wordIndex.defaultRemoteProfile.handle());
final boolean global =
(profile.remoteIndexing()) /* granted */ &&
(entry.depth() == profile.depth()) /* leaf node */ &&
//(initiatorHash.equals(yacyCore.seedDB.mySeed.hash)) /* not proxy */ &&
(
(wordIndex.seedDB.mySeed().isSenior()) ||
(wordIndex.seedDB.mySeed().isPrincipal())
) /* qualified */;
if (!local && !global && !remote && !proxy) {
this.log.logSevere("URL '" + entry.url().toString() + "' cannot be crawled. initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
} else {
if (global) {
// it may be possible that global == true and local == true, so do not check an error case against it
if (proxy) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: global = true, proxy = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: global = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_LIMIT, entry);
} else if (local) {
if (proxy) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: local = true, proxy = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: local = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_CORE, entry);
} else if (proxy) {
if (remote) this.log.logWarning("URL '" + entry.url().toString() + "' has conflicting initiator properties: proxy = true, remote = true, initiator = " + entry.initiator() + ", profile.handle = " + profile.handle());
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_CORE, entry);
} else if (remote) {
nextQueue.noticeURL.push(NoticedURL.STACK_TYPE_REMOTE, entry);
}
}
return null;
}
|
diff --git a/src/thesaurus/gui/canvas/ViewGraph.java b/src/thesaurus/gui/canvas/ViewGraph.java
index 6e6e4c1..18810fb 100644
--- a/src/thesaurus/gui/canvas/ViewGraph.java
+++ b/src/thesaurus/gui/canvas/ViewGraph.java
@@ -1,304 +1,304 @@
package thesaurus.gui.canvas;
import java.util.LinkedList;
import javafx.event.EventHandler;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import thesaurus.gui.window.VisualisationRoot;
import thesaurus.parser.Vertex;
public class ViewGraph {
private static final int SYNONYM = 1;
private static final int ANTONYM = 0;
private int windowWidth;
private int windowHeight;
private Vertex vertex;
private VisualisationRoot vr;
private Canvas graph;
private GraphicsContext gc;
private int xOffset = 0;
private int yOffset = 0;
private int displaySynonyms;
private int displayAntonyms;
private int groupingEnabled;
public ViewGraph(int width, int height, Vertex vertex, VisualisationRoot vr, int displaySynonyms, int displayAntonyms, int groupingEnabled){
windowWidth = width;
windowHeight = height;
this.vertex = vertex;
this.vr = vr;
this.displaySynonyms = displaySynonyms;
this.displayAntonyms = displayAntonyms;
this.groupingEnabled = groupingEnabled;
//Move window to right to support dual view better
if(windowWidth<500){
this.xOffset=windowWidth/2;
}
//Centre origin node in canvas
xOffset = (int) (vertex.getPos().getX() - (windowWidth/2));
yOffset = (int) (vertex.getPos().getY() - (windowHeight/2));
start();
}
public ScrollPane returnGraph(){
ScrollPane sp = new ScrollPane();
sp.setPrefSize(windowWidth, windowHeight);
sp.setMaxSize(windowWidth, windowHeight);
sp.setHbarPolicy(ScrollBarPolicy.NEVER);
sp.setVbarPolicy(ScrollBarPolicy.NEVER);
sp.setStyle("-fx-background-color:transparent;");
sp.setContent(graph);
return sp;
}
private void drawMainNode(Vertex v){
int nodeWidth = v.getWord().length() * 12;
gc.setStroke(Color.BLACK);
gc.setFill(Color.rgb(176,220,247));
gc.setLineWidth(2);
gc.strokeOval((v.getPos().getX()-(nodeWidth/2)-xOffset),(v.getPos().getY()-13-yOffset), nodeWidth, 36);
gc.fillOval((v.getPos().getX()+1-(nodeWidth/2)-xOffset),(v.getPos().getY()-12-yOffset),nodeWidth-2,34);
gc.setFill(Color.BLACK);
gc.setFont(new Font(14));
gc.setTextAlign(TextAlignment.CENTER);
gc.fillText(v.getWord(), (v.getPos().getX()-xOffset), (v.getPos().getY()+10-yOffset));
}
private void drawSynNode(Vertex v){
int nodeWidth = v.getWord().length() * 8;
gc.setStroke(Color.BLACK);
gc.setFill(Color.rgb(191, 247, 176));
gc.setLineWidth(2);
gc.strokeOval((v.getPos().getX()-(nodeWidth/2)-xOffset),(v.getPos().getY()-10-yOffset), nodeWidth, 30);
gc.fillOval((v.getPos().getX()+1-(nodeWidth/2)-xOffset),(v.getPos().getY()-9-yOffset),nodeWidth-2,28);
gc.setFill(Color.BLACK);
gc.setFont(new Font(11));
gc.setTextAlign(TextAlignment.CENTER);
gc.fillText(v.getWord(), (v.getPos().getX()-xOffset), (v.getPos().getY()+9-yOffset));
}
private void drawAntNode(Vertex v){
int nodeWidth = v.getWord().length() * 8;
gc.setStroke(Color.BLACK);
gc.setFill(Color.rgb(242, 211, 211));
gc.setLineWidth(2);
gc.strokeOval((v.getPos().getX()-(nodeWidth/2)-xOffset),(v.getPos().getY()-10-yOffset), nodeWidth, 30);
gc.fillOval((v.getPos().getX()+1-(nodeWidth/2)-xOffset),(v.getPos().getY()-9-yOffset),nodeWidth-2,28);
gc.setFill(Color.BLACK);
gc.setFont(new Font(11));
gc.setTextAlign(TextAlignment.CENTER);
gc.fillText(v.getWord(), (v.getPos().getX()-xOffset), (v.getPos().getY()+9-yOffset));
}
private void drawConnector(double x1, double y1, double x2, double y2, int type){
if(type==1){
//Synonym
gc.setStroke(Color.GREEN);
} else {
//Antonym
gc.setStroke(Color.RED);
}
gc.setLineWidth(2);
gc.strokeLine(x1-xOffset, y1-yOffset, x2-xOffset, y2-yOffset);
}
private void drawGraph(){
//Draw connectors
//Synonyms
if(displaySynonyms==1){
double mainX = vertex.getPos().getX();
double mainY = vertex.getPos().getY();
for(Vertex v:vertex.getSynomyns()){
//Draw connector main node to synonym
double childX = v.getPos().getX();
double childY = v.getPos().getY();
drawConnector(childX,childY,mainX,mainY,SYNONYM);
//Draw connector synonym to its synonyms
if(v.getSynomyns().size()!=0){
for(Vertex c:v.getSynomyns()){
drawConnector(childX,childY,c.getPos().getX(),c.getPos().getY(),SYNONYM);
childX = c.getPos().getX();
childY = c.getPos().getY();
if(c.getSynomyns().size()!=0){
for(Vertex m:c.getSynomyns()){
drawConnector(childX,childY,m.getPos().getX(),m.getPos().getY(),SYNONYM);
}
}
}
}
}
}
if(displayAntonyms==1){
double mainX = vertex.getPos().getX();
double mainY = vertex.getPos().getY();
- for(Vertex v:vertex.getSynomyns()){
+ for(Vertex v:vertex.getAntonyms()){
//Draw connector main node to synonym
double childX = v.getPos().getX();
double childY = v.getPos().getY();
drawConnector(childX,childY,mainX,mainY,ANTONYM);
//Draw connector synonym to its synonyms
if(v.getAntonyms().size()!=0){
for(Vertex c:v.getAntonyms()){
drawConnector(childX,childY,c.getPos().getX(),c.getPos().getY(),ANTONYM);
childX = c.getPos().getX();
childY = c.getPos().getY();
- if(c.getSynomyns().size()!=0){
+ if(c.getAntonyms().size()!=0){
for(Vertex m:c.getAntonyms()){
drawConnector(childX,childY,m.getPos().getX(),m.getPos().getY(),ANTONYM);
}
}
}
}
}
}
//Draw synonym nodes
if(displaySynonyms==1){
for(Vertex v:vertex.getSynomyns()){
drawSynNode(v);
if(v.getSynomyns().size()!=0){
for(Vertex c:v.getSynomyns()){
drawSynNode(c);
if(c.getSynomyns().size()!=0)
for(Vertex m:c.getSynomyns()){
drawSynNode(m);
}
}
}
}
}
if(displayAntonyms==1){
for(Vertex v:vertex.getAntonyms()){
drawAntNode(v);
if(v.getAntonyms().size()!=0){
for(Vertex c:v.getAntonyms()){
drawAntNode(c);
if(c.getAntonyms().size()!=0)
for(Vertex m:c.getAntonyms()){
drawAntNode(m);
}
}
}
}
}
//Draw main node
drawMainNode(vertex);
}
private void resetGraph(){
gc.setFill(Color.rgb(242,242,242));
gc.fillRect(0, 0, windowWidth, windowHeight);
gc.setFill(Color.BLACK);
}
public void setScale(double scale){
graph.setScaleX(scale);
graph.setScaleY(scale);
}
private void start() {
graph = new Canvas(windowWidth,windowHeight);
gc = graph.getGraphicsContext2D();
graph.setWidth(windowWidth);
graph.setHeight(windowHeight);
resetGraph();
drawGraph();
/**
* Action Methods
*/
final LinkedList<Double> curX = new LinkedList<Double>();
final LinkedList<Double> curY = new LinkedList<Double>();
graph.addEventHandler(MouseEvent.MOUSE_DRAGGED,
new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
curX.add(e.getX());
curY.add(e.getY());
if(curX.size()>1){
xOffset += curX.get(0)-curX.get(1);
yOffset += curY.get(0)-curY.get(1);
resetGraph();
drawGraph();
curX.removeFirst();
curY.removeFirst();
}
}
});
graph.addEventHandler(MouseEvent.MOUSE_RELEASED,
new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
curX.clear();
curY.clear();
}
});
graph.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
if(e.getClickCount()==2){
//On double click, search for clicked node
double clickX = e.getX() + xOffset;
double clickY = e.getY() + yOffset;
for(Vertex v:vertex.getSynomyns()){
double nodeWidth = v.getWord().length() * 5;
if((clickX > v.getPos().getX()-nodeWidth) && clickX < (v.getPos().getX() + nodeWidth)){
if((clickY > v.getPos().getY()-13) && clickY < (v.getPos().getY()+13)){
//found.
System.out.println("//" + vertex.getSynomyns());
vr.doClickSearchGraph(v.getWord());
break;
}
}
//child nodes to go here.
for(Vertex c:v.getSynomyns()){
double nodewidth = c.getWord().length() * 5;
if((clickX > c.getPos().getX()-nodeWidth) && clickX < (c.getPos().getX() + nodeWidth)){
if((clickY > c.getPos().getY()-13) && clickY < (c.getPos().getY()+13)){
//found.
System.out.println(c.getPos());
vr.doClickSearchGraph(c.getWord());
}
}
}
}
}
}
});
}
}
| false | true | private void drawGraph(){
//Draw connectors
//Synonyms
if(displaySynonyms==1){
double mainX = vertex.getPos().getX();
double mainY = vertex.getPos().getY();
for(Vertex v:vertex.getSynomyns()){
//Draw connector main node to synonym
double childX = v.getPos().getX();
double childY = v.getPos().getY();
drawConnector(childX,childY,mainX,mainY,SYNONYM);
//Draw connector synonym to its synonyms
if(v.getSynomyns().size()!=0){
for(Vertex c:v.getSynomyns()){
drawConnector(childX,childY,c.getPos().getX(),c.getPos().getY(),SYNONYM);
childX = c.getPos().getX();
childY = c.getPos().getY();
if(c.getSynomyns().size()!=0){
for(Vertex m:c.getSynomyns()){
drawConnector(childX,childY,m.getPos().getX(),m.getPos().getY(),SYNONYM);
}
}
}
}
}
}
if(displayAntonyms==1){
double mainX = vertex.getPos().getX();
double mainY = vertex.getPos().getY();
for(Vertex v:vertex.getSynomyns()){
//Draw connector main node to synonym
double childX = v.getPos().getX();
double childY = v.getPos().getY();
drawConnector(childX,childY,mainX,mainY,ANTONYM);
//Draw connector synonym to its synonyms
if(v.getAntonyms().size()!=0){
for(Vertex c:v.getAntonyms()){
drawConnector(childX,childY,c.getPos().getX(),c.getPos().getY(),ANTONYM);
childX = c.getPos().getX();
childY = c.getPos().getY();
if(c.getSynomyns().size()!=0){
for(Vertex m:c.getAntonyms()){
drawConnector(childX,childY,m.getPos().getX(),m.getPos().getY(),ANTONYM);
}
}
}
}
}
}
//Draw synonym nodes
if(displaySynonyms==1){
for(Vertex v:vertex.getSynomyns()){
drawSynNode(v);
if(v.getSynomyns().size()!=0){
for(Vertex c:v.getSynomyns()){
drawSynNode(c);
if(c.getSynomyns().size()!=0)
for(Vertex m:c.getSynomyns()){
drawSynNode(m);
}
}
}
}
}
if(displayAntonyms==1){
for(Vertex v:vertex.getAntonyms()){
drawAntNode(v);
if(v.getAntonyms().size()!=0){
for(Vertex c:v.getAntonyms()){
drawAntNode(c);
if(c.getAntonyms().size()!=0)
for(Vertex m:c.getAntonyms()){
drawAntNode(m);
}
}
}
}
}
//Draw main node
drawMainNode(vertex);
}
| private void drawGraph(){
//Draw connectors
//Synonyms
if(displaySynonyms==1){
double mainX = vertex.getPos().getX();
double mainY = vertex.getPos().getY();
for(Vertex v:vertex.getSynomyns()){
//Draw connector main node to synonym
double childX = v.getPos().getX();
double childY = v.getPos().getY();
drawConnector(childX,childY,mainX,mainY,SYNONYM);
//Draw connector synonym to its synonyms
if(v.getSynomyns().size()!=0){
for(Vertex c:v.getSynomyns()){
drawConnector(childX,childY,c.getPos().getX(),c.getPos().getY(),SYNONYM);
childX = c.getPos().getX();
childY = c.getPos().getY();
if(c.getSynomyns().size()!=0){
for(Vertex m:c.getSynomyns()){
drawConnector(childX,childY,m.getPos().getX(),m.getPos().getY(),SYNONYM);
}
}
}
}
}
}
if(displayAntonyms==1){
double mainX = vertex.getPos().getX();
double mainY = vertex.getPos().getY();
for(Vertex v:vertex.getAntonyms()){
//Draw connector main node to synonym
double childX = v.getPos().getX();
double childY = v.getPos().getY();
drawConnector(childX,childY,mainX,mainY,ANTONYM);
//Draw connector synonym to its synonyms
if(v.getAntonyms().size()!=0){
for(Vertex c:v.getAntonyms()){
drawConnector(childX,childY,c.getPos().getX(),c.getPos().getY(),ANTONYM);
childX = c.getPos().getX();
childY = c.getPos().getY();
if(c.getAntonyms().size()!=0){
for(Vertex m:c.getAntonyms()){
drawConnector(childX,childY,m.getPos().getX(),m.getPos().getY(),ANTONYM);
}
}
}
}
}
}
//Draw synonym nodes
if(displaySynonyms==1){
for(Vertex v:vertex.getSynomyns()){
drawSynNode(v);
if(v.getSynomyns().size()!=0){
for(Vertex c:v.getSynomyns()){
drawSynNode(c);
if(c.getSynomyns().size()!=0)
for(Vertex m:c.getSynomyns()){
drawSynNode(m);
}
}
}
}
}
if(displayAntonyms==1){
for(Vertex v:vertex.getAntonyms()){
drawAntNode(v);
if(v.getAntonyms().size()!=0){
for(Vertex c:v.getAntonyms()){
drawAntNode(c);
if(c.getAntonyms().size()!=0)
for(Vertex m:c.getAntonyms()){
drawAntNode(m);
}
}
}
}
}
//Draw main node
drawMainNode(vertex);
}
|
diff --git a/app/models/AirlinePlan.java b/app/models/AirlinePlan.java
index 6236e0e..790e809 100644
--- a/app/models/AirlinePlan.java
+++ b/app/models/AirlinePlan.java
@@ -1,130 +1,130 @@
package models;
import javax.persistence.*;
import play.data.validation.Max;
import play.data.validation.Required;
import play.db.jpa.Model;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: reyoung
* Date: 3/17/13
* Time: 2:27 PM
* To change this template use File | Settings | File Templates.
*/
@Entity
public class AirlinePlan extends Model {
@Column(name = "Number",nullable = false)
@Required
@Max(value = 255)
public String Number;
@Column(name = "LeaveTime",nullable = false)
@Required
public Date LeaveTime;
@Required
@Column(name = "FlyTime",nullable = false)
public int FlyTime;
@Column(name = "Repeat",nullable = false)
@Required
@Max(value = 255)
public String Repeat;
@OneToOne
@JoinColumn(name = "Company",nullable = false)
public AirCompany Company;
@Required
@OneToOne()
@JoinColumn(name = "LeavePlace", nullable = false)
public Airport LeavePlace;
@Required
@OneToOne()
@JoinColumn(name = "ArrivePlace",nullable = false)
public Airport ArrivePlace;
@OneToMany()
public List<Airport> StopoverPlaces;
public String switchNumber(String cha){
if(cha.equals("1")){
cha="一";
}else if(cha.equals("2")){
cha="二";
}else if(cha.equals("2")){
cha="二";
}else if(cha.equals("3")){
cha="三";
}else if(cha.equals("4")){
cha="四";
}else if(cha.equals("5")){
cha="五";
}else if(cha.equals("6")){
cha="六";
}else if(cha.equals("7")){
cha="日";
}
return cha;
}
public String getReadableLeaveTime() {
String strLeaveTime=null;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
if(this.Repeat.subSequence(0, 1).equals("N")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
strLeaveTime=sdf.format(this.LeaveTime)+"起飞";
}else if(this.Repeat.subSequence(0, 1).equals("W")){
- if(this.Repeat.subSequence(0, 1).equals("W1234567")){
+ if(this.Repeat.equals("W1234567")){
strLeaveTime="每天";
}else{
strLeaveTime="每周";
for(int i=1;i<Repeat.length();i++){
String cha=Repeat.substring(i,i+1);
strLeaveTime+=switchNumber(cha)+",";
}
strLeaveTime=strLeaveTime.subSequence(0, strLeaveTime.length()-1)+df.format(this.LeaveTime)+"起飞";
}
}else if(this.Repeat.subSequence(0, 1).equals("M")){
strLeaveTime="每月"+Repeat.subSequence(1, Repeat.length())+"号"+df.format(this.LeaveTime)+"起飞";
}
return strLeaveTime;
}
public String getReadableFlyTime(){
int day=FlyTime/1440;
int hour=(FlyTime/60)%24;
int minute=FlyTime%60;
String strFlyTime="飞行时间为:"+day+"天"+hour+"小时"+minute+"分钟";
return strFlyTime;
}
public String getReadableStopovers(){
if (StopoverPlaces.size()==0){
return "无" ;
} else {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (Airport ap : StopoverPlaces){
sb.append(ap.toString());
sb.append(",");
}
sb.setCharAt(sb.length()-1,']');
return sb.toString();
}
}
public String getEditLeaveTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(this.LeaveTime);
}
}
| true | true | public String getReadableLeaveTime() {
String strLeaveTime=null;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
if(this.Repeat.subSequence(0, 1).equals("N")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
strLeaveTime=sdf.format(this.LeaveTime)+"起飞";
}else if(this.Repeat.subSequence(0, 1).equals("W")){
if(this.Repeat.subSequence(0, 1).equals("W1234567")){
strLeaveTime="每天";
}else{
strLeaveTime="每周";
for(int i=1;i<Repeat.length();i++){
String cha=Repeat.substring(i,i+1);
strLeaveTime+=switchNumber(cha)+",";
}
strLeaveTime=strLeaveTime.subSequence(0, strLeaveTime.length()-1)+df.format(this.LeaveTime)+"起飞";
}
}else if(this.Repeat.subSequence(0, 1).equals("M")){
strLeaveTime="每月"+Repeat.subSequence(1, Repeat.length())+"号"+df.format(this.LeaveTime)+"起飞";
}
return strLeaveTime;
}
| public String getReadableLeaveTime() {
String strLeaveTime=null;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
if(this.Repeat.subSequence(0, 1).equals("N")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
strLeaveTime=sdf.format(this.LeaveTime)+"起飞";
}else if(this.Repeat.subSequence(0, 1).equals("W")){
if(this.Repeat.equals("W1234567")){
strLeaveTime="每天";
}else{
strLeaveTime="每周";
for(int i=1;i<Repeat.length();i++){
String cha=Repeat.substring(i,i+1);
strLeaveTime+=switchNumber(cha)+",";
}
strLeaveTime=strLeaveTime.subSequence(0, strLeaveTime.length()-1)+df.format(this.LeaveTime)+"起飞";
}
}else if(this.Repeat.subSequence(0, 1).equals("M")){
strLeaveTime="每月"+Repeat.subSequence(1, Repeat.length())+"号"+df.format(this.LeaveTime)+"起飞";
}
return strLeaveTime;
}
|
diff --git a/src/com/jkush321/autowalls/ColorCycler.java b/src/com/jkush321/autowalls/ColorCycler.java
index 0277ec8..c374272 100644
--- a/src/com/jkush321/autowalls/ColorCycler.java
+++ b/src/com/jkush321/autowalls/ColorCycler.java
@@ -1,135 +1,135 @@
package com.jkush321.autowalls;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.kitteh.tag.TagAPI;
public class ColorCycler {
public static int MAX_COLOR_TIME;
public static Map<Player, ChatColor> fakeColors = new HashMap<>();
public static Map<Player, Integer> colorTime = new HashMap<>();
public static ChatColor getFakeColor(Player p)
{
if (fakeColors.containsKey(p)) return fakeColors.get(p);
return null;
}
public static void setFakeColor(Player p, ChatColor c)
{
if (fakeColors.containsKey(p)) fakeColors.remove(p);
fakeColors.put(p, c);
TagAPI.refreshPlayer(p);
}
public static void cycle(Player p)
{
ChatColor nextColor;
if (getFakeColor(p) == null)
{
if (AutoWalls.redTeam.contains(p))
{
nextColor = ChatColor.DARK_AQUA;
}
else if (AutoWalls.blueTeam.contains(p))
{
nextColor = ChatColor.DARK_GREEN;
}
else if (AutoWalls.greenTeam.contains(p))
{
nextColor = ChatColor.GOLD;
}
else
{
nextColor = ChatColor.DARK_RED;
}
}
else
{
if (getFakeColor(p)==ChatColor.DARK_RED)
{
nextColor = ChatColor.DARK_AQUA;
}
else if (getFakeColor(p)==ChatColor.DARK_AQUA)
{
nextColor = ChatColor.DARK_GREEN;
}
else if (getFakeColor(p)==ChatColor.DARK_GREEN)
{
nextColor = ChatColor.GOLD;
}
else
{
nextColor = ChatColor.DARK_RED;
}
}
if ((AutoWalls.redTeam.contains(p) && nextColor == ChatColor.DARK_RED) ||
(AutoWalls.blueTeam.contains(p) && nextColor == ChatColor.DARK_AQUA) ||
(AutoWalls.greenTeam.contains(p) && nextColor == ChatColor.DARK_GREEN) ||
(AutoWalls.orangeTeam.contains(p) && nextColor == ChatColor.GOLD))
{
setFakeColor(p, null);
p.sendMessage(ChatColor.GREEN + "You now have your original nameplate color");
}
else
{
if (nextColor == ChatColor.DARK_RED)
{
- p.sendMessage(ChatColor.GREEN + "You nameplate now appears as red");
+ p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as red");
}
else if (nextColor == ChatColor.DARK_AQUA)
{
- p.sendMessage(ChatColor.GREEN + "You nameplate now appears as blue");
+ p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as blue");
}
else if (nextColor == ChatColor.DARK_GREEN)
{
- p.sendMessage(ChatColor.GREEN + "You nameplate now appears as green");
+ p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as green");
}
else
{
- p.sendMessage(ChatColor.GREEN + "You nameplate now appears as orange");
+ p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as orange");
}
setFakeColor(p, nextColor);
}
}
public static void tick()
{
if (fakeColors.size() > 0)
{
Set<Player> copiedSet = new HashSet<Player>();
copiedSet.addAll(fakeColors.keySet());
for (Player p : copiedSet)
{
if (fakeColors.get(p) != null)
{
if (colorTime.containsKey(p))
{
int time;
if ((time = colorTime.get(p)) > 0)
{
time = time - 1;
colorTime.remove(p);
colorTime.put(p, time);
}
else
{
fakeColors.remove(p);
p.sendMessage(ChatColor.RED + "Your ability to change color has worn off!");
TagAPI.refreshPlayer(p);
}
}
else
{
colorTime.put(p, MAX_COLOR_TIME);
}
}
}
}
}
}
| false | true | public static void cycle(Player p)
{
ChatColor nextColor;
if (getFakeColor(p) == null)
{
if (AutoWalls.redTeam.contains(p))
{
nextColor = ChatColor.DARK_AQUA;
}
else if (AutoWalls.blueTeam.contains(p))
{
nextColor = ChatColor.DARK_GREEN;
}
else if (AutoWalls.greenTeam.contains(p))
{
nextColor = ChatColor.GOLD;
}
else
{
nextColor = ChatColor.DARK_RED;
}
}
else
{
if (getFakeColor(p)==ChatColor.DARK_RED)
{
nextColor = ChatColor.DARK_AQUA;
}
else if (getFakeColor(p)==ChatColor.DARK_AQUA)
{
nextColor = ChatColor.DARK_GREEN;
}
else if (getFakeColor(p)==ChatColor.DARK_GREEN)
{
nextColor = ChatColor.GOLD;
}
else
{
nextColor = ChatColor.DARK_RED;
}
}
if ((AutoWalls.redTeam.contains(p) && nextColor == ChatColor.DARK_RED) ||
(AutoWalls.blueTeam.contains(p) && nextColor == ChatColor.DARK_AQUA) ||
(AutoWalls.greenTeam.contains(p) && nextColor == ChatColor.DARK_GREEN) ||
(AutoWalls.orangeTeam.contains(p) && nextColor == ChatColor.GOLD))
{
setFakeColor(p, null);
p.sendMessage(ChatColor.GREEN + "You now have your original nameplate color");
}
else
{
if (nextColor == ChatColor.DARK_RED)
{
p.sendMessage(ChatColor.GREEN + "You nameplate now appears as red");
}
else if (nextColor == ChatColor.DARK_AQUA)
{
p.sendMessage(ChatColor.GREEN + "You nameplate now appears as blue");
}
else if (nextColor == ChatColor.DARK_GREEN)
{
p.sendMessage(ChatColor.GREEN + "You nameplate now appears as green");
}
else
{
p.sendMessage(ChatColor.GREEN + "You nameplate now appears as orange");
}
setFakeColor(p, nextColor);
}
}
| public static void cycle(Player p)
{
ChatColor nextColor;
if (getFakeColor(p) == null)
{
if (AutoWalls.redTeam.contains(p))
{
nextColor = ChatColor.DARK_AQUA;
}
else if (AutoWalls.blueTeam.contains(p))
{
nextColor = ChatColor.DARK_GREEN;
}
else if (AutoWalls.greenTeam.contains(p))
{
nextColor = ChatColor.GOLD;
}
else
{
nextColor = ChatColor.DARK_RED;
}
}
else
{
if (getFakeColor(p)==ChatColor.DARK_RED)
{
nextColor = ChatColor.DARK_AQUA;
}
else if (getFakeColor(p)==ChatColor.DARK_AQUA)
{
nextColor = ChatColor.DARK_GREEN;
}
else if (getFakeColor(p)==ChatColor.DARK_GREEN)
{
nextColor = ChatColor.GOLD;
}
else
{
nextColor = ChatColor.DARK_RED;
}
}
if ((AutoWalls.redTeam.contains(p) && nextColor == ChatColor.DARK_RED) ||
(AutoWalls.blueTeam.contains(p) && nextColor == ChatColor.DARK_AQUA) ||
(AutoWalls.greenTeam.contains(p) && nextColor == ChatColor.DARK_GREEN) ||
(AutoWalls.orangeTeam.contains(p) && nextColor == ChatColor.GOLD))
{
setFakeColor(p, null);
p.sendMessage(ChatColor.GREEN + "You now have your original nameplate color");
}
else
{
if (nextColor == ChatColor.DARK_RED)
{
p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as red");
}
else if (nextColor == ChatColor.DARK_AQUA)
{
p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as blue");
}
else if (nextColor == ChatColor.DARK_GREEN)
{
p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as green");
}
else
{
p.sendMessage(ChatColor.GREEN + "Your nameplate now appears as orange");
}
setFakeColor(p, nextColor);
}
}
|
diff --git a/org.cfeclipse.cfml/src/org/cfeclipse/cfml/parser/docitems/CfmlTagItem.java b/org.cfeclipse.cfml/src/org/cfeclipse/cfml/parser/docitems/CfmlTagItem.java
index 87b17b99..f1375a9e 100644
--- a/org.cfeclipse.cfml/src/org/cfeclipse/cfml/parser/docitems/CfmlTagItem.java
+++ b/org.cfeclipse.cfml/src/org/cfeclipse/cfml/parser/docitems/CfmlTagItem.java
@@ -1,148 +1,150 @@
/*
* Created on Mar 18, 2004
*
* The MIT License
* Copyright (c) 2004 Oliver Tupman
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.cfeclipse.cfml.parser.docitems;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Iterator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.cfeclipse.cfml.dictionary.Parameter;
import org.cfeclipse.cfml.dictionary.Tag;
import org.cfeclipse.cfml.parser.ParseError;
import org.cfeclipse.cfml.parser.exception.DuplicateAttributeException;
import org.cfeclipse.cfml.parser.exception.InvalidAttributeException;
/**
* @author Oliver Tupman
*
*/
public class CfmlTagItem extends TagItem {
/**
*
* @see org.cfeclipse.cfml.parser.docitems.DocItem#IsSane()
*/
public boolean IsSane() {
//staticLookups
HashMap suggestedAttributes = new HashMap();
Set suggAttribSet = itemAttributes.keySet();
String attributesFound = "";
for (Iterator iter = suggAttribSet.iterator(); iter.hasNext();) {
String attributeName = (String) iter.next();
AttributeItem attributeValue = (AttributeItem)itemAttributes.get(attributeName);
suggestedAttributes.put(attributeName, attributeValue.getValue());
}
Set attributes = syntax.getElementAttributes(this.itemName);
if(attributes == null) {
return super.IsSane();
}
Object[] params = attributes.toArray();
if(itemAttributes.size() > 0) {
attributesFound = " (Found: "+ itemAttributes.keySet().toString() + ")";
}
for(int i = 0; i < params.length; i++) {
Parameter currParam = (Parameter)params[i];
- if(currParam.isRequired() && !(itemAttributes.containsKey(currParam.getName().toLowerCase()) || itemAttributes.containsKey(currParam.getName().toUpperCase()))) {
+ if (currParam.isRequired()
+ && !(itemAttributes.containsKey(currParam.getName().toLowerCase()) || itemAttributes.containsKey(currParam.getName()
+ .toUpperCase())) && !itemAttributes.containsKey("attributecollection")) {
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"The attribute \'" + currParam.getName() + "\' is compulsory for the <" + this.itemName + "> tag." + attributesFound));
}
if(!currParam.getTriggers().isEmpty() && currParam.isRequired(suggestedAttributes) == 3 && !itemAttributes.containsKey(currParam.getName())){
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"The attribute \'" + currParam.getName() + "\' is required for the <" + this.itemName + "> tag." + attributesFound));
// the logic here is funky for optional tags with triggers TODO: refactor
// } else if (!currParam.getTriggers().isEmpty() && currParam.isTriggered(suggestedAttributes) == 0 && itemAttributes.containsKey(currParam.getName())) {
// this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
// "The attribute \'" + currParam.getName() + "\' is not valid for the <" + this.itemName + "> tag." + attributesFound));
}
}
return super.IsSane();
}
/**
* Determines whether the child is valid or not.
* <b>NB:</b> At present the default is <b>true</b>. Classes that derive from this class may
* choose to change this behavour.
*
* @see org.cfeclipse.cfml.parser.docitems.DocItem#validChildAddition(org.cfeclipse.cfml.parser.DocItem)
*/
public boolean validChildAddition(DocItem parentItem) {
return true;
}
/**
* Adds a string-based name/value attribute pair to the tag
*
* @param newAttr The new attribute to add to this CFML tag item
* @throws DuplicateAttributeException The attribute already exists in the attr list
* @throws InvalidAttributeException The attribute does not belong to this tag.
*/
public boolean addAttribute(AttributeItem newAttr)
{
boolean addOkay = true;
Tag tag = syntax.getTag(itemName);
if (tag == null || !tag.allowsAnyAttribute()) {
Set attributes = syntax.getFilteredAttributes(this.itemName.toLowerCase(), newAttr.getName());
if(attributes.size() == 0) {
/*
* if we don't know the tag why tell the user about invalid attributes? :denny
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"Attribute \'" + newAttr.getName() + "\' is not valid."));
*/
addOkay = false; // While it's incorrect we still wish to add it to the item
}
}
addOkay = super.addAttribute(newAttr) && addOkay;
return addOkay;
}
/**
* @param line
* @param startDocPos
* @param endDocPos
* @param name
*/
public CfmlTagItem(int line, int startDocPos, int endDocPos, String name) {
super(line, startDocPos, endDocPos, name);
}
}
| true | true | public boolean IsSane() {
//staticLookups
HashMap suggestedAttributes = new HashMap();
Set suggAttribSet = itemAttributes.keySet();
String attributesFound = "";
for (Iterator iter = suggAttribSet.iterator(); iter.hasNext();) {
String attributeName = (String) iter.next();
AttributeItem attributeValue = (AttributeItem)itemAttributes.get(attributeName);
suggestedAttributes.put(attributeName, attributeValue.getValue());
}
Set attributes = syntax.getElementAttributes(this.itemName);
if(attributes == null) {
return super.IsSane();
}
Object[] params = attributes.toArray();
if(itemAttributes.size() > 0) {
attributesFound = " (Found: "+ itemAttributes.keySet().toString() + ")";
}
for(int i = 0; i < params.length; i++) {
Parameter currParam = (Parameter)params[i];
if(currParam.isRequired() && !(itemAttributes.containsKey(currParam.getName().toLowerCase()) || itemAttributes.containsKey(currParam.getName().toUpperCase()))) {
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"The attribute \'" + currParam.getName() + "\' is compulsory for the <" + this.itemName + "> tag." + attributesFound));
}
if(!currParam.getTriggers().isEmpty() && currParam.isRequired(suggestedAttributes) == 3 && !itemAttributes.containsKey(currParam.getName())){
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"The attribute \'" + currParam.getName() + "\' is required for the <" + this.itemName + "> tag." + attributesFound));
// the logic here is funky for optional tags with triggers TODO: refactor
// } else if (!currParam.getTriggers().isEmpty() && currParam.isTriggered(suggestedAttributes) == 0 && itemAttributes.containsKey(currParam.getName())) {
// this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
// "The attribute \'" + currParam.getName() + "\' is not valid for the <" + this.itemName + "> tag." + attributesFound));
}
}
return super.IsSane();
}
| public boolean IsSane() {
//staticLookups
HashMap suggestedAttributes = new HashMap();
Set suggAttribSet = itemAttributes.keySet();
String attributesFound = "";
for (Iterator iter = suggAttribSet.iterator(); iter.hasNext();) {
String attributeName = (String) iter.next();
AttributeItem attributeValue = (AttributeItem)itemAttributes.get(attributeName);
suggestedAttributes.put(attributeName, attributeValue.getValue());
}
Set attributes = syntax.getElementAttributes(this.itemName);
if(attributes == null) {
return super.IsSane();
}
Object[] params = attributes.toArray();
if(itemAttributes.size() > 0) {
attributesFound = " (Found: "+ itemAttributes.keySet().toString() + ")";
}
for(int i = 0; i < params.length; i++) {
Parameter currParam = (Parameter)params[i];
if (currParam.isRequired()
&& !(itemAttributes.containsKey(currParam.getName().toLowerCase()) || itemAttributes.containsKey(currParam.getName()
.toUpperCase())) && !itemAttributes.containsKey("attributecollection")) {
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"The attribute \'" + currParam.getName() + "\' is compulsory for the <" + this.itemName + "> tag." + attributesFound));
}
if(!currParam.getTriggers().isEmpty() && currParam.isRequired(suggestedAttributes) == 3 && !itemAttributes.containsKey(currParam.getName())){
this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
"The attribute \'" + currParam.getName() + "\' is required for the <" + this.itemName + "> tag." + attributesFound));
// the logic here is funky for optional tags with triggers TODO: refactor
// } else if (!currParam.getTriggers().isEmpty() && currParam.isTriggered(suggestedAttributes) == 0 && itemAttributes.containsKey(currParam.getName())) {
// this.parseMessages.addMessage(new ParseError(lineNumber, startPosition, endPosition, itemData,
// "The attribute \'" + currParam.getName() + "\' is not valid for the <" + this.itemName + "> tag." + attributesFound));
}
}
return super.IsSane();
}
|
diff --git a/src/org/bouncycastle/crypto/tls/NamedCurve.java b/src/org/bouncycastle/crypto/tls/NamedCurve.java
index fe18cee4..5f407a09 100644
--- a/src/org/bouncycastle/crypto/tls/NamedCurve.java
+++ b/src/org/bouncycastle/crypto/tls/NamedCurve.java
@@ -1,93 +1,93 @@
package org.bouncycastle.crypto.tls;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
/**
* RFC 4492 5.1.1
*
* The named curves defined here are those specified in SEC 2 [13]. Note that many of
* these curves are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00
* through 0xFEFF are reserved for private use. Values 0xFF01 and 0xFF02 indicate that the
* client supports arbitrary prime and characteristic-2 curves, respectively (the curve
* parameters must be encoded explicitly in ECParameters).
*/
public class NamedCurve
{
public static final int sect163k1 = 1;
public static final int sect163r1 = 2;
public static final int sect163r2 = 3;
public static final int sect193r1 = 4;
public static final int sect193r2 = 5;
public static final int sect233k1 = 6;
public static final int sect233r1 = 7;
public static final int sect239k1 = 8;
public static final int sect283k1 = 9;
public static final int sect283r1 = 10;
public static final int sect409k1 = 11;
public static final int sect409r1 = 12;
public static final int sect571k1 = 13;
public static final int sect571r1 = 14;
public static final int secp160k1 = 15;
public static final int secp160r1 = 16;
public static final int secp160r2 = 17;
public static final int secp192k1 = 18;
public static final int secp192r1 = 19;
public static final int secp224k1 = 20;
public static final int secp224r1 = 21;
public static final int secp256k1 = 22;
public static final int secp256r1 = 23;
public static final int secp384r1 = 24;
public static final int secp521r1 = 25;
/*
* reserved (0xFE00..0xFEFF)
*/
public static final int arbitrary_explicit_prime_curves = 0xFF01;
public static final int arbitrary_explicit_char2_curves = 0xFF02;
private static final String[] curveNames = new String[] {
"sect163k1",
"sect163r1",
"sect163r2",
"sect193r1",
"sect193r2",
"sect233k1",
"sect233r1",
"sect239k1",
"sect283k1",
"sect283r1",
"sect409k1",
"sect409r1",
"sect571k1",
"sect571r1",
"secp160k1",
"secp160r1",
"secp160r2",
"secp192k1",
"secp192r1",
"secp224k1",
"secp224r1",
"secp256k1",
"secp256r1",
"secp384r1",
"secp521r1", };
static ECDomainParameters getECParameters(int namedCurve)
{
int index = namedCurve - 1;
if (index < 0 || index >= curveNames.length)
{
return null;
}
// Lazily created the first time a particular curve is accessed
- X9ECParameters ecP = SECNamedCurves.getByName(curveNames[namedCurve]);
+ X9ECParameters ecP = SECNamedCurves.getByName(curveNames[index]);
// It's a bit inefficient to do this conversion every time
return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(),
ecP.getSeed());
}
}
| true | true | static ECDomainParameters getECParameters(int namedCurve)
{
int index = namedCurve - 1;
if (index < 0 || index >= curveNames.length)
{
return null;
}
// Lazily created the first time a particular curve is accessed
X9ECParameters ecP = SECNamedCurves.getByName(curveNames[namedCurve]);
// It's a bit inefficient to do this conversion every time
return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(),
ecP.getSeed());
}
| static ECDomainParameters getECParameters(int namedCurve)
{
int index = namedCurve - 1;
if (index < 0 || index >= curveNames.length)
{
return null;
}
// Lazily created the first time a particular curve is accessed
X9ECParameters ecP = SECNamedCurves.getByName(curveNames[index]);
// It's a bit inefficient to do this conversion every time
return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(),
ecP.getSeed());
}
|
diff --git a/ParqDaoLayer/src/main/java/com/parq/server/dao/UserDao.java b/ParqDaoLayer/src/main/java/com/parq/server/dao/UserDao.java
index 337b22b..d1278b5 100644
--- a/ParqDaoLayer/src/main/java/com/parq/server/dao/UserDao.java
+++ b/ParqDaoLayer/src/main/java/com/parq/server/dao/UserDao.java
@@ -1,404 +1,404 @@
package com.parq.server.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import com.parq.server.dao.exception.DuplicateEmailException;
import com.parq.server.dao.model.object.User;
/**
* Dao class responsible for accessing and updating the User Table
*
*
* @author GZ
*
*/
public class UserDao extends AbstractParqDaoParent {
/**
* Name of the local cache use by this dao
*/
private static final String cacheName = "UserCache";
private static Cache myCache;
private static final String sqlGetUserStatement = "SELECT user_id, password, email, phone_number FROM user ";
private static final String isNotDeleted = " AND is_deleted IS NOT TRUE";
private static final String sqlGetUserById = sqlGetUserStatement + "WHERE user_id = ? " + isNotDeleted;
private static final String sqlGetUserByEmail = sqlGetUserStatement + "WHERE email = ? " + isNotDeleted;
private static final String sqlDeleteUserById = "UPDATE user SET is_deleted = TRUE, email = ? WHERE user_id = ?";
private static final String sqlUpdateUser = "UPDATE user SET password = ?, email = ?, phone_number = ? "
+ " WHERE user_id = ?";
private static final String sqlCreateUser = "INSERT INTO user (password, email, phone_number, django_user_id) "
+ " VALUES (?, ?, ?, ?)";
static final String sqlDjangoCreateAuthUser = "INSERT INTO auth_user (username, email, password) " +
" VALUES (?, ?, ?)";
static final String sqlDjangoUpdateAuthUser = "UPDATE auth_user SET username =?, email = ?, password = ?";
static final String sqlDjangoDeleteAuthUser = "UPDATE auth_user SET is_active = false, username = ?, email = ? " +
" WHERE id = (SELECT django_user_id FROM user WHERE user_id = ?)";
static final String sqlGetNewDjangoAuthUserId = "SELECT MAX(id) AS id FROM auth_user WHERE email = ? ";
private static final String emailCache = "getUserByEmail:";
private static final String idCache = "getUserById:";
public UserDao() {
super();
if (myCache == null) {
// create the cache.
myCache = setupCache(cacheName);
}
}
/**
* Create the User model object from the DB query result set.
*
* @param rs
* @return
* @throws SQLException
*/
private User createUserObject(ResultSet rs) throws SQLException {
if (rs == null || !rs.isBeforeFirst()) {
return null;
}
User user = new User();
rs.first();
user.setUserID(rs.getLong("user_id"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setPhoneNumber(rs.getString("phone_number"));
return user;
}
/**
* Retrieve the <code>User</code> object based on the userId, if no
* <code>User</code> exist based on the userId or if the <code>User</code>
* with this id has been deleted, then <code>NULL</code> is returned.
*
* @param id
* The id of the user to retrive, must be > 0
* @return <code>User</code> corresponding to the id, or <code>NULL</code>
* is no such user exist or the user has been deleted
* <code>NULL</code>
*/
public User getUserById(long id) {
// the cache key for this method call;
String cacheKey = idCache + id;
User user = null;
Element cacheEntry = myCache.get(cacheKey);
if (cacheEntry != null) {
user = (User) cacheEntry.getValue();
return user;
}
// query the DB for the user object
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sqlGetUserById);
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
user = createUserObject(rs);
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
// put result into cache
myCache.put(new Element(cacheKey, user));
return user;
}
/**
* Retrieve the <code>User</code> based on his/her email address. If the no
* <code>User</code> exist for this email address or the user has been
* delete. <code>NULL</code> is returned.
*
* @param emailAddress
* the email address to search the user based on, must not be
* <code>NULL</code>
* @return <code>User</code> corresponding to the email address, or
* <code>NULL</code> is no such user exist or the user has been
* deleted <code>NULL</code>
*/
public User getUserByEmail(String emailAddress) {
// the cache key for this method call;
String cacheKey = emailCache + emailAddress;
User user = null;
Element cacheEntry = myCache.get(cacheKey);
if (cacheEntry != null) {
user = (User) cacheEntry.getValue();
return user;
}
// query the DB for the user object
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sqlGetUserByEmail);
pstmt.setString(1, emailAddress);
ResultSet rs = pstmt.executeQuery();
user = createUserObject(rs);
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
// put result into cache
myCache.put(new Element(cacheKey, user));
return user;
}
/**
* Delete the user with the id provided.
*
* @param id
* the user id, must be > 0
* @return <code>True</code> if delete is successful, <code>false</code>
* other wise.
*/
public synchronized boolean deleteUserById(long id) {
if (id <= 0) {
throw new IllegalStateException("Invalid user delete request");
}
User delUser = getUserById(id);
// clear out the cache entry for deleted user
revokeUserCacheById(id);
PreparedStatement pstmt = null;
Connection con = null;
boolean deleteSuccessful = false;
if (delUser != null) {
try {
con = getConnection();
pstmt = con.prepareStatement(sqlDeleteUserById);
String deletedEmail = delUser.getEmail() + " deleted_On:" + System.currentTimeMillis();
pstmt.setString(1, deletedEmail);
pstmt.setLong(2, id);
deleteSuccessful = pstmt.executeUpdate() > 0;
if (deleteSuccessful) {
deleteSuccessful &= deleteDjangoUser(id, deletedEmail, con);
}
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
}
return deleteSuccessful;
}
/**
* Update the user information. Note all the field on the <code>User</code>
* object must be set, if the field is not set, then the value in DB will be
* set to <code>Null</code>
*
* @param user
* @return <code>true</code> if the user was updated successfully, <code>false</code> otherwise
*
* @throws <code>com.parq.server.dao.exception.DuplicateEmailException</code> if
* the email already exist in the system, and is not tied to this user.
*/
public synchronized boolean updateUser(User user) {
if (user == null || user.getEmail() == null || user.getUserID() <= 0) {
throw new IllegalStateException("Invalid user update request");
}
// test to make sure no duplicate email is used
User tempUser = getUserByEmail(user.getEmail());
if(tempUser != null && tempUser.getUserID() != user.getUserID()) {
throw new DuplicateEmailException("Email: " + user.getEmail() + " already exist");
}
// clear out the cache entry for user that is going to be updated
- revokeUserCacheById(user.getUserID());
+ clearUserCache();
PreparedStatement pstmt = null;
Connection con = null;
boolean updateSuccessful = false;
try {
con = getConnection();
pstmt = con.prepareStatement(sqlUpdateUser);
pstmt.setString(1, user.getPassword());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPhoneNumber());
pstmt.setLong(4, user.getUserID());
updateSuccessful = pstmt.executeUpdate() > 0;
if (updateSuccessful) {
updateSuccessful &= updateDjangoUser(user, con);
}
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
return updateSuccessful;
}
/**
* Create a new user. Note all the field on the <code>User</code>, expect
* the userId field object must be set, if any of the the fields is not set,
* then the value in DB will be set to <code>Null</code>
*
* @param user
* @return <code>true</code> if the user was updated successfully,
* <code>false</code> otherwise
* @throws <code>com.parq.server.dao.exception.DuplicateEmailException</code> if
* the email associated with this new user already exist.
*/
public synchronized boolean createNewUser(User user) {
if (user == null || user.getEmail() == null) {
throw new IllegalStateException("Invalid user create request");
}
// test to make sure no duplicate email is used
else if(getUserByEmail(user.getEmail()) != null) {
throw new DuplicateEmailException("Email: " + user.getEmail() + " already exist");
}
// clear out the cache entry for user that is going to be updated
revokeCache(myCache, emailCache, user.getEmail());
PreparedStatement pstmt = null;
Connection con = null;
boolean newUserCreated = false;
try {
con = getConnection();
// create the auth_user table entry first before creating the user table entry
int djangoId = createDjangoUser(user, con);
if (djangoId > 0) {
pstmt = con.prepareStatement(sqlCreateUser);
pstmt.setString(1, user.getPassword());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPhoneNumber());
pstmt.setInt(4, djangoId);
newUserCreated = pstmt.executeUpdate() == 1;
}
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
return newUserCreated;
}
/**
* Revoke all the cache instance of this User by id and email address.
* @param userID
*/
private synchronized void revokeUserCacheById(long userID) {
if (userID < 0) {
return;
}
User user = getUserById(userID);
revokeCache(myCache, idCache, "" + userID);
if (user != null) {
revokeCache(myCache, emailCache, user.getEmail());
}
}
/**
* manually clear out the cache
* @return
*/
public boolean clearUserCache() {
myCache.removeAll();
return true;
}
/**
* Secondary query to be with the createUser method to keep the Django auth_user table in sync
*/
private int createDjangoUser(User user, Connection con) throws SQLException {
int DjangoAuthUserId = -1;
PreparedStatement pstmt = null;
// create the new auth_user
pstmt = con.prepareStatement(sqlDjangoCreateAuthUser);
pstmt.setString(1, user.getEmail());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPassword());
boolean newUserCreated = pstmt.executeUpdate() == 1;
// get the new auth_user's id
if (newUserCreated) {
pstmt = con.prepareStatement(sqlGetNewDjangoAuthUserId);
pstmt.setString(1, user.getEmail());
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.isBeforeFirst()) {
rs.next();
DjangoAuthUserId = rs.getInt("id");
}
else {
throw new RuntimeException("Invalid id from auth_user table");
}
}
return DjangoAuthUserId;
}
/**
* Secondary query to be with the updateUser method to keep the Django auth_user table insync
*/
private boolean updateDjangoUser(User user, Connection con) throws SQLException {
PreparedStatement pstmt = con.prepareStatement(sqlDjangoUpdateAuthUser);
pstmt.setString(1, user.getEmail());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPassword());
boolean updateSuccessful = pstmt.executeUpdate() > 0;
return updateSuccessful;
}
/**
* Secondary query to be with the deleteUser method to keep the Django auth_user table insync
*/
private boolean deleteDjangoUser(long id, String deletedEmail, Connection con) throws SQLException {
PreparedStatement pstmt = con.prepareStatement(sqlDjangoDeleteAuthUser);
pstmt.setString(1, deletedEmail);
pstmt.setString(2, deletedEmail);
pstmt.setLong(3, id);
boolean deleteSuccessful = pstmt.executeUpdate() > 0;
return deleteSuccessful;
}
}
| true | true | public synchronized boolean updateUser(User user) {
if (user == null || user.getEmail() == null || user.getUserID() <= 0) {
throw new IllegalStateException("Invalid user update request");
}
// test to make sure no duplicate email is used
User tempUser = getUserByEmail(user.getEmail());
if(tempUser != null && tempUser.getUserID() != user.getUserID()) {
throw new DuplicateEmailException("Email: " + user.getEmail() + " already exist");
}
// clear out the cache entry for user that is going to be updated
revokeUserCacheById(user.getUserID());
PreparedStatement pstmt = null;
Connection con = null;
boolean updateSuccessful = false;
try {
con = getConnection();
pstmt = con.prepareStatement(sqlUpdateUser);
pstmt.setString(1, user.getPassword());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPhoneNumber());
pstmt.setLong(4, user.getUserID());
updateSuccessful = pstmt.executeUpdate() > 0;
if (updateSuccessful) {
updateSuccessful &= updateDjangoUser(user, con);
}
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
return updateSuccessful;
}
| public synchronized boolean updateUser(User user) {
if (user == null || user.getEmail() == null || user.getUserID() <= 0) {
throw new IllegalStateException("Invalid user update request");
}
// test to make sure no duplicate email is used
User tempUser = getUserByEmail(user.getEmail());
if(tempUser != null && tempUser.getUserID() != user.getUserID()) {
throw new DuplicateEmailException("Email: " + user.getEmail() + " already exist");
}
// clear out the cache entry for user that is going to be updated
clearUserCache();
PreparedStatement pstmt = null;
Connection con = null;
boolean updateSuccessful = false;
try {
con = getConnection();
pstmt = con.prepareStatement(sqlUpdateUser);
pstmt.setString(1, user.getPassword());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPhoneNumber());
pstmt.setLong(4, user.getUserID());
updateSuccessful = pstmt.executeUpdate() > 0;
if (updateSuccessful) {
updateSuccessful &= updateDjangoUser(user, con);
}
} catch (SQLException sqle) {
System.out.println("SQL statement is invalid: " + pstmt);
sqle.printStackTrace();
throw new RuntimeException(sqle);
} finally {
closeConnection(con);
}
return updateSuccessful;
}
|
diff --git a/bundle/command/src/main/java/org/apache/karaf/bundle/command/BundleCommand.java b/bundle/command/src/main/java/org/apache/karaf/bundle/command/BundleCommand.java
index c34eca386..cd8b942c4 100644
--- a/bundle/command/src/main/java/org/apache/karaf/bundle/command/BundleCommand.java
+++ b/bundle/command/src/main/java/org/apache/karaf/bundle/command/BundleCommand.java
@@ -1,52 +1,52 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.bundle.command;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.apache.karaf.shell.util.ShellUtil;
import org.osgi.framework.Bundle;
/**
* Unique bundle command.
*/
public abstract class BundleCommand extends OsgiCommandSupport {
@Argument(index = 0, name = "id", description = "The bundle ID", required = true, multiValued = false)
long id;
protected Object doExecute() throws Exception {
return doExecute(true);
}
protected Object doExecute(boolean force) throws Exception {
Bundle bundle = getBundleContext().getBundle(id);
if (bundle == null) {
System.err.println("Bundle " + id + " not found");
return null;
}
- if (force || ShellUtil.isASystemBundle(bundleContext, bundle)) {
+ if (force || !ShellUtil.isASystemBundle(bundleContext, bundle)) {
doExecute(bundle);
} else {
System.err.println("Access to system bundle " + id + " is discouraged. You may override with -f");
}
return null;
}
protected abstract void doExecute(Bundle bundle) throws Exception;
}
| true | true | protected Object doExecute(boolean force) throws Exception {
Bundle bundle = getBundleContext().getBundle(id);
if (bundle == null) {
System.err.println("Bundle " + id + " not found");
return null;
}
if (force || ShellUtil.isASystemBundle(bundleContext, bundle)) {
doExecute(bundle);
} else {
System.err.println("Access to system bundle " + id + " is discouraged. You may override with -f");
}
return null;
}
| protected Object doExecute(boolean force) throws Exception {
Bundle bundle = getBundleContext().getBundle(id);
if (bundle == null) {
System.err.println("Bundle " + id + " not found");
return null;
}
if (force || !ShellUtil.isASystemBundle(bundleContext, bundle)) {
doExecute(bundle);
} else {
System.err.println("Access to system bundle " + id + " is discouraged. You may override with -f");
}
return null;
}
|
diff --git a/src/com/CC/Commands/StaffCommands.java b/src/com/CC/Commands/StaffCommands.java
index 7f6c373..a49c0e3 100644
--- a/src/com/CC/Commands/StaffCommands.java
+++ b/src/com/CC/Commands/StaffCommands.java
@@ -1,233 +1,235 @@
package com.CC.Commands;
import static org.bukkit.ChatColor.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.CC.Arenas.GameManager;
import com.CC.Commands.Staff.EndGame;
import com.CC.General.User;
import com.CC.General.UserManager;
import com.CC.General.onStartup;
import com.CC.Messages.PlayerMessages;
public class StaffCommands implements CommandExecutor
{
private final EndGame endgame;
private final onStartup plugin;
private final GameManager gamemanager;
private final PlayerMessages messages;
private final UserManager um;
public StaffCommands(onStartup instance)
{
plugin = instance;
endgame = new EndGame(plugin);
gamemanager = plugin.getGameManager();
messages = plugin.getMessages();
um = plugin.getUserManager();
}
public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args)
{
if(!(sender instanceof Player))
{
sender.sendMessage("Sorry but this command can only be used in game");
return false;
}
Player player = (Player)sender;
if(!player.hasPermission("ClusterChunk.Admin")){
player.sendMessage(messages.noPermissionCommand(player));
return false;
}
if(string.equalsIgnoreCase("endgame"))
{
if(args.length == 0)
{
player.sendMessage(new StringBuilder(GREEN.toString()).append("Correct Usage: /endgame <Game> <Reason> || /endgame <Game> <Reason>").toString());
return false;
}
else if(args.length == 1)
{
if(gamemanager.isGame(args[0]))
{
return endgame.endGame(player, gamemanager.getGame(args[0]), " No specified reason");
}
else
{
player.sendMessage(new StringBuilder(RED.toString()).append("The game you have specified does not exist").toString());
return false;
}
}
else if(args.length >= 2)
{
System.out.println(glue(args, " "));
if(gamemanager.isGame(args[0]))
{
return endgame.endGame(player, gamemanager.getGame(args[0]), glue(args, " "));
}
else
{
player.sendMessage(new StringBuilder(RED.toString()).append("The game you have specified does not exist").toString());
return false;
}
}
}
else if(string.equalsIgnoreCase("rep"))
{
if(args.length == 0)
{
player.sendMessage("Correct Usage: /rep <player>");
}
else if(args.length == 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
player.sendMessage(ChatColor.GRAY + args[0] + "'s Reputation is " + ChatColor.DARK_GRAY + um.getUser(Bukkit.getPlayer(args[0])).getReputation());
}
else
{
player.sendMessage(ChatColor.RED + "The player you have specified does not exist");
}
}
- else if(args.length == 2)
+ else if(args.length == 3)
{
if(player.hasPermission("ClusterChunk.Admin"))
{
if(args[0].equalsIgnoreCase("add"))
{
if(Bukkit.getPlayer(args[1]) != null)
{
if(isInt(args[2])){
User user = um.getUser(Bukkit.getPlayer(args[1]));
int old = user.getReputation();
if(old + Integer.parseInt(args[2]) <= 10)
{
user.changeReputation(old + Integer.parseInt(args[2]));
player.sendMessage(args[1] + "'s reputation is now " + user.getReputation());
- um.updatePlayer(user, "stats");
+ um.updatePlayer(user, "reputation");
+ Bukkit.getPlayer(args[1]).sendMessage(ChatColor.GRAY + player.getName() + " has added " + ChatColor.DARK_GRAY + args[2] + ChatColor.GRAY + " to your reputation");
}
else
{
player.sendMessage(ChatColor.RED + "You may not make a player's reputation more than 10");
player.sendMessage(ChatColor.RED + "Please try a different amount");
}
}
else
{
player.sendMessage(ChatColor.RED + args[2] + " is not an integer!");
}
}
else
{
player.sendMessage(ChatColor.RED + "The specified user does not exist");
}
}
else if(args[0].equalsIgnoreCase("take"))
{
if(Bukkit.getPlayer(args[1]) != null)
{
if(isInt(args[2])){
User user = um.getUser(Bukkit.getPlayer(args[1]));
int old = user.getReputation();
if(old - Integer.parseInt(args[2]) >= 0)
{
- user.changeReputation(old + Integer.parseInt(args[2]));
+ user.changeReputation(old - Integer.parseInt(args[2]));
player.sendMessage(args[1] + "'s reputation is now " + user.getReputation());
- um.updatePlayer(user, "stats");
+ um.updatePlayer(user, "reputation");
+ Bukkit.getPlayer(args[1]).sendMessage(ChatColor.GRAY + player.getName() + " has removed " + ChatColor.DARK_GRAY + args[2] + ChatColor.GRAY + " from your reputation");
}
else
{
player.sendMessage(ChatColor.RED + "You may not make a player's reputation negative!");
player.sendMessage(ChatColor.RED + "Please try a different amount");
}
}
else
{
player.sendMessage(ChatColor.RED + args[2] + " is not an integer!");
}
}
else
{
player.sendMessage(ChatColor.RED + "The specified user does not exist");
}
}
}
else
{
player.sendMessage("Correct Usage: /rep <player>");
}
}
}
else if(string.equalsIgnoreCase("kick"))
{
if(player.hasPermission("ClusterChunk.Admin"))
{
if(args.length == 0 )
{
player.sendMessage("Correct Usage: /kick <player> <reason>(optional)");
}
else if(args.length == 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
Bukkit.getPlayer(args[0]).kickPlayer(ChatColor.RED + "You have been kicked by an admin");
player.sendMessage("You have kicked " + args[0]);
}
else
{
player.sendMessage(ChatColor.RED + "The specified player does not exist!");
}
}
else if(args.length > 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
Bukkit.getPlayer(args[0]).kickPlayer(ChatColor.RED + player.getName() + ": " + glue(args, " "));
player.sendMessage("You have kicked " + args[0]);
}
else
{
player.sendMessage(ChatColor.RED + "The specified player does not exist!");
}
}
}
}
return false;
}
public String glue(String[] array, String glue)
{
StringBuilder glued = new StringBuilder();
for(int i = 1; i < array.length;i++)
{
glued.append(array[i]);
if(i != array.length-1)
glued.append(glue);
}
return glued.toString();
}
public boolean isInt(String string){
try{
Integer.parseInt(string);
}catch(Exception e){
return false;
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args)
{
if(!(sender instanceof Player))
{
sender.sendMessage("Sorry but this command can only be used in game");
return false;
}
Player player = (Player)sender;
if(!player.hasPermission("ClusterChunk.Admin")){
player.sendMessage(messages.noPermissionCommand(player));
return false;
}
if(string.equalsIgnoreCase("endgame"))
{
if(args.length == 0)
{
player.sendMessage(new StringBuilder(GREEN.toString()).append("Correct Usage: /endgame <Game> <Reason> || /endgame <Game> <Reason>").toString());
return false;
}
else if(args.length == 1)
{
if(gamemanager.isGame(args[0]))
{
return endgame.endGame(player, gamemanager.getGame(args[0]), " No specified reason");
}
else
{
player.sendMessage(new StringBuilder(RED.toString()).append("The game you have specified does not exist").toString());
return false;
}
}
else if(args.length >= 2)
{
System.out.println(glue(args, " "));
if(gamemanager.isGame(args[0]))
{
return endgame.endGame(player, gamemanager.getGame(args[0]), glue(args, " "));
}
else
{
player.sendMessage(new StringBuilder(RED.toString()).append("The game you have specified does not exist").toString());
return false;
}
}
}
else if(string.equalsIgnoreCase("rep"))
{
if(args.length == 0)
{
player.sendMessage("Correct Usage: /rep <player>");
}
else if(args.length == 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
player.sendMessage(ChatColor.GRAY + args[0] + "'s Reputation is " + ChatColor.DARK_GRAY + um.getUser(Bukkit.getPlayer(args[0])).getReputation());
}
else
{
player.sendMessage(ChatColor.RED + "The player you have specified does not exist");
}
}
else if(args.length == 2)
{
if(player.hasPermission("ClusterChunk.Admin"))
{
if(args[0].equalsIgnoreCase("add"))
{
if(Bukkit.getPlayer(args[1]) != null)
{
if(isInt(args[2])){
User user = um.getUser(Bukkit.getPlayer(args[1]));
int old = user.getReputation();
if(old + Integer.parseInt(args[2]) <= 10)
{
user.changeReputation(old + Integer.parseInt(args[2]));
player.sendMessage(args[1] + "'s reputation is now " + user.getReputation());
um.updatePlayer(user, "stats");
}
else
{
player.sendMessage(ChatColor.RED + "You may not make a player's reputation more than 10");
player.sendMessage(ChatColor.RED + "Please try a different amount");
}
}
else
{
player.sendMessage(ChatColor.RED + args[2] + " is not an integer!");
}
}
else
{
player.sendMessage(ChatColor.RED + "The specified user does not exist");
}
}
else if(args[0].equalsIgnoreCase("take"))
{
if(Bukkit.getPlayer(args[1]) != null)
{
if(isInt(args[2])){
User user = um.getUser(Bukkit.getPlayer(args[1]));
int old = user.getReputation();
if(old - Integer.parseInt(args[2]) >= 0)
{
user.changeReputation(old + Integer.parseInt(args[2]));
player.sendMessage(args[1] + "'s reputation is now " + user.getReputation());
um.updatePlayer(user, "stats");
}
else
{
player.sendMessage(ChatColor.RED + "You may not make a player's reputation negative!");
player.sendMessage(ChatColor.RED + "Please try a different amount");
}
}
else
{
player.sendMessage(ChatColor.RED + args[2] + " is not an integer!");
}
}
else
{
player.sendMessage(ChatColor.RED + "The specified user does not exist");
}
}
}
else
{
player.sendMessage("Correct Usage: /rep <player>");
}
}
}
else if(string.equalsIgnoreCase("kick"))
{
if(player.hasPermission("ClusterChunk.Admin"))
{
if(args.length == 0 )
{
player.sendMessage("Correct Usage: /kick <player> <reason>(optional)");
}
else if(args.length == 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
Bukkit.getPlayer(args[0]).kickPlayer(ChatColor.RED + "You have been kicked by an admin");
player.sendMessage("You have kicked " + args[0]);
}
else
{
player.sendMessage(ChatColor.RED + "The specified player does not exist!");
}
}
else if(args.length > 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
Bukkit.getPlayer(args[0]).kickPlayer(ChatColor.RED + player.getName() + ": " + glue(args, " "));
player.sendMessage("You have kicked " + args[0]);
}
else
{
player.sendMessage(ChatColor.RED + "The specified player does not exist!");
}
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args)
{
if(!(sender instanceof Player))
{
sender.sendMessage("Sorry but this command can only be used in game");
return false;
}
Player player = (Player)sender;
if(!player.hasPermission("ClusterChunk.Admin")){
player.sendMessage(messages.noPermissionCommand(player));
return false;
}
if(string.equalsIgnoreCase("endgame"))
{
if(args.length == 0)
{
player.sendMessage(new StringBuilder(GREEN.toString()).append("Correct Usage: /endgame <Game> <Reason> || /endgame <Game> <Reason>").toString());
return false;
}
else if(args.length == 1)
{
if(gamemanager.isGame(args[0]))
{
return endgame.endGame(player, gamemanager.getGame(args[0]), " No specified reason");
}
else
{
player.sendMessage(new StringBuilder(RED.toString()).append("The game you have specified does not exist").toString());
return false;
}
}
else if(args.length >= 2)
{
System.out.println(glue(args, " "));
if(gamemanager.isGame(args[0]))
{
return endgame.endGame(player, gamemanager.getGame(args[0]), glue(args, " "));
}
else
{
player.sendMessage(new StringBuilder(RED.toString()).append("The game you have specified does not exist").toString());
return false;
}
}
}
else if(string.equalsIgnoreCase("rep"))
{
if(args.length == 0)
{
player.sendMessage("Correct Usage: /rep <player>");
}
else if(args.length == 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
player.sendMessage(ChatColor.GRAY + args[0] + "'s Reputation is " + ChatColor.DARK_GRAY + um.getUser(Bukkit.getPlayer(args[0])).getReputation());
}
else
{
player.sendMessage(ChatColor.RED + "The player you have specified does not exist");
}
}
else if(args.length == 3)
{
if(player.hasPermission("ClusterChunk.Admin"))
{
if(args[0].equalsIgnoreCase("add"))
{
if(Bukkit.getPlayer(args[1]) != null)
{
if(isInt(args[2])){
User user = um.getUser(Bukkit.getPlayer(args[1]));
int old = user.getReputation();
if(old + Integer.parseInt(args[2]) <= 10)
{
user.changeReputation(old + Integer.parseInt(args[2]));
player.sendMessage(args[1] + "'s reputation is now " + user.getReputation());
um.updatePlayer(user, "reputation");
Bukkit.getPlayer(args[1]).sendMessage(ChatColor.GRAY + player.getName() + " has added " + ChatColor.DARK_GRAY + args[2] + ChatColor.GRAY + " to your reputation");
}
else
{
player.sendMessage(ChatColor.RED + "You may not make a player's reputation more than 10");
player.sendMessage(ChatColor.RED + "Please try a different amount");
}
}
else
{
player.sendMessage(ChatColor.RED + args[2] + " is not an integer!");
}
}
else
{
player.sendMessage(ChatColor.RED + "The specified user does not exist");
}
}
else if(args[0].equalsIgnoreCase("take"))
{
if(Bukkit.getPlayer(args[1]) != null)
{
if(isInt(args[2])){
User user = um.getUser(Bukkit.getPlayer(args[1]));
int old = user.getReputation();
if(old - Integer.parseInt(args[2]) >= 0)
{
user.changeReputation(old - Integer.parseInt(args[2]));
player.sendMessage(args[1] + "'s reputation is now " + user.getReputation());
um.updatePlayer(user, "reputation");
Bukkit.getPlayer(args[1]).sendMessage(ChatColor.GRAY + player.getName() + " has removed " + ChatColor.DARK_GRAY + args[2] + ChatColor.GRAY + " from your reputation");
}
else
{
player.sendMessage(ChatColor.RED + "You may not make a player's reputation negative!");
player.sendMessage(ChatColor.RED + "Please try a different amount");
}
}
else
{
player.sendMessage(ChatColor.RED + args[2] + " is not an integer!");
}
}
else
{
player.sendMessage(ChatColor.RED + "The specified user does not exist");
}
}
}
else
{
player.sendMessage("Correct Usage: /rep <player>");
}
}
}
else if(string.equalsIgnoreCase("kick"))
{
if(player.hasPermission("ClusterChunk.Admin"))
{
if(args.length == 0 )
{
player.sendMessage("Correct Usage: /kick <player> <reason>(optional)");
}
else if(args.length == 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
Bukkit.getPlayer(args[0]).kickPlayer(ChatColor.RED + "You have been kicked by an admin");
player.sendMessage("You have kicked " + args[0]);
}
else
{
player.sendMessage(ChatColor.RED + "The specified player does not exist!");
}
}
else if(args.length > 1)
{
if(Bukkit.getPlayer(args[0]) != null)
{
Bukkit.getPlayer(args[0]).kickPlayer(ChatColor.RED + player.getName() + ": " + glue(args, " "));
player.sendMessage("You have kicked " + args[0]);
}
else
{
player.sendMessage(ChatColor.RED + "The specified player does not exist!");
}
}
}
}
return false;
}
|
diff --git a/com.genericworkflownodes.knime/src/com/genericworkflownodes/knime/generic_node/GenericKnimeNodeModel.java b/com.genericworkflownodes.knime/src/com/genericworkflownodes/knime/generic_node/GenericKnimeNodeModel.java
index be04fc0..9323598 100644
--- a/com.genericworkflownodes.knime/src/com/genericworkflownodes/knime/generic_node/GenericKnimeNodeModel.java
+++ b/com.genericworkflownodes.knime/src/com/genericworkflownodes/knime/generic_node/GenericKnimeNodeModel.java
@@ -1,839 +1,839 @@
/**
* Copyright (c) 2011-2012, Marc Röttig, Stephan Aiche.
*
* This file is part of GenericKnimeNodes.
*
* GenericKnimeNodes is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.genericworkflownodes.knime.generic_node;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.knime.base.filehandling.mime.MIMEMap;
import org.knime.core.data.uri.URIContent;
import org.knime.core.data.uri.URIPortObject;
import org.knime.core.data.uri.URIPortObjectSpec;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.ExecutionContext;
import org.knime.core.node.ExecutionMonitor;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeLogger;
import org.knime.core.node.NodeModel;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import org.knime.core.node.port.PortObject;
import org.knime.core.node.port.PortObjectSpec;
import org.knime.core.node.port.PortType;
import com.genericworkflownodes.knime.GenericNodesPlugin;
import com.genericworkflownodes.knime.base.data.prefixport.PrefixURIPortObject;
import com.genericworkflownodes.knime.config.INodeConfiguration;
import com.genericworkflownodes.knime.config.IPluginConfiguration;
import com.genericworkflownodes.knime.execution.AsynchronousToolExecutor;
import com.genericworkflownodes.knime.execution.ICommandGenerator;
import com.genericworkflownodes.knime.execution.IToolExecutor;
import com.genericworkflownodes.knime.execution.impl.CancelMonitorThread;
import com.genericworkflownodes.knime.parameter.FileListParameter;
import com.genericworkflownodes.knime.parameter.FileParameter;
import com.genericworkflownodes.knime.parameter.IFileParameter;
import com.genericworkflownodes.knime.parameter.InvalidParameterValueException;
import com.genericworkflownodes.knime.parameter.Parameter;
import com.genericworkflownodes.knime.port.Port;
import com.genericworkflownodes.knime.toolfinderservice.ExternalTool;
import com.genericworkflownodes.knime.toolfinderservice.PluginPreferenceToolLocator;
import com.genericworkflownodes.util.FileStashFactory;
import com.genericworkflownodes.util.FileStashProperties;
import com.genericworkflownodes.util.Helper;
import com.genericworkflownodes.util.IFileStash;
/**
* The GenericKnimeNodeModel is the base class for all derived classes within
* the GenericKnimeNodes system.
*
* The base class is configured using a {@link INodeConfiguration} object,
* holding information about:
* <ul>
* <li>number of input and output ports</li>
* <li> {@link MIMEType}s of these ports</li>
* </ul>
*
* @author
*/
public abstract class GenericKnimeNodeModel extends NodeModel {
private static final NodeLogger LOGGER = NodeLogger
.getLogger(GenericKnimeNodeModel.class);
/**
* Short-cut for optional ports.
*/
public static final PortType OPTIONAL_PORT_TYPE = new PortType(
URIPortObject.class, true);
/**
* Contains information on which of the available output types is selected
* for each output port.
*/
protected int[] m_selectedOutputType;
/**
* stores the node configuration (i.e. parameters, ports, ..)
*/
private final INodeConfiguration m_nodeConfig;
/**
* The configuration of the encapsulating plugin.
*/
private final IPluginConfiguration m_pluginConfig;
/**
* The file endings supported by the input ports.
*/
private final String[][] m_fileEndingsInPorts;
/**
* The file endings supported by the output ports.
*/
private final String[][] m_fileEndingsOutPorts;
/**
* The actual m_executor used to run the tool.
*/
IToolExecutor m_executor;
/**
* The file stash that manages files generated by this node.
*/
private IFileStash m_fileStash;
/**
* Constructor for the node model.
*/
protected GenericKnimeNodeModel(INodeConfiguration nodeConfig,
IPluginConfiguration pluginConfig, String[][] fileEndingsInPorts,
String[][] fileEndingsOutPorts) {
super(createOPOs(nodeConfig.getInputPorts()), createOPOs(nodeConfig
.getOutputPorts()));
m_nodeConfig = nodeConfig;
m_pluginConfig = pluginConfig;
m_fileEndingsInPorts = new String[fileEndingsInPorts.length][];
Helper.array2dcopy(fileEndingsInPorts, m_fileEndingsInPorts);
m_fileEndingsOutPorts = new String[fileEndingsOutPorts.length][];
Helper.array2dcopy(fileEndingsOutPorts, m_fileEndingsOutPorts);
m_fileStash = FileStashFactory.createTemporary();
init();
}
protected void init() {
// init with [0,0,....,0]
m_selectedOutputType = new int[m_nodeConfig.getNumberOfOutputPorts()];
}
protected String getOutputType(int idx) {
return m_nodeConfig.getOutputPorts().get(idx).getMimeTypes()
.get(m_selectedOutputType[idx]);
}
protected int getOutputTypeIndex(int idx) {
return m_selectedOutputType[idx];
}
private static PortType[] createOPOs(List<Port> ports) {
PortType[] portTypes = new PortType[ports.size()];
Arrays.fill(portTypes, URIPortObject.TYPE);
for (int i = 0; i < ports.size(); i++) {
if (ports.get(i).isOptional()) {
portTypes[i] = OPTIONAL_PORT_TYPE;
}
}
return portTypes;
}
private void prepareExecute(final File jobdir, final ExecutionContext exec)
throws Exception {
instantiateToolExecutor();
m_executor.setWorkingDirectory(jobdir);
m_executor.prepareExecution(m_nodeConfig, m_pluginConfig);
executeTool(jobdir, exec);
}
/**
* Try to instantiate the IToolExecutor specified by the plugin.
*
* @throws Exception
*/
private void instantiateToolExecutor() throws Exception {
String executorClassName = "";
String commandGeneratorClassName = "";
try {
executorClassName = m_pluginConfig.getPluginProperties()
.getProperty("executor");
commandGeneratorClassName = m_pluginConfig.getPluginProperties()
.getProperty("commandGenerator");
if (executorClassName == null || "".equals(executorClassName)) {
throw new Exception(
"No m_executor was specified by the plugin.");
}
m_executor = (IToolExecutor) Class.forName(executorClassName)
.newInstance();
// configure the m_executor
ICommandGenerator generator = (ICommandGenerator) Class.forName(
commandGeneratorClassName).newInstance();
m_executor.setCommandGenerator(generator);
} catch (IllegalAccessException ex) {
throw new Exception(
"Could not instantiate m_executor/generator (IllegalAccessException): "
+ executorClassName + "/"
+ commandGeneratorClassName);
} catch (ClassNotFoundException ex) {
throw new Exception(
"Could not instantiate m_executor/generator (ClassNotFoundException): "
+ executorClassName + "/"
+ commandGeneratorClassName);
} catch (InstantiationException ex) {
throw new Exception(
"Could not instantiate m_executor/generator (InstantiationException): "
+ executorClassName + "/"
+ commandGeneratorClassName);
}
}
private void executeTool(final File jobdir, final ExecutionContext exec)
throws Exception {
final AsynchronousToolExecutor asyncExecutor = new AsynchronousToolExecutor(
m_executor);
asyncExecutor.invoke();
// create one thread that will periodically check if the user has
// cancelled the execution of the node
// if this monitor thread detects that a cancel was requested, then it
// will invoke the kill method
// of the asyncExecutor
final CancelMonitorThread monitorThread = new CancelMonitorThread(
asyncExecutor, exec);
monitorThread.start();
// wait until the execution completes
asyncExecutor.waitUntilFinished();
// also wait for the monitor thread to die
monitorThread.waitUntilFinished();
int retcode = -1;
try {
retcode = asyncExecutor.getReturnCode();
} catch (ExecutionException ex) {
// it means that the task threw an exception, assume retcode == -1
ex.printStackTrace();
}
GenericNodesPlugin.log("STDOUT: " + m_executor.getToolOutput());
GenericNodesPlugin.log("STDERR: " + m_executor.getToolErrorOutput());
GenericNodesPlugin.log("retcode=" + retcode);
if (retcode != 0) {
LOGGER.error("Failing process stdout: "
+ m_executor.getToolOutput());
LOGGER.error("Failing process stderr: "
+ m_executor.getToolErrorOutput());
throw new Exception("Execution of external tool failed.");
}
}
/**
* {@inheritDoc}
*/
@Override
protected void reset() {
// TODO Reset all parameters to its defaults .. how
// Models build during execute are cleared here.
// Also data handled in load/saveInternals will be erased here.
/*
* for(Parameter<?> param: config.getParameters()) {
* param.setValue(null); }
*/
}
/**
* {@inheritDoc}
*/
@Override
protected void saveSettingsTo(final NodeSettingsWO settings) {
for (String key : m_nodeConfig.getParameterKeys()) {
Parameter<?> param = m_nodeConfig.getParameter(key);
// skip file parameters
if (param instanceof IFileParameter)
continue;
settings.addString(key, param.getStringRep());
}
for (int i = 0; i < m_nodeConfig.getNumberOfOutputPorts(); i++) {
settings.addInt("GENERIC_KNIME_NODES_outtype#" + i,
getOutputTypeIndex(i));
}
}
/**
* {@inheritDoc}
*/
@Override
protected void loadValidatedSettingsFrom(final NodeSettingsRO settings)
throws InvalidSettingsException {
// - we know that values are validated and thus are valid
// - we xfer the values into the corresponding model objects
for (String key : m_nodeConfig.getParameterKeys()) {
// FileParameters are not set by the UI
if (m_nodeConfig.getParameter(key) instanceof IFileParameter)
continue;
String value = settings.getString(key);
try {
m_nodeConfig.getParameter(key).fillFromString(value);
} catch (InvalidParameterValueException e) {
e.printStackTrace();
}
}
for (int i = 0; i < m_nodeConfig.getNumberOfOutputPorts(); i++) {
int idx = settings.getInt("GENERIC_KNIME_NODES_outtype#" + i);
m_selectedOutputType[i] = idx;
}
}
/**
* {@inheritDoc}
*/
@Override
protected void validateSettings(final NodeSettingsRO settings)
throws InvalidSettingsException {
// - we validate incoming settings values here
// - we do not xfer values to member variables
// - we throw an exception if something is invalid
for (String key : m_nodeConfig.getParameterKeys()) {
Parameter<?> param = m_nodeConfig.getParameter(key);
// FileParameters are not set by the UI
if (param instanceof IFileParameter)
continue;
if (!param.isOptional()) {
if (!settings.containsKey(key)) {
GenericNodesPlugin
.log("\t no key found for mand. parameter " + key);
throw new InvalidSettingsException(
"no value for mandatory parameter " + key
+ " supplied");
}
if (settings.getString(key) == null) {
GenericNodesPlugin
.log("\t null value found for mand. parameter "
+ key);
throw new InvalidSettingsException(
"no value for mandatory parameter " + key
+ " supplied");
}
}
String value = settings.getString(key);
try {
param.fillFromString(value);
} catch (InvalidParameterValueException e) {
GenericNodesPlugin.log("\t invalid value for parameter " + key);
throw new InvalidSettingsException(
"invalid value for parameter " + key);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void loadInternals(final File internDir,
final ExecutionMonitor exec) throws IOException,
CanceledExecutionException {
File file = FileStashProperties.readLocation(internDir);
if (file != null) {
m_fileStash = FileStashFactory.createPersistent(file);
} else {
// leave temporary file stash
}
}
/**
* {@inheritDoc}
*/
@Override
protected void saveInternals(final File internDir,
final ExecutionMonitor exec) throws IOException,
CanceledExecutionException {
FileStashProperties.saveLocation(m_fileStash, internDir);
}
@Override
protected PortObjectSpec[] configure(PortObjectSpec[] inSpecs)
throws InvalidSettingsException {
// Test if the named tool exists in the tool-db, if not throws an
// exception to tell the user that the executable is missing.
checkIfToolExists();
for (Parameter<?> param : m_nodeConfig.getParameters()) {
if (!param.isOptional() && param.getValue() != null
&& "".equals(param.getStringRep())
&& !(param instanceof IFileParameter)) {
setWarningMessage("Some mandatory parameters might are not set.");
}
}
int nIn = m_fileEndingsInPorts.length;
for (int i = 0; i < nIn; i++) {
// not connected input ports have nulls in inSpec
if (inSpecs[i] == null) {
// .. if port is optional everything is fine
if (m_nodeConfig.getInputPorts().get(i).isOptional()) {
continue;
} else {
throw new InvalidSettingsException(
"Non-optional input port is not connected.");
}
}
URIPortObjectSpec spec = (URIPortObjectSpec) inSpecs[i];
// get MIMEType from incoming port
// TODO: we should check all file extensions, if its more then one
String mt = MIMEMap.getMIMEType(spec.getFileExtensions().get(0));
// check whether input MIMEType is in list of allowed MIMETypes
boolean ok = false;
for (int j = 0; j < m_fileEndingsInPorts[i].length && !ok; j++) {
if (mt.equals(MIMEMap.getMIMEType(m_fileEndingsInPorts[i][j]))) {
ok = true;
}
}
// we require consistent file endings for non prefix ports
if (!ok && !m_nodeConfig.getInputPorts().get(i).isPrefix()) {
String mismatch = String.format(
"has extension: [%s]; expected on of:[%s]", mt,
Arrays.toString(m_fileEndingsInPorts[i]));
throw new InvalidSettingsException(
"Invalid MIMEtype at port number " + i + " : "
+ mismatch);
}
}
return createOutSpec();
}
private void checkIfToolExists() throws InvalidSettingsException {
try {
File executable = PluginPreferenceToolLocator
.getToolLocatorService().getToolPath(
new ExternalTool(m_pluginConfig.getPluginId(),
m_nodeConfig.getName(), m_nodeConfig
.getExecutableName()));
if (executable == null) {
throw new InvalidSettingsException(
"Neither externally configured nor shipped "
+ "binaries exist for this node. Aborting execution.");
}
} catch (InvalidSettingsException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidSettingsException(
"Failed to find a matching executable in the Tool Registry. "
+ ex.getMessage());
}
}
protected PortObjectSpec[] createOutSpec() {
int nOut = m_fileEndingsOutPorts.length;
PortObjectSpec[] out_spec = new PortObjectSpec[nOut];
// set selected MIMEURIPortObjectSpecs at output ports
for (int i = 0; i < nOut; i++) {
// selected output MIMEType
int selectedMIMETypeIndex = getOutputTypeIndex(i);
// TODO: check
out_spec[i] = new URIPortObjectSpec(
m_fileEndingsOutPorts[i][selectedMIMETypeIndex]);
}
return out_spec;
}
@Override
protected PortObject[] execute(PortObject[] inObjects, ExecutionContext exec)
throws Exception {
// fetch node descriptors
String nodeName = m_nodeConfig.getName();
// create job directory
File jobdir = Helper
.getTempDir(nodeName, !GenericNodesPlugin.isDebug());
GenericNodesPlugin.log("jobdir=" + jobdir);
// transfer the incoming files into the nodeConfiguration
transferIncomingPorts2Config(inObjects);
// prepare input data and parameter values
List<List<URI>> outputFiles = transferOutgoingPorts2Config(jobdir,
inObjects);
// launch executable
prepareExecute(jobdir, exec);
// process result files
PortObject[] outports = processOutput(outputFiles, exec);
if (!GenericNodesPlugin.isDebug()) {
FileUtils.deleteDirectory(jobdir);
}
return outports;
}
/**
* Creates a list of lists of output files (as {@link URI}s) pointing to the
* files that will be generated by the executed tool.
*
* @param jobdir
* The working directory of the executable.
* @param inData
* The input data as {@link PortObject} array
* @return A list of lists of output files
* @throws Exception
* If the input has an invalid configuration.
*/
private List<List<URI>> transferOutgoingPorts2Config(final File jobdir,
PortObject[] inData) throws Exception {
List<List<URI>> outfiles = new ArrayList<List<URI>>();
int nOut = m_nodeConfig.getOutputPorts().size();
for (int i = 0; i < nOut; i++) {
Port port = m_nodeConfig.getOutputPorts().get(i);
String name = port.getName();
String ext = getOutputType(i);
Parameter<?> p = m_nodeConfig.getParameter(name);
// used to remember which files we actually generated here
List<URI> fileURIs = new ArrayList<URI>();
// basenames and number of output files guessed from input
List<String> basenames = getOutputBaseNames();
if (p instanceof FileListParameter && port.isMultiFile()) {
FileListParameter flp = (FileListParameter) p;
List<String> fileNames = new ArrayList<String>();
if (basenames.size() == 0) {
throw new Exception(
"Cannot determine number of output files if no input file is given.");
}
for (int f = 0; f < basenames.size(); ++f) {
// create basename: <base_name>_<port_nr>_<outfile_nr>
String file_basename = String.format("%s_%d_%d",
- basenames.get(i), i, f);
+ basenames.get(f), i, f);
File file = m_fileStash.getFile(file_basename, ext);
fileNames.add(file.getAbsolutePath());
fileURIs.add(file.toURI());
}
// overwrite existing settings with new values generated by the
// stash
flp.setValue(fileNames);
} else if (p instanceof FileParameter && !port.isMultiFile()) {
// if we have no basename to use (e.g., Node without input-file)
// we use the nodename
String basename;
if (basenames.isEmpty()) {
basename = m_nodeConfig.getName();
} else {
basename = basenames.get(0);
}
// create basename: <base_name>_<port_nr>_<outfile_nr>
String file_basename = String.format("%s_%d", basename, i);
// we do not append the file extension if we have a prefix
File file = m_fileStash.getFile(file_basename, ext);
((FileParameter) p).setValue(file.getAbsolutePath());
GenericNodesPlugin.log("> setting param " + name + "->" + file);
// remember output file
fileURIs.add(file.toURI());
} else {
throw new Exception(
"Invalid connection between ports and parameters.");
}
outfiles.add(fileURIs);
}
return outfiles;
}
/**
* Tries to guess the optimal output file names given all the input edges.
* The file names will be extracted from the configuration, hence the file
* names need to be transferred into config prior to using this method. See
* {@link GenericKnimeNodeModel#transferIncomingPorts2Config(PortObject[])}.
*
* @return A list of base names for the output files.
* @throws Exception
*/
private List<String> getOutputBaseNames() throws Exception {
// 1. we select always the list with the highest number of files.
// 2. we prefer lists over files (independent of the number of
// elements).
// 3. we prefer files over prefixes since we assume that prefixes are
// often indices or reference data
List<String> basenames = new ArrayList<String>();
// find the port
int naming_port = 0;
int max_size = -1;
boolean seen_prefix = false;
boolean is_fileParameter = false;
for (int i = 0; i < m_nodeConfig.getInputPorts().size(); ++i) {
Port port = m_nodeConfig.getInputPorts().get(i);
String name = port.getName();
Parameter<?> p = m_nodeConfig.getParameter(name);
if (p instanceof FileListParameter) {
FileListParameter flp = (FileListParameter) p;
if (max_size == -1
|| (is_fileParameter && (max_size <= flp.getValue()
.size()))) {
max_size = flp.getValue().size();
naming_port = i;
} else if (flp.getValue().size() != max_size) {
throw new Exception(
"The number of output files cannot be determined since multiple input file lists with disagreeing numbers exist.");
}
} else if (max_size == -1 || seen_prefix) {
// is a regular incoming port but we have no better option
max_size = 1;
naming_port = i;
// indicating that we have (for now) selected a file parameter
// which will be overruled by any FileListParameter
is_fileParameter = true;
seen_prefix = port.isPrefix();
}
}
if (m_nodeConfig.getInputPorts().size() > 0) {
// generate the filenames if there are input ports
// without ports, the names are set in transferOutgoingPorts2Config
Port port = m_nodeConfig.getInputPorts().get(naming_port);
String name = port.getName();
Parameter<?> p = m_nodeConfig.getParameter(name);
if (p instanceof FileListParameter) {
// we have multiple base names
FileListParameter flp = (FileListParameter) p;
for (String fName : flp.getValue()) {
basenames.add(FilenameUtils.getBaseName(fName));
}
} else {
// we only have a single basename
// FilenameUtils.getBaseName()
basenames.add(FilenameUtils.getBaseName(((FileParameter) p)
.getValue()));
}
}
return basenames;
}
/**
* Transfers the incoming ports into the config, that it can be written out
* into a config file or can be tranferred to the command line.
*
* @param inData
* The incoming port objects.
* @throws Exception
*/
private void transferIncomingPorts2Config(PortObject[] inData)
throws Exception {
// Transfer settings from the input ports into the configuration object
for (int i = 0; i < inData.length; i++) {
// skip optional and unconnected inport ports
if (inData[i] == null) {
continue;
}
// find the internal port for this PortObject
Port port = m_nodeConfig.getInputPorts().get(i);
URIPortObject po = (URIPortObject) inData[i];
List<URIContent> uris = po.getURIContents();
String name = port.getName();
boolean isMultiFile = port.isMultiFile();
boolean isPrefix = port.isPrefix();
if (uris.size() > 1 && (!isMultiFile && !isPrefix)) {
throw new Exception(
"URIPortObject with multiple URIs supplied at single URI port #"
+ i);
}
// find the associated parameter in the configuration
Parameter<?> p = m_nodeConfig.getParameter(name);
// check that we are actually referencing a file parameter from this
// port
if (!(p instanceof IFileParameter)) {
throw new Exception(
"Invalid reference from port to non-file parameter. URI port #"
+ i);
}
if (isPrefix) {
// we pass only the prefix to the tool
PrefixURIPortObject puri = (PrefixURIPortObject) inData[i];
((FileParameter) p).setValue(puri.getPrefix());
} else if (isMultiFile) {
// we need to collect all filenames and then set them as a batch
// in the config
List<String> filenames = new ArrayList<String>();
for (URIContent uric : uris) {
URI uri = uric.getURI();
filenames.add(new File(uri).getAbsolutePath());
}
((FileListParameter) p).setValue(filenames);
} else {
// just one filename
URI uri = uris.get(0).getURI();
String filename = new File(uri).getAbsolutePath();
((FileParameter) p).setValue(filename);
}
}
}
/**
* Converts the given list of output files to an array of {@link PortObject}
* s that can be passed on in the current workflow.
*
* @param outputFileNames
* The output name as list of lists of {@link URI}.
* @param exec
* The execution context of the current node.
* @return
* @throws NonExistingMimeTypeException
*/
private PortObject[] processOutput(final List<List<URI>> outputFileNames,
final ExecutionContext exec) throws NonExistingMimeTypeException {
int nOut = m_nodeConfig.getOutputPorts().size();
// create output tables
URIPortObject[] outports = new URIPortObject[nOut];
for (int i = 0; i < nOut; i++) {
List<URIContent> uris = new ArrayList<URIContent>();
String someFileName = "";
if (m_nodeConfig.getOutputPorts().get(i).isPrefix()) {
// we have generated a list of files based on a prefix
URI filename = outputFileNames.get(i).get(0);
final File f = new File(filename);
final String f_name = f.getName();
// list a files sharing the prefix
String[] files = f.getParentFile().list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(f_name);
}
});
// add prefix to and files to output list
for (String file_name : files) {
uris.add(new URIContent(new File(f.getParentFile(),
file_name).toURI(), getExtension(file_name)));
}
outports[i] = new PrefixURIPortObject(uris, f.getAbsolutePath());
} else {
// multi output file
for (URI filename : outputFileNames.get(i)) {
someFileName = filename.getPath();
uris.add(new URIContent(filename, getExtension(filename
.getPath())));
}
String mimeType = getExtension(someFileName);
if (mimeType == null)
throw new NonExistingMimeTypeException(someFileName);
outports[i] = new URIPortObject(uris);
}
}
return outports;
}
/**
* Extracts the extension from the given path.
*
* @param path
* @return
*/
private String getExtension(String path) {
if (path.lastIndexOf('.') == -1) {
return "";
} else {
return path.substring(path.lastIndexOf('.') + 1);
}
}
}
| true | true | private List<List<URI>> transferOutgoingPorts2Config(final File jobdir,
PortObject[] inData) throws Exception {
List<List<URI>> outfiles = new ArrayList<List<URI>>();
int nOut = m_nodeConfig.getOutputPorts().size();
for (int i = 0; i < nOut; i++) {
Port port = m_nodeConfig.getOutputPorts().get(i);
String name = port.getName();
String ext = getOutputType(i);
Parameter<?> p = m_nodeConfig.getParameter(name);
// used to remember which files we actually generated here
List<URI> fileURIs = new ArrayList<URI>();
// basenames and number of output files guessed from input
List<String> basenames = getOutputBaseNames();
if (p instanceof FileListParameter && port.isMultiFile()) {
FileListParameter flp = (FileListParameter) p;
List<String> fileNames = new ArrayList<String>();
if (basenames.size() == 0) {
throw new Exception(
"Cannot determine number of output files if no input file is given.");
}
for (int f = 0; f < basenames.size(); ++f) {
// create basename: <base_name>_<port_nr>_<outfile_nr>
String file_basename = String.format("%s_%d_%d",
basenames.get(i), i, f);
File file = m_fileStash.getFile(file_basename, ext);
fileNames.add(file.getAbsolutePath());
fileURIs.add(file.toURI());
}
// overwrite existing settings with new values generated by the
// stash
flp.setValue(fileNames);
} else if (p instanceof FileParameter && !port.isMultiFile()) {
// if we have no basename to use (e.g., Node without input-file)
// we use the nodename
String basename;
if (basenames.isEmpty()) {
basename = m_nodeConfig.getName();
} else {
basename = basenames.get(0);
}
// create basename: <base_name>_<port_nr>_<outfile_nr>
String file_basename = String.format("%s_%d", basename, i);
// we do not append the file extension if we have a prefix
File file = m_fileStash.getFile(file_basename, ext);
((FileParameter) p).setValue(file.getAbsolutePath());
GenericNodesPlugin.log("> setting param " + name + "->" + file);
// remember output file
fileURIs.add(file.toURI());
} else {
throw new Exception(
"Invalid connection between ports and parameters.");
}
outfiles.add(fileURIs);
}
return outfiles;
}
| private List<List<URI>> transferOutgoingPorts2Config(final File jobdir,
PortObject[] inData) throws Exception {
List<List<URI>> outfiles = new ArrayList<List<URI>>();
int nOut = m_nodeConfig.getOutputPorts().size();
for (int i = 0; i < nOut; i++) {
Port port = m_nodeConfig.getOutputPorts().get(i);
String name = port.getName();
String ext = getOutputType(i);
Parameter<?> p = m_nodeConfig.getParameter(name);
// used to remember which files we actually generated here
List<URI> fileURIs = new ArrayList<URI>();
// basenames and number of output files guessed from input
List<String> basenames = getOutputBaseNames();
if (p instanceof FileListParameter && port.isMultiFile()) {
FileListParameter flp = (FileListParameter) p;
List<String> fileNames = new ArrayList<String>();
if (basenames.size() == 0) {
throw new Exception(
"Cannot determine number of output files if no input file is given.");
}
for (int f = 0; f < basenames.size(); ++f) {
// create basename: <base_name>_<port_nr>_<outfile_nr>
String file_basename = String.format("%s_%d_%d",
basenames.get(f), i, f);
File file = m_fileStash.getFile(file_basename, ext);
fileNames.add(file.getAbsolutePath());
fileURIs.add(file.toURI());
}
// overwrite existing settings with new values generated by the
// stash
flp.setValue(fileNames);
} else if (p instanceof FileParameter && !port.isMultiFile()) {
// if we have no basename to use (e.g., Node without input-file)
// we use the nodename
String basename;
if (basenames.isEmpty()) {
basename = m_nodeConfig.getName();
} else {
basename = basenames.get(0);
}
// create basename: <base_name>_<port_nr>_<outfile_nr>
String file_basename = String.format("%s_%d", basename, i);
// we do not append the file extension if we have a prefix
File file = m_fileStash.getFile(file_basename, ext);
((FileParameter) p).setValue(file.getAbsolutePath());
GenericNodesPlugin.log("> setting param " + name + "->" + file);
// remember output file
fileURIs.add(file.toURI());
} else {
throw new Exception(
"Invalid connection between ports and parameters.");
}
outfiles.add(fileURIs);
}
return outfiles;
}
|
diff --git a/src/com/redhat/ceylon/tools/help/CeylonHelpTool.java b/src/com/redhat/ceylon/tools/help/CeylonHelpTool.java
index 68460df8d..3b50ed557 100644
--- a/src/com/redhat/ceylon/tools/help/CeylonHelpTool.java
+++ b/src/com/redhat/ceylon/tools/help/CeylonHelpTool.java
@@ -1,108 +1,108 @@
package com.redhat.ceylon.tools.help;
import com.redhat.ceylon.common.tool.Argument;
import com.redhat.ceylon.common.tool.Description;
import com.redhat.ceylon.common.tool.Tool;
import com.redhat.ceylon.common.tool.ToolModel;
import com.redhat.ceylon.common.tool.RemainingSections;
import com.redhat.ceylon.common.tool.Summary;
import com.redhat.ceylon.common.tool.Tools;
import com.redhat.ceylon.common.tool.WordWrap;
import com.redhat.ceylon.tools.CeylonTool;
import com.redhat.ceylon.tools.help.Output.Synopsis;
/**
* A plugin which provides help about other plugins
* @author tom
*/
@Summary("Display help information about other ceylon tools")
@Description(
"If a `<tool>` is given, displays help about that ceylon tool on the standard output.\n\n" +
"If no `<tool>` is given, displays the synopsis of the top level `ceylon` command. "
)
@RemainingSections(
"## SEE ALSO\n\n" +
"* `ceylon doc-tool` for generating documentation about ceylon tools\n"
)
public class CeylonHelpTool extends AbstractDoc implements Tool {
private String tool;
@Argument(argumentName="tool", multiplicity="?")
public void setTool(String tool) {
this.tool = tool;
}
@Override
public void run() {
final WordWrap wrap = new WordWrap();
Output plain = new PlainOutput(wrap);
if (tool == null) {
printTopLevelHelp(plain, wrap, toolLoader.getToolNames());
} else {
final ToolModel<?> model = toolLoader.loadToolModel(tool);
if (model != null) {
printToolHelp(plain, new ToolDocumentation<>(model));
} else {
Tools.printToolSuggestions(toolLoader, wrap, tool);
}
}
wrap.flush();
}
protected final void printTopLevelHelp(Output out, WordWrap wrap, Iterable<String> toolNames) {
final ToolModel<CeylonTool> root = toolLoader.loadToolModel("");
final ToolDocumentation<CeylonTool> docModel = new ToolDocumentation<CeylonTool>(root);
printToolSummary(out, docModel);
Synopsis synopsis = out.startSynopsis(bundle.getString("section.SYNOPSIS"));
- synopsis.appendSynopsis(Tools.progName());
+ synopsis.appendSynopsis(Tools.progName() + " ");
synopsis.longOptionSynopsis("--version");
synopsis.nextSynopsis();
- synopsis.appendSynopsis(Tools.progName());
+ synopsis.appendSynopsis(Tools.progName() + " ");
synopsis.argumentSynopsis("[<cey-options>]");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("<command>");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("[<command-options>]");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("[<command-args>]");
synopsis.endSynopsis();
printToolDescription(out, docModel);
wrap.setIndent(8);
int max = 0;
for (String toolName : toolNames) {
max = Math.max(max, toolName.length());
}
wrap.addTabStop(max + 12);
wrap.setIndentRestLines(max + 12);
for (String toolName : toolNames) {
final ToolModel<Tool> model = toolLoader.loadToolModel(toolName);
if (model == null) {
throw new RuntimeException(toolName);
}
if (!model.isPorcelain()) {
continue;
}
final Class<Tool> toolClass = model.getToolClass();
final Summary summary = toolClass.getAnnotation(Summary.class);
wrap.append(toolName);
if (summary != null) {
wrap.tab().append(summary.value());
}
wrap.newline();
}
wrap.removeTabStop(max + 12);
wrap.setIndent(8);
wrap.newline();
wrap.append("See '" + Tools.progName() + " help <command>' for more information on a particular command");
wrap.setIndent(0);
wrap.newline();
}
}
| false | true | protected final void printTopLevelHelp(Output out, WordWrap wrap, Iterable<String> toolNames) {
final ToolModel<CeylonTool> root = toolLoader.loadToolModel("");
final ToolDocumentation<CeylonTool> docModel = new ToolDocumentation<CeylonTool>(root);
printToolSummary(out, docModel);
Synopsis synopsis = out.startSynopsis(bundle.getString("section.SYNOPSIS"));
synopsis.appendSynopsis(Tools.progName());
synopsis.longOptionSynopsis("--version");
synopsis.nextSynopsis();
synopsis.appendSynopsis(Tools.progName());
synopsis.argumentSynopsis("[<cey-options>]");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("<command>");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("[<command-options>]");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("[<command-args>]");
synopsis.endSynopsis();
printToolDescription(out, docModel);
wrap.setIndent(8);
int max = 0;
for (String toolName : toolNames) {
max = Math.max(max, toolName.length());
}
wrap.addTabStop(max + 12);
wrap.setIndentRestLines(max + 12);
for (String toolName : toolNames) {
final ToolModel<Tool> model = toolLoader.loadToolModel(toolName);
if (model == null) {
throw new RuntimeException(toolName);
}
if (!model.isPorcelain()) {
continue;
}
final Class<Tool> toolClass = model.getToolClass();
final Summary summary = toolClass.getAnnotation(Summary.class);
wrap.append(toolName);
if (summary != null) {
wrap.tab().append(summary.value());
}
wrap.newline();
}
wrap.removeTabStop(max + 12);
wrap.setIndent(8);
wrap.newline();
wrap.append("See '" + Tools.progName() + " help <command>' for more information on a particular command");
wrap.setIndent(0);
wrap.newline();
}
| protected final void printTopLevelHelp(Output out, WordWrap wrap, Iterable<String> toolNames) {
final ToolModel<CeylonTool> root = toolLoader.loadToolModel("");
final ToolDocumentation<CeylonTool> docModel = new ToolDocumentation<CeylonTool>(root);
printToolSummary(out, docModel);
Synopsis synopsis = out.startSynopsis(bundle.getString("section.SYNOPSIS"));
synopsis.appendSynopsis(Tools.progName() + " ");
synopsis.longOptionSynopsis("--version");
synopsis.nextSynopsis();
synopsis.appendSynopsis(Tools.progName() + " ");
synopsis.argumentSynopsis("[<cey-options>]");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("<command>");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("[<command-options>]");
synopsis.appendSynopsis(" ");
synopsis.argumentSynopsis("[<command-args>]");
synopsis.endSynopsis();
printToolDescription(out, docModel);
wrap.setIndent(8);
int max = 0;
for (String toolName : toolNames) {
max = Math.max(max, toolName.length());
}
wrap.addTabStop(max + 12);
wrap.setIndentRestLines(max + 12);
for (String toolName : toolNames) {
final ToolModel<Tool> model = toolLoader.loadToolModel(toolName);
if (model == null) {
throw new RuntimeException(toolName);
}
if (!model.isPorcelain()) {
continue;
}
final Class<Tool> toolClass = model.getToolClass();
final Summary summary = toolClass.getAnnotation(Summary.class);
wrap.append(toolName);
if (summary != null) {
wrap.tab().append(summary.value());
}
wrap.newline();
}
wrap.removeTabStop(max + 12);
wrap.setIndent(8);
wrap.newline();
wrap.append("See '" + Tools.progName() + " help <command>' for more information on a particular command");
wrap.setIndent(0);
wrap.newline();
}
|
diff --git a/src/test/java/net/paguo/trafshow/backend/snmp/summary/commands/GetTrafficDataCommandTest.java b/src/test/java/net/paguo/trafshow/backend/snmp/summary/commands/GetTrafficDataCommandTest.java
index 58078b6..50a6e82 100644
--- a/src/test/java/net/paguo/trafshow/backend/snmp/summary/commands/GetTrafficDataCommandTest.java
+++ b/src/test/java/net/paguo/trafshow/backend/snmp/summary/commands/GetTrafficDataCommandTest.java
@@ -1,28 +1,28 @@
package net.paguo.trafshow.backend.snmp.summary.commands;
import org.junit.Test;
import org.junit.Assert;
import java.util.Calendar;
import java.util.Date;
public class GetTrafficDataCommandTest{
@Test
public void testGetData(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 10);
Date begin = cal.getTime();
cal.roll(Calendar.HOUR_OF_DAY, 23);
- cal.roll(Calendar.MINUTE, 59);
- cal.roll(Calendar.SECOND, 59);
+ cal.set(Calendar.MINUTE, 59);
+ cal.set(Calendar.SECOND, 59);
Date end = cal.getTime();
GetTrafficDataCommand command = new GetTrafficDataCommand(begin, end);
Object result = command.getData();
Assert.assertNotNull(result);
}
}
| true | true | public void testGetData(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 10);
Date begin = cal.getTime();
cal.roll(Calendar.HOUR_OF_DAY, 23);
cal.roll(Calendar.MINUTE, 59);
cal.roll(Calendar.SECOND, 59);
Date end = cal.getTime();
GetTrafficDataCommand command = new GetTrafficDataCommand(begin, end);
Object result = command.getData();
Assert.assertNotNull(result);
}
| public void testGetData(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 10);
Date begin = cal.getTime();
cal.roll(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
Date end = cal.getTime();
GetTrafficDataCommand command = new GetTrafficDataCommand(begin, end);
Object result = command.getData();
Assert.assertNotNull(result);
}
|
diff --git a/src/powercrystals/minefactoryreloaded/gui/MFRCreativeTab.java b/src/powercrystals/minefactoryreloaded/gui/MFRCreativeTab.java
index a87eeda2..b6d13e34 100644
--- a/src/powercrystals/minefactoryreloaded/gui/MFRCreativeTab.java
+++ b/src/powercrystals/minefactoryreloaded/gui/MFRCreativeTab.java
@@ -1,33 +1,34 @@
package powercrystals.minefactoryreloaded.gui;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
public class MFRCreativeTab extends CreativeTabs {
public static final MFRCreativeTab tab = new MFRCreativeTab("Minefactory Reloaded", new ItemStack(MineFactoryReloadedCore.conveyorBlock));
//-------------------
private String label;
private ItemStack icon;
public MFRCreativeTab(String label, ItemStack icon) {
super(label);
this.label = label;
+ this.icon = icon;
}
@Override
public ItemStack getIconItemStack() {
return icon;
}
@Override
public String getTabLabel() {
return this.label;
}
@Override
public String getTranslatedTabLabel() {
return this.getTabLabel();
}
}
| true | true | public MFRCreativeTab(String label, ItemStack icon) {
super(label);
this.label = label;
}
| public MFRCreativeTab(String label, ItemStack icon) {
super(label);
this.label = label;
this.icon = icon;
}
|
diff --git a/app/src/main/java/org/gdg/frisbee/android/adapter/NewsAdapter.java b/app/src/main/java/org/gdg/frisbee/android/adapter/NewsAdapter.java
index f6e9c5d2..0b6eafe8 100644
--- a/app/src/main/java/org/gdg/frisbee/android/adapter/NewsAdapter.java
+++ b/app/src/main/java/org/gdg/frisbee/android/adapter/NewsAdapter.java
@@ -1,422 +1,422 @@
/*
* Copyright 2013 The GDG Frisbee Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gdg.frisbee.android.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.PlusOneButton;
import com.google.api.services.plus.model.Activity;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import org.gdg.frisbee.android.R;
import org.gdg.frisbee.android.activity.YoutubeActivity;
import org.gdg.frisbee.android.app.App;
import org.gdg.frisbee.android.utils.Utils;
import org.gdg.frisbee.android.view.ResizableImageView;
import org.joda.time.DateTime;
/**
* GDG Aachen
* org.gdg.frisbee.android
* <p/>
* User: maui
* Date: 22.04.13
* Time: 02:48
*/
public class NewsAdapter extends BaseAdapter {
private static final String LOG_TAG = "GDG-NewsAdapter";
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Item> mActivities;
private PlusClient mPlusClient;
public NewsAdapter(Context ctx, PlusClient client) {
mContext = ctx;
mPlusClient = client;
mInflater = LayoutInflater.from(mContext);
mActivities = new ArrayList<Item>();
}
public void addAll(Collection<Activity> items) {
for(Activity a : items) {
mActivities.add(new Item(a));
}
notifyDataSetChanged();
}
public void replaceAll(Collection<Activity> items, int start) {
for(Activity a : items) {
if(start < mActivities.size()) {
if(a.getId().equals(mActivities.get(start).getActivity().getId())) {
mActivities.set(start, new Item(a));
} else {
mActivities.add(start, new Item(a));
start++;
}
} else {
mActivities.add(new Item(a));
}
start++;
}
notifyDataSetChanged();
}
public void add(Activity item) {
mActivities.add(new Item(item));
notifyDataSetChanged();
}
public void clear() {
mActivities.clear();
notifyDataSetChanged();
}
@Override
public int getCount() {
return mActivities.size();
}
@Override
public Object getItem(int i) {
return mActivities.get(i).getActivity();
}
public Item getItemInternal(int i) {
return mActivities.get(i);
}
@Override
public long getItemId(int i) {
return Utils.stringToLong(getItemInternal(i).getActivity().getId());
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getViewTypeCount() {
// nothing, article, video, photo, album, event
return 6;
}
@Override
public int getItemViewType(int position) {
Item item = (Item) getItemInternal(position);
Activity activity = item.getActivity();
if(activity.getObject().getAttachments() == null || activity.getObject().getAttachments().isEmpty())
return 0;
else {
Activity.PlusObject.Attachments attachment = activity.getObject().getAttachments().get(0);
String objectType = attachment.getObjectType();
if(objectType.equals("article"))
return 1;
else if(objectType.equals("video"))
return 2;
else if(objectType.equals("photo"))
return 3;
else if(objectType.equals("album"))
return 4;
else if(objectType.equals("event"))
return 5;
}
return 0;
}
public void updatePlusOne(View v) {
if(v != null && v.getTag() != null) {
String url = (String) v.getTag();
PlusOneButton plusButton = (PlusOneButton) v.findViewById(R.id.plus_one_button);
if(mPlusClient != null && mPlusClient.isConnected()) {
plusButton.setVisibility(View.VISIBLE);
plusButton.initialize(mPlusClient, url, 1);
}
}
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null)
view = mInflater.inflate(R.layout.news_item_base, null);
Item item = (Item) getItemInternal(i);
final Activity activity = item.getActivity();
view.setTag(activity.getUrl());
ViewGroup container = (ViewGroup) view.findViewById(R.id.attachmentContainer);
PlusOneButton plusButton = (PlusOneButton) view.findViewById(R.id.plus_one_button);
- if(mPlusClient != null) {
+ if(mPlusClient != null && mPlusClient.isConnected()) {
plusButton.setVisibility(View.VISIBLE);
plusButton.initialize(mPlusClient, activity.getUrl(), 1);
} else {
plusButton.setVisibility(View.GONE);
}
/*ResizableImageView picture = (ResizableImageView) view.findViewById(R.id.image);
picture.setOnClickListener(null);
picture.setImageDrawable(null);*/
TextView timeStamp = (TextView) view.findViewById(R.id.timestamp);
if(activity.getPublished() != null) {
timeStamp.setVisibility(View.VISIBLE);
timeStamp.setText(Utils.toHumanTimePeriod(mContext,new DateTime(activity.getPublished().getValue()), DateTime.now()));
} else {
timeStamp.setVisibility(View.GONE);
}
if(activity.getVerb().equals("share"))
populateShare(activity, view);
else
populatePost(activity, view);
if(activity.getObject().getAttachments() != null && activity.getObject().getAttachments().size() > 0) {
final Activity.PlusObject.Attachments attachment = activity.getObject().getAttachments().get(0);
switch(getItemViewType(i)) {
case 1:
// Article
populateArticle(container, attachment);
break;
case 2:
// Video
populateVideo(container, attachment);
break;
case 3:
// Photo
populatePhoto(container, attachment);
break;
case 4:
// Album
populateAlbum(container, attachment);
break;
case 5:
// Album
populateEvent(container, attachment);
break;
}
}
// That item will contain a special property that tells if it was freshly retrieved
if (!item.isConsumed()) {
item.setConsumed(true);
// In which case we magically instantiate our effect and launch it directly on the view
Animation animation = AnimationUtils.makeInChildBottomAnimation(mContext);
view.startAnimation(animation);
}
return view;
}
private View createAttachmentView(ViewGroup container, int layout) {
View attachmentView = null;
if(container.getChildCount() == 0) {
attachmentView = mInflater.inflate(layout, null);
container.addView(attachmentView);
} else {
attachmentView = container.getChildAt(0);
}
return attachmentView;
}
private void populateArticle(ViewGroup container, final Activity.PlusObject.Attachments attachment) {
if(attachment == null)
return;
View attachmentView = createAttachmentView(container, R.layout.news_item_article);
ImageView articleImage = (ImageView) attachmentView.findViewById(R.id.image);
TextView title = (TextView)attachmentView.findViewById(R.id.displayName);
TextView content = (TextView)attachmentView.findViewById(R.id.content);
title.setText(attachment.getDisplayName());
try {
content.setText(new URL(attachment.getUrl()).getHost());
} catch (MalformedURLException e) {
e.printStackTrace();
}
if(attachment.getImage() == null && attachment.getFullImage() == null)
articleImage.setVisibility(View.GONE);
else {
String imageUrl = attachment.getImage().getUrl();
if(attachment.getFullImage() != null)
imageUrl = attachment.getFullImage().getUrl();
articleImage.setImageDrawable(null);
articleImage.setVisibility(View.VISIBLE);
App.getInstance().getPicasso()
.load(imageUrl)
.into(articleImage);
}
attachmentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(attachment.getUrl()));
mContext.startActivity(i);
}
});
}
private void populateVideo(ViewGroup container, final Activity.PlusObject.Attachments attachment) {
if(attachment == null)
return;
View attachmentView = createAttachmentView(container, R.layout.news_item_video);
ResizableImageView poster = (ResizableImageView) attachmentView.findViewById(R.id.videoPoster);
App.getInstance().getPicasso()
.load(attachment.getImage().getUrl())
.into(poster);
attachmentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent playVideoIntent = new Intent(mContext, YoutubeActivity.class);
playVideoIntent.putExtra("video_id", Utils.splitQuery(new URL(attachment.getUrl())).get("v"));
mContext.startActivity(playVideoIntent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
private void populatePhoto(ViewGroup container, Activity.PlusObject.Attachments attachment) {
if(attachment == null)
return;
View attachmentView = createAttachmentView(container, R.layout.news_item_photo);
ResizableImageView photo = (ResizableImageView) attachmentView.findViewById(R.id.photo);
photo.setImageDrawable(null);
App.getInstance().getPicasso()
.load(attachment.getImage().getUrl())
.into(photo);
}
private void populateAlbum(ViewGroup container, Activity.PlusObject.Attachments attachment) {
if(attachment == null)
return;
View attachmentView = createAttachmentView(container, R.layout.news_item_album);
ImageView pic1 = (ImageView) attachmentView.findViewById(R.id.pic1);
ImageView pic2 = (ImageView) attachmentView.findViewById(R.id.pic2);
ImageView pic3 = (ImageView) attachmentView.findViewById(R.id.pic3);
App.getInstance().getPicasso()
.load(attachment.getThumbnails().get(0).getImage().getUrl())
.into(pic1);
if(attachment.getThumbnails().size() > 1)
App.getInstance().getPicasso()
.load(attachment.getThumbnails().get(1).getImage().getUrl())
.into(pic2);
if(attachment.getThumbnails().size() > 2)
App.getInstance().getPicasso()
.load(attachment.getThumbnails().get(2).getImage().getUrl())
.into(pic3);
}
private void populateEvent(ViewGroup container, Activity.PlusObject.Attachments attachment) {
View attachmentView = createAttachmentView(container, R.layout.news_item_event);
TextView content = (TextView) attachmentView.findViewById(R.id.content);
content.setText(attachment.getContent());
}
public void populatePost(Activity item, View v) {
TextView content = (TextView) v.findViewById(R.id.content);
content.setText(Html.fromHtml(item.getObject().getContent()));
}
public void populateShare(Activity item, View v) {
TextView content = (TextView) v.findViewById(R.id.content);
if(item.getAnnotation() != null) {
content.setText(Html.fromHtml(item.getAnnotation() + "<hr/>"+item.getObject().getContent()));
} else {
content.setText(Html.fromHtml(item.getObject().getContent()));
}
}
public class Item {
private Activity mActivity;
private boolean mConsumed = false;
public Item(Activity a) {
mActivity = a;
mConsumed = false;
}
public Activity getActivity() {
return mActivity;
}
public void setActivity(Activity mActivity) {
this.mActivity = mActivity;
}
public boolean isConsumed() {
return mConsumed;
}
public void setConsumed(boolean mConsumed) {
this.mConsumed = mConsumed;
}
}
}
| true | true | public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null)
view = mInflater.inflate(R.layout.news_item_base, null);
Item item = (Item) getItemInternal(i);
final Activity activity = item.getActivity();
view.setTag(activity.getUrl());
ViewGroup container = (ViewGroup) view.findViewById(R.id.attachmentContainer);
PlusOneButton plusButton = (PlusOneButton) view.findViewById(R.id.plus_one_button);
if(mPlusClient != null) {
plusButton.setVisibility(View.VISIBLE);
plusButton.initialize(mPlusClient, activity.getUrl(), 1);
} else {
plusButton.setVisibility(View.GONE);
}
/*ResizableImageView picture = (ResizableImageView) view.findViewById(R.id.image);
picture.setOnClickListener(null);
picture.setImageDrawable(null);*/
TextView timeStamp = (TextView) view.findViewById(R.id.timestamp);
if(activity.getPublished() != null) {
timeStamp.setVisibility(View.VISIBLE);
timeStamp.setText(Utils.toHumanTimePeriod(mContext,new DateTime(activity.getPublished().getValue()), DateTime.now()));
} else {
timeStamp.setVisibility(View.GONE);
}
if(activity.getVerb().equals("share"))
populateShare(activity, view);
else
populatePost(activity, view);
if(activity.getObject().getAttachments() != null && activity.getObject().getAttachments().size() > 0) {
final Activity.PlusObject.Attachments attachment = activity.getObject().getAttachments().get(0);
switch(getItemViewType(i)) {
case 1:
// Article
populateArticle(container, attachment);
break;
case 2:
// Video
populateVideo(container, attachment);
break;
case 3:
// Photo
populatePhoto(container, attachment);
break;
case 4:
// Album
populateAlbum(container, attachment);
break;
case 5:
// Album
populateEvent(container, attachment);
break;
}
}
// That item will contain a special property that tells if it was freshly retrieved
if (!item.isConsumed()) {
item.setConsumed(true);
// In which case we magically instantiate our effect and launch it directly on the view
Animation animation = AnimationUtils.makeInChildBottomAnimation(mContext);
view.startAnimation(animation);
}
return view;
}
| public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null)
view = mInflater.inflate(R.layout.news_item_base, null);
Item item = (Item) getItemInternal(i);
final Activity activity = item.getActivity();
view.setTag(activity.getUrl());
ViewGroup container = (ViewGroup) view.findViewById(R.id.attachmentContainer);
PlusOneButton plusButton = (PlusOneButton) view.findViewById(R.id.plus_one_button);
if(mPlusClient != null && mPlusClient.isConnected()) {
plusButton.setVisibility(View.VISIBLE);
plusButton.initialize(mPlusClient, activity.getUrl(), 1);
} else {
plusButton.setVisibility(View.GONE);
}
/*ResizableImageView picture = (ResizableImageView) view.findViewById(R.id.image);
picture.setOnClickListener(null);
picture.setImageDrawable(null);*/
TextView timeStamp = (TextView) view.findViewById(R.id.timestamp);
if(activity.getPublished() != null) {
timeStamp.setVisibility(View.VISIBLE);
timeStamp.setText(Utils.toHumanTimePeriod(mContext,new DateTime(activity.getPublished().getValue()), DateTime.now()));
} else {
timeStamp.setVisibility(View.GONE);
}
if(activity.getVerb().equals("share"))
populateShare(activity, view);
else
populatePost(activity, view);
if(activity.getObject().getAttachments() != null && activity.getObject().getAttachments().size() > 0) {
final Activity.PlusObject.Attachments attachment = activity.getObject().getAttachments().get(0);
switch(getItemViewType(i)) {
case 1:
// Article
populateArticle(container, attachment);
break;
case 2:
// Video
populateVideo(container, attachment);
break;
case 3:
// Photo
populatePhoto(container, attachment);
break;
case 4:
// Album
populateAlbum(container, attachment);
break;
case 5:
// Album
populateEvent(container, attachment);
break;
}
}
// That item will contain a special property that tells if it was freshly retrieved
if (!item.isConsumed()) {
item.setConsumed(true);
// In which case we magically instantiate our effect and launch it directly on the view
Animation animation = AnimationUtils.makeInChildBottomAnimation(mContext);
view.startAnimation(animation);
}
return view;
}
|
diff --git a/src/main/java/org/telscenter/sail/webapp/presentation/web/controllers/teacher/RegisterTeacherController.java b/src/main/java/org/telscenter/sail/webapp/presentation/web/controllers/teacher/RegisterTeacherController.java
index 9fc9cfd..b9de755 100644
--- a/src/main/java/org/telscenter/sail/webapp/presentation/web/controllers/teacher/RegisterTeacherController.java
+++ b/src/main/java/org/telscenter/sail/webapp/presentation/web/controllers/teacher/RegisterTeacherController.java
@@ -1,163 +1,164 @@
/**
* Copyright (c) 2007 Regents of the University of California (Regents). Created
* by TELS, Graduate School of Education, University of California at Berkeley.
*
* This software is distributed under the GNU Lesser General Public License, v2.
*
* Permission is hereby granted, without written agreement and without license
* or royalty fees, to use, copy, modify, and distribute this software and its
* documentation for any purpose, provided that the above copyright notice and
* the following two paragraphs appear in all copies of this software.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE. THE SOFTWAREAND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
* HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
* MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
* SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.telscenter.sail.webapp.presentation.web.controllers.teacher;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.sail.webapp.domain.User;
import net.sf.sail.webapp.presentation.web.controllers.SignupController;
import net.sf.sail.webapp.service.authentication.DuplicateUsernameException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.telscenter.sail.webapp.domain.authentication.Curriculumsubjects;
import org.telscenter.sail.webapp.domain.authentication.Schoollevel;
import org.telscenter.sail.webapp.domain.authentication.impl.TeacherUserDetails;
import org.telscenter.sail.webapp.presentation.web.TeacherAccountForm;
/**
* Signup controller for TELS teacher user
*
* @author Hiroki Terashima
* @version $Id: RegisterTeacherController.java 1033 2007-09-08 00:05:01Z archana $
*/
public class RegisterTeacherController extends SignupController {
protected static final String USERNAME_KEY = "username";
protected static final String DISPLAYNAME_KEY = "displayname";
public RegisterTeacherController() {
setValidateOnBinding(false);
}
/**
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
*/
@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
return new TeacherAccountForm();
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
*/
@Override
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
model.put("schoollevels", Schoollevel.values());
model.put("curriculumsubjects",Curriculumsubjects.values());
return model;
}
/**
* On submission of the signup form, a user is created and saved to the data
* store.
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
String domain = "http://" + request.getServerName();
String domainWithPort = domain + ":" + request.getLocalPort();
String referrer = request.getHeader("referer");
String registerUrl = "/webapp/teacher/registerteacher.html";
String updateAccountInfoUrl = "/webapp/teacher/management/updatemyaccountinfo.html";
if(referrer.contains(domain + registerUrl) ||
referrer.contains(domainWithPort + registerUrl) ||
+ referrer.contains(domain + updateAccountInfoUrl) ||
referrer.contains(domainWithPort + updateAccountInfoUrl)){
TeacherAccountForm accountForm = (TeacherAccountForm) command;
TeacherUserDetails userDetails = (TeacherUserDetails) accountForm.getUserDetails();
if (accountForm.isNewAccount()) {
try {
userDetails.setDisplayname(userDetails.getFirstname() + " " + userDetails.getLastname());
userDetails.setEmailValid(true);
this.userService.createUser(userDetails);
}
catch (DuplicateUsernameException e) {
errors.rejectValue("username", "error.duplicate-username",
new Object[] { userDetails.getUsername() }, "Duplicate Username.");
return showForm(request, response, errors);
}
} else {
User user = userService.retrieveUserByUsername(userDetails.getUsername());
TeacherUserDetails teacherUserDetails = (TeacherUserDetails) user.getUserDetails();
teacherUserDetails.setCity(userDetails.getCity());
teacherUserDetails.setCountry(userDetails.getCountry());
teacherUserDetails.setCurriculumsubjects(userDetails.getCurriculumsubjects());
teacherUserDetails.setEmailAddress(userDetails.getEmailAddress());
teacherUserDetails.setSchoollevel(userDetails.getSchoollevel());
teacherUserDetails.setSchoolname(userDetails.getSchoolname());
teacherUserDetails.setState(userDetails.getState());
teacherUserDetails.setDisplayname(userDetails.getDisplayname());
teacherUserDetails.setEmailValid(true);
userService.updateUser(user);
// update user in session
request.getSession().setAttribute(
User.CURRENT_USER_SESSION_KEY, user);
}
ModelAndView modelAndView = new ModelAndView(getSuccessView());
modelAndView.addObject(USERNAME_KEY, userDetails.getUsername());
modelAndView.addObject(DISPLAYNAME_KEY, userDetails.getDisplayname());
return modelAndView;
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
}
/**
* @see org.springframework.web.servlet.mvc.BaseCommandController#onBindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.BindException)
*/
@Override
protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
throws Exception {
TeacherAccountForm accountForm = (TeacherAccountForm) command;
TeacherUserDetails userDetails = (TeacherUserDetails) accountForm.getUserDetails();
if (accountForm.isNewAccount()) {
userDetails.setSignupdate(Calendar.getInstance().getTime());
}
getValidator().validate(accountForm, errors);
}
}
| true | true | protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
String domain = "http://" + request.getServerName();
String domainWithPort = domain + ":" + request.getLocalPort();
String referrer = request.getHeader("referer");
String registerUrl = "/webapp/teacher/registerteacher.html";
String updateAccountInfoUrl = "/webapp/teacher/management/updatemyaccountinfo.html";
if(referrer.contains(domain + registerUrl) ||
referrer.contains(domainWithPort + registerUrl) ||
referrer.contains(domainWithPort + updateAccountInfoUrl)){
TeacherAccountForm accountForm = (TeacherAccountForm) command;
TeacherUserDetails userDetails = (TeacherUserDetails) accountForm.getUserDetails();
if (accountForm.isNewAccount()) {
try {
userDetails.setDisplayname(userDetails.getFirstname() + " " + userDetails.getLastname());
userDetails.setEmailValid(true);
this.userService.createUser(userDetails);
}
catch (DuplicateUsernameException e) {
errors.rejectValue("username", "error.duplicate-username",
new Object[] { userDetails.getUsername() }, "Duplicate Username.");
return showForm(request, response, errors);
}
} else {
User user = userService.retrieveUserByUsername(userDetails.getUsername());
TeacherUserDetails teacherUserDetails = (TeacherUserDetails) user.getUserDetails();
teacherUserDetails.setCity(userDetails.getCity());
teacherUserDetails.setCountry(userDetails.getCountry());
teacherUserDetails.setCurriculumsubjects(userDetails.getCurriculumsubjects());
teacherUserDetails.setEmailAddress(userDetails.getEmailAddress());
teacherUserDetails.setSchoollevel(userDetails.getSchoollevel());
teacherUserDetails.setSchoolname(userDetails.getSchoolname());
teacherUserDetails.setState(userDetails.getState());
teacherUserDetails.setDisplayname(userDetails.getDisplayname());
teacherUserDetails.setEmailValid(true);
userService.updateUser(user);
// update user in session
request.getSession().setAttribute(
User.CURRENT_USER_SESSION_KEY, user);
}
ModelAndView modelAndView = new ModelAndView(getSuccessView());
modelAndView.addObject(USERNAME_KEY, userDetails.getUsername());
modelAndView.addObject(DISPLAYNAME_KEY, userDetails.getDisplayname());
return modelAndView;
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
}
| protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
String domain = "http://" + request.getServerName();
String domainWithPort = domain + ":" + request.getLocalPort();
String referrer = request.getHeader("referer");
String registerUrl = "/webapp/teacher/registerteacher.html";
String updateAccountInfoUrl = "/webapp/teacher/management/updatemyaccountinfo.html";
if(referrer.contains(domain + registerUrl) ||
referrer.contains(domainWithPort + registerUrl) ||
referrer.contains(domain + updateAccountInfoUrl) ||
referrer.contains(domainWithPort + updateAccountInfoUrl)){
TeacherAccountForm accountForm = (TeacherAccountForm) command;
TeacherUserDetails userDetails = (TeacherUserDetails) accountForm.getUserDetails();
if (accountForm.isNewAccount()) {
try {
userDetails.setDisplayname(userDetails.getFirstname() + " " + userDetails.getLastname());
userDetails.setEmailValid(true);
this.userService.createUser(userDetails);
}
catch (DuplicateUsernameException e) {
errors.rejectValue("username", "error.duplicate-username",
new Object[] { userDetails.getUsername() }, "Duplicate Username.");
return showForm(request, response, errors);
}
} else {
User user = userService.retrieveUserByUsername(userDetails.getUsername());
TeacherUserDetails teacherUserDetails = (TeacherUserDetails) user.getUserDetails();
teacherUserDetails.setCity(userDetails.getCity());
teacherUserDetails.setCountry(userDetails.getCountry());
teacherUserDetails.setCurriculumsubjects(userDetails.getCurriculumsubjects());
teacherUserDetails.setEmailAddress(userDetails.getEmailAddress());
teacherUserDetails.setSchoollevel(userDetails.getSchoollevel());
teacherUserDetails.setSchoolname(userDetails.getSchoolname());
teacherUserDetails.setState(userDetails.getState());
teacherUserDetails.setDisplayname(userDetails.getDisplayname());
teacherUserDetails.setEmailValid(true);
userService.updateUser(user);
// update user in session
request.getSession().setAttribute(
User.CURRENT_USER_SESSION_KEY, user);
}
ModelAndView modelAndView = new ModelAndView(getSuccessView());
modelAndView.addObject(USERNAME_KEY, userDetails.getUsername());
modelAndView.addObject(DISPLAYNAME_KEY, userDetails.getDisplayname());
return modelAndView;
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
}
|
diff --git a/src/com/android/settings/LocationSettings.java b/src/com/android/settings/LocationSettings.java
index 645e6d772..0824aab0f 100644
--- a/src/com/android/settings/LocationSettings.java
+++ b/src/com/android/settings/LocationSettings.java
@@ -1,193 +1,192 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.content.ContentQueryMap;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.location.LocationManager;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import java.util.Observable;
import java.util.Observer;
/**
* Gesture lock pattern settings.
*/
public class LocationSettings extends SettingsPreferenceFragment
implements OnPreferenceChangeListener {
// Location Settings
private static final String KEY_LOCATION_NETWORK = "location_network";
private static final String KEY_LOCATION_GPS = "location_gps";
private static final String KEY_ASSISTED_GPS = "assisted_gps";
private static final String KEY_USE_LOCATION = "location_use_for_services";
private CheckBoxPreference mNetwork;
private CheckBoxPreference mGps;
private CheckBoxPreference mAssistedGps;
private CheckBoxPreference mUseLocation;
// These provide support for receiving notification when Location Manager settings change.
// This is necessary because the Network Location Provider can change settings
// if the user does not confirm enabling the provider.
private ContentQueryMap mContentQueryMap;
private Observer mSettingsObserver;
@Override
public void onStart() {
super.onStart();
// listen for Location Manager settings changes
Cursor settingsCursor = getContentResolver().query(Settings.Secure.CONTENT_URI, null,
"(" + Settings.System.NAME + "=?)",
new String[]{Settings.Secure.LOCATION_PROVIDERS_ALLOWED},
null);
mContentQueryMap = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, null);
}
@Override
public void onStop() {
super.onStop();
if (mSettingsObserver != null) {
mContentQueryMap.deleteObserver(mSettingsObserver);
}
}
private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.location_settings);
root = getPreferenceScreen();
mNetwork = (CheckBoxPreference) root.findPreference(KEY_LOCATION_NETWORK);
mGps = (CheckBoxPreference) root.findPreference(KEY_LOCATION_GPS);
mAssistedGps = (CheckBoxPreference) root.findPreference(KEY_ASSISTED_GPS);
if (GoogleLocationSettingHelper.isAvailable(getActivity())) {
// GSF present, Add setting for 'Use My Location'
CheckBoxPreference useLocation = new CheckBoxPreference(getActivity());
useLocation.setKey(KEY_USE_LOCATION);
useLocation.setTitle(R.string.use_location_title);
- useLocation.setSummaryOn(R.string.use_location_summary_enabled);
- useLocation.setSummaryOff(R.string.use_location_summary_disabled);
+ useLocation.setSummary(R.string.use_location_summary);
useLocation.setChecked(
GoogleLocationSettingHelper.getUseLocationForServices(getActivity())
== GoogleLocationSettingHelper.USE_LOCATION_FOR_SERVICES_ON);
useLocation.setPersistent(false);
useLocation.setOnPreferenceChangeListener(this);
getPreferenceScreen().addPreference(useLocation);
mUseLocation = useLocation;
}
// Change the summary for wifi-only devices
if (Utils.isWifiOnly()) {
mNetwork.setSummaryOn(R.string.location_neighborhood_level_wifi);
}
return root;
}
@Override
public void onResume() {
super.onResume();
// Make sure we reload the preference hierarchy since some of these settings
// depend on others...
createPreferenceHierarchy();
updateLocationToggles();
if (mSettingsObserver == null) {
mSettingsObserver = new Observer() {
public void update(Observable o, Object arg) {
updateLocationToggles();
}
};
mContentQueryMap.addObserver(mSettingsObserver);
}
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mNetwork) {
Settings.Secure.setLocationProviderEnabled(getContentResolver(),
LocationManager.NETWORK_PROVIDER, mNetwork.isChecked());
} else if (preference == mGps) {
boolean enabled = mGps.isChecked();
Settings.Secure.setLocationProviderEnabled(getContentResolver(),
LocationManager.GPS_PROVIDER, enabled);
if (mAssistedGps != null) {
mAssistedGps.setEnabled(enabled);
}
} else if (preference == mAssistedGps) {
Settings.Secure.putInt(getContentResolver(), Settings.Secure.ASSISTED_GPS_ENABLED,
mAssistedGps.isChecked() ? 1 : 0);
} else {
// If we didn't handle it, let preferences handle it.
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
return true;
}
/*
* Creates toggles for each available location provider
*/
private void updateLocationToggles() {
ContentResolver res = getContentResolver();
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
res, LocationManager.GPS_PROVIDER);
mNetwork.setChecked(Settings.Secure.isLocationProviderEnabled(
res, LocationManager.NETWORK_PROVIDER));
mGps.setChecked(gpsEnabled);
if (mAssistedGps != null) {
mAssistedGps.setChecked(Settings.Secure.getInt(res,
Settings.Secure.ASSISTED_GPS_ENABLED, 2) == 1);
mAssistedGps.setEnabled(gpsEnabled);
}
}
/**
* see confirmPatternThenDisableAndClear
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
createPreferenceHierarchy();
}
public boolean onPreferenceChange(Preference preference, Object value) {
if (preference == mUseLocation) {
boolean newValue = (value == null ? false : (Boolean) value);
GoogleLocationSettingHelper.setUseLocationForServices(getActivity(), newValue);
// We don't want to change the value immediately here, since the user may click
// disagree in the dialog that pops up. When the activity we just launched exits, this
// activity will be restated and the new value re-read, so the checkbox will get its
// new value then.
return false;
}
return true;
}
}
| true | true | private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.location_settings);
root = getPreferenceScreen();
mNetwork = (CheckBoxPreference) root.findPreference(KEY_LOCATION_NETWORK);
mGps = (CheckBoxPreference) root.findPreference(KEY_LOCATION_GPS);
mAssistedGps = (CheckBoxPreference) root.findPreference(KEY_ASSISTED_GPS);
if (GoogleLocationSettingHelper.isAvailable(getActivity())) {
// GSF present, Add setting for 'Use My Location'
CheckBoxPreference useLocation = new CheckBoxPreference(getActivity());
useLocation.setKey(KEY_USE_LOCATION);
useLocation.setTitle(R.string.use_location_title);
useLocation.setSummaryOn(R.string.use_location_summary_enabled);
useLocation.setSummaryOff(R.string.use_location_summary_disabled);
useLocation.setChecked(
GoogleLocationSettingHelper.getUseLocationForServices(getActivity())
== GoogleLocationSettingHelper.USE_LOCATION_FOR_SERVICES_ON);
useLocation.setPersistent(false);
useLocation.setOnPreferenceChangeListener(this);
getPreferenceScreen().addPreference(useLocation);
mUseLocation = useLocation;
}
// Change the summary for wifi-only devices
if (Utils.isWifiOnly()) {
mNetwork.setSummaryOn(R.string.location_neighborhood_level_wifi);
}
return root;
}
| private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.location_settings);
root = getPreferenceScreen();
mNetwork = (CheckBoxPreference) root.findPreference(KEY_LOCATION_NETWORK);
mGps = (CheckBoxPreference) root.findPreference(KEY_LOCATION_GPS);
mAssistedGps = (CheckBoxPreference) root.findPreference(KEY_ASSISTED_GPS);
if (GoogleLocationSettingHelper.isAvailable(getActivity())) {
// GSF present, Add setting for 'Use My Location'
CheckBoxPreference useLocation = new CheckBoxPreference(getActivity());
useLocation.setKey(KEY_USE_LOCATION);
useLocation.setTitle(R.string.use_location_title);
useLocation.setSummary(R.string.use_location_summary);
useLocation.setChecked(
GoogleLocationSettingHelper.getUseLocationForServices(getActivity())
== GoogleLocationSettingHelper.USE_LOCATION_FOR_SERVICES_ON);
useLocation.setPersistent(false);
useLocation.setOnPreferenceChangeListener(this);
getPreferenceScreen().addPreference(useLocation);
mUseLocation = useLocation;
}
// Change the summary for wifi-only devices
if (Utils.isWifiOnly()) {
mNetwork.setSummaryOn(R.string.location_neighborhood_level_wifi);
}
return root;
}
|
diff --git a/PaperFly/src/main/java/de/fhb/mi/paperfly/fragments/ChatFragment.java b/PaperFly/src/main/java/de/fhb/mi/paperfly/fragments/ChatFragment.java
index d44abcc..ae9c398 100644
--- a/PaperFly/src/main/java/de/fhb/mi/paperfly/fragments/ChatFragment.java
+++ b/PaperFly/src/main/java/de/fhb/mi/paperfly/fragments/ChatFragment.java
@@ -1,186 +1,183 @@
package de.fhb.mi.paperfly.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import de.fhb.mi.paperfly.PaperFlyApp;
import de.fhb.mi.paperfly.R;
import de.fhb.mi.paperfly.auth.AuthHelper;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketConnectionHandler;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketOptions;
import java.util.List;
/**
* @author Christoph Ott
*/
public class ChatFragment extends Fragment {
public static final String TAG = "ChatFragment";
public static final String ARG_CHAT_ROOM = "chat_room";
public static String ROOM_GLOBAL = "Global";
private final WebSocketConnection mConnection = new WebSocketConnection();
private View rootView;
private ListView messagesList;
private EditText messageInput;
private ImageButton buSend;
private ArrayAdapter<String> messagesAdapter;
private boolean globalRoom;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.rootView = inflater.inflate(R.layout.fragment_chat, container, false);
initViewsById();
String room = getArguments().getString(ARG_CHAT_ROOM);
if (room == ROOM_GLOBAL) {
globalRoom = true;
} else {
globalRoom = false;
}
messagesAdapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_list_item_1);
messageInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
buSend.setAlpha(1.0f);
buSend.setClickable(true);
} else {
buSend.setAlpha(0.5f);
buSend.setClickable(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
// make button not clickable
buSend.setAlpha(0.5f);
buSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = "{'text': '" + messageInput.getText().toString() + "'}";
- messagesAdapter.add(messageInput.getText().toString());
- messagesAdapter.notifyDataSetChanged();
-// ((PaperFlyApp)getActivity().getApplication()).getChatGlobal().add(messageInput.getText().toString());
mConnection.sendTextMessage(message);
messageInput.setText("");
}
});
buSend.setClickable(false);
// messagesList.setAdapter(messagesAdapter);
messagesList.setStackFromBottom(true);
messagesList.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
return rootView;
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart");
connectToWebsocket(AuthHelper.URL_CHAT_GLOBAL);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
mConnection.disconnect();
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop");
}
@Override
public void onDetach() {
super.onDetach();
Log.d(TAG, "onDetach");
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "onAttach");
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
List<String> chatList;
if (globalRoom) {
chatList = ((PaperFlyApp) getActivity().getApplication()).getChatGlobal();
} else {
chatList = ((PaperFlyApp) getActivity().getApplication()).getChatRoom();
}
messagesAdapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_list_item_1, chatList);
messagesList.setAdapter(messagesAdapter);
messageInput.requestFocus();
}
private void initViewsById() {
messagesList = (ListView) this.rootView.findViewById(R.id.messagesList);
messageInput = (EditText) this.rootView.findViewById(R.id.messageInput);
buSend = (ImageButton) this.rootView.findViewById(R.id.buSend);
}
private void connectToWebsocket(final String wsuri) {
WebSocketOptions asd = new WebSocketOptions();
try {
mConnection.connect(wsuri, new WebSocketConnectionHandler() {
@Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri);
}
@Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got payload: " + payload);
messagesAdapter.add(payload);
messagesAdapter.notifyDataSetChanged();
}
@Override
public void onClose(int code, String reason) {
Toast.makeText(rootView.getContext(), "Connection lost.", Toast.LENGTH_LONG).show();
Log.d(TAG, "Connection lost.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.rootView = inflater.inflate(R.layout.fragment_chat, container, false);
initViewsById();
String room = getArguments().getString(ARG_CHAT_ROOM);
if (room == ROOM_GLOBAL) {
globalRoom = true;
} else {
globalRoom = false;
}
messagesAdapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_list_item_1);
messageInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
buSend.setAlpha(1.0f);
buSend.setClickable(true);
} else {
buSend.setAlpha(0.5f);
buSend.setClickable(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
// make button not clickable
buSend.setAlpha(0.5f);
buSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = "{'text': '" + messageInput.getText().toString() + "'}";
messagesAdapter.add(messageInput.getText().toString());
messagesAdapter.notifyDataSetChanged();
// ((PaperFlyApp)getActivity().getApplication()).getChatGlobal().add(messageInput.getText().toString());
mConnection.sendTextMessage(message);
messageInput.setText("");
}
});
buSend.setClickable(false);
// messagesList.setAdapter(messagesAdapter);
messagesList.setStackFromBottom(true);
messagesList.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
return rootView;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.rootView = inflater.inflate(R.layout.fragment_chat, container, false);
initViewsById();
String room = getArguments().getString(ARG_CHAT_ROOM);
if (room == ROOM_GLOBAL) {
globalRoom = true;
} else {
globalRoom = false;
}
messagesAdapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_list_item_1);
messageInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
buSend.setAlpha(1.0f);
buSend.setClickable(true);
} else {
buSend.setAlpha(0.5f);
buSend.setClickable(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
// make button not clickable
buSend.setAlpha(0.5f);
buSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = "{'text': '" + messageInput.getText().toString() + "'}";
mConnection.sendTextMessage(message);
messageInput.setText("");
}
});
buSend.setClickable(false);
// messagesList.setAdapter(messagesAdapter);
messagesList.setStackFromBottom(true);
messagesList.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
return rootView;
}
|
diff --git a/uk.ac.diamond.scisoft.analysis.test/src/uk/ac/diamond/scisoft/analysis/dataset/InterpolatorUtilsTest.java b/uk.ac.diamond.scisoft.analysis.test/src/uk/ac/diamond/scisoft/analysis/dataset/InterpolatorUtilsTest.java
index 61e9055e4..1dfa14c49 100644
--- a/uk.ac.diamond.scisoft.analysis.test/src/uk/ac/diamond/scisoft/analysis/dataset/InterpolatorUtilsTest.java
+++ b/uk.ac.diamond.scisoft.analysis.test/src/uk/ac/diamond/scisoft/analysis/dataset/InterpolatorUtilsTest.java
@@ -1,48 +1,48 @@
/*-
* Copyright 2013 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.diamond.scisoft.analysis.dataset;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class InterpolatorUtilsTest {
@Test
public void test() {
AbstractDataset im = AbstractDataset.arange(0.0,10000.0,1.0, AbstractDataset.FLOAT32);
im = im.reshape(100,100);
AbstractDataset off = Maths.sin(AbstractDataset.arange(0.0, 10.0, 0.1,AbstractDataset.FLOAT32));
AbstractDataset axis = AbstractDataset.arange(-5.0, 5.0, 0.1, AbstractDataset.FLOAT32);
AbstractDataset newaxis = AbstractDataset.arange(-10.0, 10.0, 0.1, AbstractDataset.FLOAT32);
AbstractDataset output = InterpolatorUtils.remapOneAxis(im, 0, off, axis, newaxis);
// check that some values are correct
- assertEquals("Cooridinate Incorrect", 989.761, output.getDouble(62,29), 0.1);
- assertEquals("Cooridinate Incorrect", 8387.267, output.getDouble(127,56), 0.1);
+ assertEquals("Cooridinate Incorrect", 1468.249, output.getDouble(62,29), 0.1);
+ assertEquals("Cooridinate Incorrect", 7124.733, output.getDouble(127,56), 0.1);
assertEquals("Cooridinate Incorrect", Double.NaN, output.getDouble(179,33), 0.1);
- assertEquals("Cooridinate Incorrect", 9203.331, output.getDouble(144,2), 0.1);
- assertEquals("Cooridinate Incorrect", 346.186, output.getDouble(53,63), 0.1);
- assertEquals("Cooridinate Incorrect", 768.761, output.getDouble(54,97), 0.1);
- assertEquals("Cooridinate Incorrect", 7069.225, output.getDouble(120,94), 0.1);
+ assertEquals("Cooridinate Incorrect", 9600.669, output.getDouble(144,2), 0.1);
+ assertEquals("Cooridinate Incorrect", 379.814, output.getDouble(53,63), 0.1);
+ assertEquals("Cooridinate Incorrect", 225.239, output.getDouble(54,97), 0.1);
+ assertEquals("Cooridinate Incorrect", 7118.775, output.getDouble(120,94), 0.1);
}
}
| false | true | public void test() {
AbstractDataset im = AbstractDataset.arange(0.0,10000.0,1.0, AbstractDataset.FLOAT32);
im = im.reshape(100,100);
AbstractDataset off = Maths.sin(AbstractDataset.arange(0.0, 10.0, 0.1,AbstractDataset.FLOAT32));
AbstractDataset axis = AbstractDataset.arange(-5.0, 5.0, 0.1, AbstractDataset.FLOAT32);
AbstractDataset newaxis = AbstractDataset.arange(-10.0, 10.0, 0.1, AbstractDataset.FLOAT32);
AbstractDataset output = InterpolatorUtils.remapOneAxis(im, 0, off, axis, newaxis);
// check that some values are correct
assertEquals("Cooridinate Incorrect", 989.761, output.getDouble(62,29), 0.1);
assertEquals("Cooridinate Incorrect", 8387.267, output.getDouble(127,56), 0.1);
assertEquals("Cooridinate Incorrect", Double.NaN, output.getDouble(179,33), 0.1);
assertEquals("Cooridinate Incorrect", 9203.331, output.getDouble(144,2), 0.1);
assertEquals("Cooridinate Incorrect", 346.186, output.getDouble(53,63), 0.1);
assertEquals("Cooridinate Incorrect", 768.761, output.getDouble(54,97), 0.1);
assertEquals("Cooridinate Incorrect", 7069.225, output.getDouble(120,94), 0.1);
}
| public void test() {
AbstractDataset im = AbstractDataset.arange(0.0,10000.0,1.0, AbstractDataset.FLOAT32);
im = im.reshape(100,100);
AbstractDataset off = Maths.sin(AbstractDataset.arange(0.0, 10.0, 0.1,AbstractDataset.FLOAT32));
AbstractDataset axis = AbstractDataset.arange(-5.0, 5.0, 0.1, AbstractDataset.FLOAT32);
AbstractDataset newaxis = AbstractDataset.arange(-10.0, 10.0, 0.1, AbstractDataset.FLOAT32);
AbstractDataset output = InterpolatorUtils.remapOneAxis(im, 0, off, axis, newaxis);
// check that some values are correct
assertEquals("Cooridinate Incorrect", 1468.249, output.getDouble(62,29), 0.1);
assertEquals("Cooridinate Incorrect", 7124.733, output.getDouble(127,56), 0.1);
assertEquals("Cooridinate Incorrect", Double.NaN, output.getDouble(179,33), 0.1);
assertEquals("Cooridinate Incorrect", 9600.669, output.getDouble(144,2), 0.1);
assertEquals("Cooridinate Incorrect", 379.814, output.getDouble(53,63), 0.1);
assertEquals("Cooridinate Incorrect", 225.239, output.getDouble(54,97), 0.1);
assertEquals("Cooridinate Incorrect", 7118.775, output.getDouble(120,94), 0.1);
}
|
diff --git a/src/main/java/tconstruct/client/TProxyClient.java b/src/main/java/tconstruct/client/TProxyClient.java
index 332792af7..c6307bfb9 100644
--- a/src/main/java/tconstruct/client/TProxyClient.java
+++ b/src/main/java/tconstruct/client/TProxyClient.java
@@ -1,152 +1,152 @@
package tconstruct.client;
import java.io.InputStream;
import javax.xml.parsers.*;
import mantle.client.SmallFontRenderer;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.init.*;
import net.minecraft.item.ItemStack;
import net.minecraft.util.*;
import org.w3c.dom.Document;
import tconstruct.TConstruct;
import tconstruct.armor.ArmorProxyClient;
import tconstruct.armor.player.TPlayerStats;
import tconstruct.common.TProxyCommon;
import tconstruct.tools.items.ManualInfo;
public class TProxyClient extends TProxyCommon
{
/* TODO: Split this class up into its respective parts */
public static SmallFontRenderer smallFontRenderer;
public static IIcon metalBall;
public static Minecraft mc;
public static RenderItem itemRenderer = new RenderItem();
public void initialize ()
{
registerRenderer();
readManuals();
}
/* Registers any rendering code. */
public void registerRenderer ()
{
Minecraft mc = Minecraft.getMinecraft();
smallFontRenderer = new SmallFontRenderer(mc.gameSettings, new ResourceLocation("textures/font/ascii.png"), mc.renderEngine, false);
}
public static Document diary;
public static Document volume1;
public static Document volume2;
public static Document smelter;
public static ManualInfo manualData;
public void readManuals ()
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
String CurrentLanguage = Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getLanguageCode();
Document diary_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/diary.xml", dbFactory);
Document volume1_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/firstday.xml", dbFactory);
Document volume2_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/materials.xml", dbFactory);
Document smelter_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/smeltery.xml", dbFactory);
diary = readManual("/assets/tinker/manuals/en_US/diary.xml", dbFactory);
volume1 = readManual("/assets/tinker/manuals/en_US/firstday.xml", dbFactory);
volume2 = readManual("/assets/tinker/manuals/en_US/materials.xml", dbFactory);
smelter = readManual("/assets/tinker/manuals/en_US/smeltery.xml", dbFactory);
if(diary_cl != null)
{
diary = diary_cl;
}
if(volume1_cl != null)
{
volume1 = volume1_cl;
}
if(volume2_cl != null)
{
- volume2 = volume2_c1;
+ volume2 = volume2_cl;
}
if(smelter_cl != null)
{
smelter = smelter_cl;
}
initManualIcons();
initManualRecipes();
initManualPages();
manualData = new ManualInfo();
}
Document readManual (String location, DocumentBuilderFactory dbFactory)
{
try
{
InputStream stream = TConstruct.class.getResourceAsStream(location);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stream);
doc.getDocumentElement().normalize();
return doc;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public void initManualIcons ()
{
MantleClientRegistry.registerManualIcon("torch", new ItemStack(Blocks.torch));
MantleClientRegistry.registerManualIcon("sapling", new ItemStack(Blocks.sapling));
MantleClientRegistry.registerManualIcon("workbench", new ItemStack(Blocks.crafting_table));
MantleClientRegistry.registerManualIcon("coal", new ItemStack(Items.coal));
MantleClientRegistry.registerManualIcon("woodplanks", new ItemStack(Blocks.planks));
MantleClientRegistry.registerManualIcon("stoneblock", new ItemStack(Blocks.stone));
MantleClientRegistry.registerManualIcon("ironingot", new ItemStack(Items.iron_ingot));
MantleClientRegistry.registerManualIcon("flint", new ItemStack(Items.flint));
MantleClientRegistry.registerManualIcon("cactus", new ItemStack(Blocks.cactus));
MantleClientRegistry.registerManualIcon("bone", new ItemStack(Items.bone));
MantleClientRegistry.registerManualIcon("obsidian", new ItemStack(Blocks.obsidian));
MantleClientRegistry.registerManualIcon("netherrack", new ItemStack(Blocks.netherrack));
}
public void initManualRecipes ()
{
}
void initManualPages ()
{
}
public static Document getManualFromStack (ItemStack stack)
{
switch (stack.getItemDamage())
{
case 0:
return volume1;
case 1:
return volume2;
case 2:
return smelter;
case 3:
return diary;
}
return null;
}
public void recalculateHealth ()
{
ArmorProxyClient.armorExtended.recalculateHealth(mc.thePlayer, TPlayerStats.get(mc.thePlayer));
}
}
| true | true | public void readManuals ()
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
String CurrentLanguage = Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getLanguageCode();
Document diary_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/diary.xml", dbFactory);
Document volume1_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/firstday.xml", dbFactory);
Document volume2_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/materials.xml", dbFactory);
Document smelter_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/smeltery.xml", dbFactory);
diary = readManual("/assets/tinker/manuals/en_US/diary.xml", dbFactory);
volume1 = readManual("/assets/tinker/manuals/en_US/firstday.xml", dbFactory);
volume2 = readManual("/assets/tinker/manuals/en_US/materials.xml", dbFactory);
smelter = readManual("/assets/tinker/manuals/en_US/smeltery.xml", dbFactory);
if(diary_cl != null)
{
diary = diary_cl;
}
if(volume1_cl != null)
{
volume1 = volume1_cl;
}
if(volume2_cl != null)
{
volume2 = volume2_c1;
}
if(smelter_cl != null)
{
smelter = smelter_cl;
}
initManualIcons();
initManualRecipes();
initManualPages();
manualData = new ManualInfo();
}
| public void readManuals ()
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
String CurrentLanguage = Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getLanguageCode();
Document diary_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/diary.xml", dbFactory);
Document volume1_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/firstday.xml", dbFactory);
Document volume2_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/materials.xml", dbFactory);
Document smelter_cl = readManual("/assets/tinker/manuals/" + CurrentLanguage + "/smeltery.xml", dbFactory);
diary = readManual("/assets/tinker/manuals/en_US/diary.xml", dbFactory);
volume1 = readManual("/assets/tinker/manuals/en_US/firstday.xml", dbFactory);
volume2 = readManual("/assets/tinker/manuals/en_US/materials.xml", dbFactory);
smelter = readManual("/assets/tinker/manuals/en_US/smeltery.xml", dbFactory);
if(diary_cl != null)
{
diary = diary_cl;
}
if(volume1_cl != null)
{
volume1 = volume1_cl;
}
if(volume2_cl != null)
{
volume2 = volume2_cl;
}
if(smelter_cl != null)
{
smelter = smelter_cl;
}
initManualIcons();
initManualRecipes();
initManualPages();
manualData = new ManualInfo();
}
|
diff --git a/core/src/edu/trunk/wisc/ssec/mcidas/adde/AddeURLConnection.java b/core/src/edu/trunk/wisc/ssec/mcidas/adde/AddeURLConnection.java
index de7d0421a..81ff6880c 100644
--- a/core/src/edu/trunk/wisc/ssec/mcidas/adde/AddeURLConnection.java
+++ b/core/src/edu/trunk/wisc/ssec/mcidas/adde/AddeURLConnection.java
@@ -1,2173 +1,2173 @@
//
// AddeURLConnection.java
//
/*
The code in this file is Copyright(C) 1999 by Tommy Jasmin,
Don Murray, Tom Whittaker, James Kelly.
It is designed to be used with the VisAD system for
interactive analysis and visualization of numerical data.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package edu.wisc.ssec.mcidas.adde;
import java.io.DataInputStream;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import HTTPClient.UncompressInputStream;
/**
* This class extends URLConnection, providing the guts of the
* work to establish an ADDE network connection, put together
* a request packet, and initiate data flow. Connections for
* image data, image directories, grid data, grid directory,
* point source data and dataset information (McIDAS
* AGET, ADIR, GDIR, GGET, MDKS, TXTG and LWPR requests) are supported.
* @see <A HREF="http://www.ssec.wisc.edu/mug/prog_man/prog_man.html">
* McIDAS Programmer's Manual</A>
*
* <pre>
*
* URLs must all have the following format:
*
* adde://host/request?keyword_1=value_1&keyword_2=value_2
*
* where request can be one of the following:
*
* datasetinfo - request for data set information (LWPR)
* griddirectory - request for grid directory information (GDIR)
* griddata - request for grid data (GGET)
* imagedata - request for data in AreaFile format (AGET)
* imagedirectory - request for image directory information (ADIR)
* pointdata - request for point data (MDKS)
* textdata - request to read a text file (TXTG)
*
* There can be any valid combination of the following supported keywords:
*
* -------for any request
*
* group=<groupname> ADDE group name
* user=<user_id> ADDE user identification
* proj=<proj #> a valid ADDE project number
* trace=<0/1> setting to 1 tells server to write debug
* trace file (imagedata, imagedirectory)
* version= ADDE version number, currently 1 except for
* griddata requests
* debug= set to true to watch the printlns stream by
* compress= set to true if you want to use compressed
* transfers. You need to have the VisAD package
* if you want to support this.
* port= Socket port to connect on. Overridden by
* a port specified in the host
* (e.g., adde.ucar.edu:500)
*
* -------for images:
*
* descr=<descriptor> ADDE descriptor name
* band=<band> spectral band or channel number
* mag=<lmag> <emag> image magnification, postitive for blowup,
* negative for blowdown (default = 1, emag=lmag)
* (imagedata only)
* latlon=<lat> <lon> lat/lon point to center image on (imagedata only)
* linele=<lin> <ele> <type> line/element to center image on (imagedata only)
* place=<placement> placement of lat/lon or linele points (center
* or upperleft (def=center)) (imagedata only)
* pos=<position> request an absolute or relative ADDE position
* number. May use <start> <end>. Default
* for <end> is 0 if start<0, or =start otherwise.
* size=<lines> <elements> size of image to be returned (imagedata only)
* unit=<unit> to specify calibration units other than the
* default
* spac=<bytes> number of bytes per data point, 1, 2, or 4
* (imagedata only)
* doc=<yes/no> specify yes to include line documentation
* with image (def=no)
* aux=<yes/no> specify yes to include auxilliary information
* with image
* time=<time1> <time2> specify the time range of images to select
* (def=latest image if pos not specified)
* day=<day> specify the day of the images to select
* (def=latest image if pos not specified)
* cal=<cal type> request a specific calibration on the image
* (imagedata only)
* id=<stn id> radar station id
*
* ------ for grids:
*
* descr=<descriptor> ADDE descriptor name
* param=<param list> parameter code list
* time=<model run time> time in hhmmss format
* day=<model run day> day in ccyyddd format
* lev=<level list> list of requested levels (value or SFC, MSL
* or TRO)
* ftime=<forecast time> valid time (hhmmss format) (use with fday)
* fday=<forecast day> forecast day (ccyyddd)
* fhour=<forecast hours> forecast hours (offset from model run time)
* (hhmmss format)
* num=<max> maximum number of grids to return (nn)
*
* ------ for point data:
*
* descr=<descriptor> ADDE descriptor name
* pos=<position> request an absolute or relative ADDE
* position number
* select=<select clause> to specify which data is required
* param=<param list> what parameters to return
* num=<max> maximum number of obs to return
*
* ------ for text data:
*
* descr=<descriptor> ADDE descriptor name
* (may also be "descr=FILE=filename")
* file=<filename> name of text file to read
*
*
* The following keywords are required:
*
* group
* descr (except datasetinfo)
*
* an example URL for images might look like:
*
* adde://viper/imagedata?group=gvar&band=1&user=tjj&proj=6999&version=1
*
* </pre>
*
* @author Tommy Jasmin, University of Wisconsin, SSEC
* @author Don Murray, UCAR/Unidata
* @author Tom Whittaker, SSEC/CIMSS
* @author James Kelly, Australian Bureau of Meteorology
*/
public class AddeURLConnection extends URLConnection
{
private InputStream is = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private URL url;
private final static int DEFAULT_LINES = 480;
private final static int DEFAULT_ELEMS = 640;
private final static int TRAILER_SIZE = 92;
private final static int REQUEST_SIZE = 120;
private final static int ERRMSG_SIZE = 72;
private final static int ERRMSG_OFFS = 8;
private final static int PORT = 500;
private final static int COMPRESS = 503;
private final static int GZIP = 112;
private final static int VERSION_1 = 1;
// ADDE server requests
/** AGET request type */
public final static int AGET = 0;
/** ADIR request type */
public final static int ADIR = 1;
/** LWPR request type */
public final static int LWPR = 2;
/** GDIR request type */
public final static int GDIR = 3;
/** GGET request type */
public final static int GGET = 4;
/** MDKS request type */
public final static int MDKS = 5;
/** TXTG request type */
public final static int TXTG = 6;
/** WTXG request type */
public final static int WTXG = 7;
/** OBTG request type */
public final static int OBTG = 8;
// ADDE data types
private final static int IMAGE = 100;
private final static int GRID = 101;
private final static int POINT = 102;
private final static int TEXT = 103;
private final static int WXTEXT = 104;
private final static int OBTEXT = 105;
private int numBytes = 0;
private int dataType = IMAGE;
private byte[] binaryData = null; // byte array to hold extra binary data
private int reqType = AGET;
private boolean debug = false;
private int portToUse = PORT; // DRM 03-Mar-2001
private int compressionType = PORT;
/**
*
* Constructor: just sets URL and calls superclass constructor.
* Actual network connection is established in connect().
*
*/
AddeURLConnection(URL url)
throws IOException
{
super(url);
this.url = normalizeURL(url);
}
/**
*
* Establishes an ADDE connection using the URL passed to the
* constructor. Opens a socket on the ADDE port, and formulates
* an ADDE image data request based on the file portion of URL.
*
* an example URL might look like:
* adde://viper.ssec.wisc.edu/image?group=gvar&band=1&mag=-8&version=1
*
*/
synchronized public void connect ()
throws IOException, AddeURLException
{
// First, see if we can use the URL passed in
// verify the service is one we can handle
// get rid of leading /
// keep original to preserve case for user= clause
String requestOriginal = url.getFile().substring(1);
String request = requestOriginal.toLowerCase();
debug = debug || request.indexOf("debug=true") >= 0;
if (debug) System.out.println("host from URL: " + url.getHost());
if (debug) System.out.println("file from URL: " + url.getFile());
if (!request.startsWith("image") &&
(!request.startsWith("datasetinfo")) &&
(!request.startsWith("text")) &&
(!request.startsWith("wxtext")) &&
(!request.startsWith("obtext")) &&
(!request.startsWith("grid")) &&
(!request.startsWith("point")) )
{
throw new AddeURLException("Request for unknown data");
}
// service - for area files, it's either AGET (Area GET) or
// ADIR (AREA directory)
byte [] svc = null;
if (request.startsWith("imagedir"))
{
svc = "adir".getBytes();
reqType = ADIR;
}
else if (request.startsWith("datasetinfo"))
{
svc = "lwpr".getBytes();
reqType = LWPR;
}
else if (request.startsWith("text"))
{
svc = "txtg".getBytes();
reqType = TXTG;
}
else if (request.startsWith("wxtext"))
{
svc = "wtxg".getBytes();
reqType = WTXG;
}
else if (request.startsWith("obtext"))
{
svc = "obtg".getBytes();
reqType = OBTG;
}
else if (request.startsWith("image"))
{
svc = "aget".getBytes();
reqType = AGET;
}
else if (request.startsWith("griddir"))
{
svc = "gdir".getBytes();
reqType = GDIR;
}
else if (request.startsWith("grid"))
{
svc = "gget".getBytes();
reqType = GGET;
}
else if (request.startsWith("point"))
{
svc = "mdks".getBytes();
reqType = MDKS;
}
else
{
throw new AddeURLException(
"Invalid or unsupported ADDE service= "+svc.toString() );
}
if (debug) System.out.println("Service = " + new String(svc));
// prep for real thing - get cmd from file part of URL
int test = request.indexOf("?");
String uCmd = (test >=0) ? request.substring(test+1) : request;
if (debug) System.out.println("uCmd="+uCmd);
// build the command string
StringBuffer sb = new StringBuffer();
switch (reqType)
{
case AGET:
sb = decodeAGETString(uCmd);
break;
case ADIR:
sb = decodeADIRString(uCmd);
break;
case LWPR:
sb = decodeLWPRString(uCmd);
break;
case GDIR:
sb = decodeGDIRString(uCmd);
break;
case GGET:
sb = decodeGDIRString(uCmd);
break;
case MDKS:
sb = decodeMDKSString(uCmd);
break;
case TXTG:
sb = decodeTXTGString(uCmd);
break;
case WTXG:
sb = decodeWTXGString(uCmd);
break;
case OBTG:
sb = decodeOBTGString(uCmd);
break;
}
// indefinitely use ADDE version 1 unless it's a GGET request
sb.append(" version=");
sb.append((reqType == GGET || reqType == WTXG) ? "A" : "1");
// now convert to array of bytes for output since chars are two byte
String cmd = new String(sb);
cmd = cmd.toUpperCase();
if (debug) System.out.println(cmd);
byte [] ob = cmd.getBytes();
// get some other stuff
int startIdx;
int endIdx;
// user initials - pass on what client supplied in user= keyword
byte [] usr;
String userStr;
startIdx = request.indexOf("user=");
- if (startIdx > 0) {
+ if (startIdx >= 0) {
endIdx = request.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = request.length();
// use original to preserve case
userStr = requestOriginal.substring(startIdx + 5, endIdx);
} else {
userStr = "XXXX";
}
usr = userStr.getBytes();
// project number - we won't validate, but make sure it's there
startIdx = uCmd.indexOf("proj=");
String projStr;
int proj;
- if (startIdx > 0) {
+ if (startIdx >= 0) {
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
projStr = uCmd.substring(startIdx + 5, endIdx);
} else {
projStr = "0";
}
try {
proj = Integer.parseInt(projStr);
} catch (NumberFormatException e) {
throw new AddeURLException("Invalid project number: " + projStr);
}
// compression
startIdx = uCmd.indexOf("compress=");
String compType = "";
- if (startIdx > 0) {
+ if (startIdx >= 0) {
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
compType = uCmd.substring(startIdx + 9, endIdx);
}
if (compType.equalsIgnoreCase("gzip")) {
compressionType = GZIP;
} else if (compType.equalsIgnoreCase("compress") ||
compType.equalsIgnoreCase("true")) {
// check to see if we can do uncompression
try {
Class c = Class.forName("HTTPClient.UncompressInputStream");
compressionType = COMPRESS;
} catch (ClassNotFoundException cnfe) {
System.err.println(
"Uncompression code not found, turning compression off");
}
}
// end of request decoding
//-------------------------------------------------------------------------
// now write this all to the port
// first figure out which port to connect on. This can either be
// one specified by the user.
//
// The priority is URL port, port=keyword, compression port (default)
if (url.getPort() == -1) { // not specified as part of URL
// see if there is a port=keyword
// default to the compression type
portToUse = compressionType;
startIdx = uCmd.indexOf("port=");
- if (startIdx > 0) {
+ if (startIdx >= 0) {
String portStr;
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
portStr = uCmd.substring(startIdx + 5, endIdx);
try {
portToUse = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
throw new AddeURLException("Invalid port number: " + portStr);
}
}
} else { // specified
portToUse = url.getPort();
}
if (debug) {
System.out.println("connecting on port " + portToUse + " using " +
(compressionType == GZIP
? "gzip"
: compressionType == COMPRESS
? "compress"
: "no") + " compression.");
}
Socket t;
try {
t = new Socket(url.getHost(), portToUse); // DRM 03-Mar-2001
} catch (UnknownHostException e) {
throw new AddeURLException(e.toString());
}
dos = new DataOutputStream ( t.getOutputStream() );
/*
Now start pumping data to the server. The sequence is:
- ADDE version (1 for now)
- Server IP and Port number (latter used to determine compression)
- Service Type (AGET, ADIR, etc)
- Server IP and Port number (again)
- Client address
- User, project, password
- Service Type (again)
- Actual request
*/
// send version number - ADDE seems to be stuck at 1
dos.writeInt(VERSION_1);
// send IP address of server
// we know the server IP address is good cause we used it above
byte [] ipa = new byte[4];
InetAddress ia = InetAddress.getByName(url.getHost());
ipa = ia.getAddress();
dos.write(ipa, 0, ipa.length);
// send ADDE port number which server uses to determine compression
dos.writeInt(compressionType);
// send the service type
dos.write(svc, 0, svc.length);
// now build and send request block, repeat some stuff
// server IP address, port
dos.write(ipa, 0, ipa.length);
dos.writeInt(compressionType); // DRM 03-Mar-2001
// client IP address
InetAddress lh = InetAddress.getLocalHost();
ipa = lh.getAddress();
dos.write(ipa, 0, ipa.length);
// gotta send 4 user bytes, ADDE protocol expects it
if (usr.length <= 4) {
dos.write(usr, 0, usr.length);
for (int i = 0; i < 4 - usr.length; i++) {
dos.writeByte(' ');
}
} else {
// if id entered was > 4 chars, complain
throw new AddeURLException("Invalid user id: " + userStr);
}
dos.writeInt(proj);
// password chars - not used either
byte [] pwd = new byte[12];
dos.write(pwd, 0, pwd.length);
// service - resend svc array
dos.write(svc, 0, svc.length);
// Write out the data. There are 2 cases:
//
// 1) ob.length <= 120
// 2) ob.length > 120
//
// In either case, there may or may not be additional binary data
//
int numBinaryBytes = 0;
if (binaryData != null) numBinaryBytes = binaryData.length;
if (ob.length > REQUEST_SIZE)
{
dos.writeInt(ob.length + numBinaryBytes); // number of additional bytes
dos.writeInt(ob.length); // number of bytes in request
for (int i=0; i < REQUEST_SIZE - 4; i++) { // - 4 accounts for prev line
dos.writeByte(0);
}
dos.write(ob,0,ob.length);
} else {
if (debug) System.out.println("numBinaryBytes= " + numBinaryBytes);
dos.writeInt(numBinaryBytes);
dos.write(ob, 0, ob.length);
for (int i=0; i < REQUEST_SIZE - ob.length; i++) {
dos.writeByte(' ');
}
}
if (numBinaryBytes > 0) dos.write(binaryData, 0, numBinaryBytes);
is = (compressionType == GZIP)
? new GZIPInputStream(t.getInputStream())
: (compressionType == COMPRESS)
? new UncompressInputStream(t.getInputStream())
: t.getInputStream();
dis = new DataInputStream(is);
if (debug && (compressionType != portToUse) ) {
System.out.println("Compression is turned ON using " +
((compressionType == GZIP)?"GZIP":"compress"));
}
// get response from server, byte count coming back
numBytes = dis.readInt();
if (debug) System.out.println("server is sending: " + numBytes + " bytes");
// if server returns zero, there was an error so read trailer and exit
if (numBytes == 0) {
byte [] trailer = new byte[TRAILER_SIZE];
dis.readFully(trailer, 0, trailer.length);
String errMsg = new String(trailer, ERRMSG_OFFS, ERRMSG_SIZE);
throw new AddeURLException(errMsg);
}
// if we made it to here, we're getting data
connected = true;
}
/**
* Get the request type
* @return type of request (ADIR, AGET, etc)
*/
public int getRequestType()
{
return reqType;
}
/**
* returns a reference to InputStream established in connect().
* calls connect() if client has not done so yet.
*
* @return InputStream reference
*/
synchronized public InputStream getInputStream ()
throws IOException
{
if (!connected) connect();
return is;
}
/**
*
* returns a reference to DataInputStream established in connect().
* calls connect() if client has not done so yet.
*
* @return DataInputStream reference
*/
synchronized public DataInputStream getDataInputStream ()
throws IOException
{
if (!connected) connect();
return dis;
}
/**
* Return the number of bytes being sent by the server for the
* first record.
*
* @return number of bytes send in the first record
*/
public int getInitialRecordSize()
{
return numBytes;
}
/**
* Decode the ADDE request for image data.
*
* there can be any valid combination of the following supported keywords:
*
* group=<groupname> ADDE group name
* descr=<descriptor> ADDE descriptor name
* band=<band> spectral band or channel number
* mag=<lmag> <emag> image magnification, postitive for blowup,
* negative for blowdown (default = 1,
* emag=lmag)
* latlon=<lat> <lon> lat/lon point to center image on
* linele=<lin> <ele> <type> line/element to center image on
* place=<placement> placement of lat/lon or linele points
* (center or upperleft (def=center))
* pos=<position> request an absolute or relative ADDE position
* number
* size=<lines> <elements> size of image to be returned
* unit=<unit> to specify calibration units other than the
* default
* spac=<bytes> number of bytes per data point, 1, 2, or 4
* doc=<yes/no> specify yes to include line documentation
* with image (def=no)
* aux=<yes/no> specify yes to include auxilliary information
* with image
* time=<time1> <time2> specify the time range of images to select
* (def=latest image if pos not specified)
* day=<day> specify the day of the images to select
* (def=latest image if pos not specified)
* cal=<cal type> request a specific calibration on the image
* id=<stn id> radar station id
* user=<user_id> ADDE user identification
* proj=<proj #> a valid ADDE project number
* trace=<0/1> setting to 1 tells server to write debug
* trace file (imagedata, imagedirectory)
*
* the following keywords are required:
*
* group
*
* an example URL might look like:
* adde://viper/imagedata?group=gvar&band=1&user=tjj&proj=6999
*
* </pre>
*/
private StringBuffer decodeAGETString(String uCmd)
{
StringBuffer buf = new StringBuffer();
boolean latFlag = false;
boolean lonFlag = false;
boolean linFlag = false;
boolean eleFlag = false;
String latString = null;
String lonString = null;
String linString = null;
String eleString = null;
String tempString = null;
String testString = null;
// Mandatory strings
String groupString = null;
String descrString = "all";
String posString = "0";
String numlinString = Integer.toString(DEFAULT_LINES);
String numeleString = Integer.toString(DEFAULT_ELEMS);
String magString = "x";
String traceString = "trace=0";
String spaceString = "spac=x";
String unitString = "unit=brit";
String auxString = "aux=yes";
String calString = "cal=x";
String docString = "doc=no";
String timeString = "time=x x i";
String lineleType = "a";
String placement = "c";
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
// group, descr and pos are mandatory
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("des"))
{
descrString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("pos"))
{
posString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("lat")) // lat or latlon
{
latString =
testString.substring(testString.indexOf("=") + 1).trim();
latFlag = true;
if (latString.indexOf(" ") > 0) // is latlon, not just lat
{
StringTokenizer tok = new StringTokenizer(latString);
if (tok.countTokens() < 2) break;
for (int i = 0; i < 2; i++)
{
tempString = tok.nextToken();
if (i == 0)
latString = tempString;
else
{
lonString = negateLongitude(tempString);
lonFlag = true;
}
}
}
}
else
if (testString.startsWith("lon"))
{
lonFlag = true;
lonString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("lin")) // line keyword or linele
{
tempString =
testString.substring(testString.indexOf("=") + 1);
if (tempString.indexOf(" ") > 0) // is linele, not just lin
{
StringTokenizer tok = new StringTokenizer(tempString);
if (tok.countTokens() < 2) break;
for (int i = 0; i < 2; i++)
{
tempString = tok.nextToken();
if (i == 0)
{
linString = tempString;
linFlag = true;
}
else
{
eleString = tempString;
eleFlag = true;
}
}
if (tok.hasMoreTokens()) // specified file or image coords
{
tempString = tok.nextToken().toLowerCase();
if (tempString.startsWith("i")) lineleType = "i";
}
}
else // is just lines string
{
numlinString = tempString;
}
}
else
if (testString.startsWith("ele")) // elements keyword
{
numeleString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("pla")) // placement keyword
{
if (testString.substring(
testString.indexOf("=") + 1).toLowerCase().startsWith("u"))
placement = "u";
}
else
if (testString.startsWith("mag"))
{
tempString =
testString.substring(testString.indexOf("=") + 1);
if (tempString.indexOf(" ") > 0) // is more than one mag
{
StringTokenizer tok = new StringTokenizer(tempString);
if (tok.countTokens() < 2) break;
for (int i = 0; i < 2; i++)
{
buf.append(" ");
tempString = tok.nextToken();
if (i == 0)
buf.append("lmag=" + tempString);
else
buf.append("emag=" + tempString);
}
}
else
magString = tempString;
}
// now get the rest of the keywords (but filter out non-needed)
else
if (testString.startsWith("size")) // size keyword
{
tempString =
testString.substring(testString.indexOf("=") + 1);
if (tempString.trim().equalsIgnoreCase("all")) {
numlinString = "99999";
numeleString = "99999";
}
else if (tempString.indexOf(" ") > 0) //is linele, not just lin
{
StringTokenizer tok = new StringTokenizer(tempString);
if (tok.countTokens() < 2) break;
for (int i = 0; i < 2; i++)
{
tempString = tok.nextToken();
if (i == 0)
numlinString = tempString;
else
numeleString = tempString;
}
}
}
else
if (testString.startsWith("tra")) // trace keyword
{
traceString = testString;
}
else
if (testString.startsWith("spa")) // aux keyword
{
spaceString = testString;
}
else
if (testString.startsWith("aux")) // aux keyword
{
auxString = testString;
}
else
if (testString.startsWith("uni")) // unit keyword
{
unitString = testString;
}
else
if (testString.startsWith("cal")) // cal keyword
{
calString = testString;
}
else
if (testString.startsWith("doc")) // doc keyword
{
docString = testString;
}
else
if (testString.startsWith("tim")) // time keyword
{
timeString = testString;
}
else
if (testString.startsWith("ban")) // band keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("day")) // day keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("id")) // id keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("lmag")) // lmag keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("emag")) // emag keyword
{
buf.append(" ");
buf.append(testString);
}
}
buf.append(" ");
buf.append(traceString);
buf.append(" ");
buf.append(spaceString);
buf.append(" ");
buf.append(unitString);
buf.append(" ");
buf.append(auxString);
buf.append(" ");
buf.append(docString);
buf.append(" ");
buf.append(timeString);
buf.append(" ");
buf.append(calString);
// now create command string
StringBuffer posParams =
new StringBuffer(
groupString + " " + descrString + " " + posString + " ");
// Set up location information
if (latFlag && lonFlag)
posParams.append("ec " + latString + " " + lonString + " ");
else if (linFlag && eleFlag)
posParams.append(lineleType + placement +" " +
linString + " " + eleString + " ");
else
posParams.append("x x x ");
// add on the mag, lin and ele pos params
posParams.append(magString + " " + numlinString +
" " + numeleString + " ");
// stuff it in at the beginning
try
{
buf.insert(0, posParams);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(e.toString());
buf = new StringBuffer("");
}
return buf;
}
/**
* Decode the ADDE request for grid directory information.
*
*
* there can be any valid combination of the following supported keywords:
*
* group=<groupname> ADDE group name
* descr=<descriptor> ADDE descriptor name
* param=<param list> parameter code list
* time=<model run time> time in hhmmss format
* day=<model run day> day in ccyyddd format
* lev=<level list> list of requested levels (value or SFC, MSL
* or TRO)
* ftime=<forecast time> valid time (hhmmss format) (use with fday)
* fday=<forecast day> forecast day (ccyyddd)
* fhour=<forecast hours> forecast hours (offset from model run time)
* (hhmmss format)
* lat=<min lat> <max lat> latitude bounding box (needs lon specified)
* lon=<min lon> <max lon> longitude bounding box (needs lat specified)
* row=<min row> <max row> row bounding box (needs col specified)
* col=<min col> <max col> column bounding box (needs row specified)
* skip=<row> <col> skip factors for rows and columns (def = 1 1)
* num=<max> maximum number of grids (nn) to return (def=1)
* user=<user_id> ADDE user identification
* proj=<proj #> a valid ADDE project number
* trace=<0/1> setting to 1 tells server to write debug
* trace file (imagedata, imagedirectory)
*
* the following keywords are required:
*
* group
*
* an example URL might look like:
* adde://noaaport/griddirectory?group=ngm&num=10
*
* </pre>
*/
private StringBuffer decodeGDIRString(String uCmd) {
StringBuffer buf = new StringBuffer();
String testString, tempString;
String groupString = null;
String descrString = "all";
String sizeString = " 999999 ";
String traceString = "trace=0";
String numString = "num=1";
String subsetString = null;
String latString = null;
String lonString = null;
String rowString = null;
String colString = null;
String srcString = null;
String skip = null;
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens()) {
testString = cmdTokens.nextToken();
// group, descr and pos are mandatory
if (testString.startsWith("grou")) {
groupString =
testString.substring(testString.indexOf("=") + 1);
} else if (testString.startsWith("des")) {
descrString =
testString.substring(testString.indexOf("=") + 1);
// now get the rest of the keywords (but filter out non-needed)
} else if (testString.startsWith("num")) {
numString = testString;
} else if (testString.startsWith("tra")) { // trace keyword
traceString = testString;
} else if (testString.startsWith("pos")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("par")) {
buf.append(" ");
buf.append("parm=");
buf.append(testString.substring(testString.indexOf("=") + 1));
} else if (testString.startsWith("fho")) {
buf.append(" ");
buf.append("vt=");
String iHMS =
testString.substring(testString.indexOf("=") + 1).trim();
buf.append(iHMS);
if (iHMS.length() < 5) buf.append("0000");
} else if (testString.startsWith("day")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("time")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("lev")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("fday")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("ftime")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("vt")) { // deprecated
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("lat")) {
latString =
ensureTwoValues(
testString.substring(testString.indexOf("=") + 1));
} else if (testString.startsWith("lon")) {
lonString =
adjustLongitudes(
ensureTwoValues(
testString.substring(testString.indexOf("=") + 1)));
} else if (testString.startsWith("row")) {
rowString =
ensureTwoValues(
testString.substring(testString.indexOf("=") + 1));
} else if (testString.startsWith("col")) {
colString =
ensureTwoValues(
testString.substring(testString.indexOf("=") + 1));
} else if (testString.startsWith("skip")) {
skip =
ensureTwoValues(
testString.substring(testString.indexOf("=") + 1));
// added with great pains for James DRM 2001-07-05 ;-)
} else if (testString.startsWith("src")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("gpro")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("trang")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("frang")) {
buf.append(" ");
buf.append(testString);
} else if (testString.startsWith("drang")) {
buf.append(" ");
buf.append(testString);
/*
} else {
System.out.println("Unknown token = "+testString);
*/
}
}
buf.append(" ");
buf.append(numString);
buf.append(" ");
buf.append(traceString);
buf.append(" ");
//buf.append(" version=A ");
// Create a subset string
if (latString != null && lonString != null)
{
StringBuffer subBuf = new StringBuffer();
subBuf.append("subset=");
subBuf.append(latString);
subBuf.append(" ");
subBuf.append(lonString);
subBuf.append(" ");
subBuf.append((skip == null) ? "1 1" : skip);
subBuf.append(" LATLON");
subsetString = subBuf.toString();
if (debug) System.out.println(subsetString);
}
else if (rowString != null && colString != null)
{
StringBuffer subBuf = new StringBuffer();
subBuf.append("subset=");
subBuf.append(rowString);
subBuf.append(" ");
subBuf.append(colString);
subBuf.append(" ");
subBuf.append((skip == null) ? "1 1" : skip);
subBuf.append(" ROWCOL");
subsetString = subBuf.toString();
if (debug) System.out.println(subsetString);
}
else if (skip != null) { // only skip specified
StringBuffer subBuf = new StringBuffer();
subBuf.append("subset=1 99999 1 99999");
subBuf.append(" ");
subBuf.append(skip);
subBuf.append(" ROWCOL");
subsetString = subBuf.toString();
if (debug) System.out.println(subsetString);
}
if (subsetString != null) buf.append(subsetString);
// create command string
String posParams = //new String (
groupString + " " + descrString + " " + sizeString + " " ;//);
try {
buf.insert(0,posParams);
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e);
buf = new StringBuffer("");
}
return buf;
}
/**
* Decode the ADDE request for image directory information.
*
* <pre>
* there can be any valid combination of the following supported keywords:
*
* group=<groupname> ADDE group name
* descr=<descriptor> ADDE descriptor name
* band=<band> spectral band or channel number
* pos=<position> request an absolute or relative ADDE position
* number
* doc=<yes/no> specify yes to include line documentation
* with image (def=no)
* aux=<yes/no> specify yes to include auxilliary information
* with image
* time=<time1> <time2> specify the time range of images to select
* (def=latest image if pos not specified)
* day=<day> specify the day of the images to select
* (def=latest image if pos not specified)
* cal=<cal type> request a specific calibration on the image
* id=<stn id> radar station id
* user=<user_id> ADDE user identification
* proj=<proj #> a valid ADDE project number
* trace=<0/1> setting to 1 tells server to write debug
* trace file (imagedata, imagedirectory)
*
* the following keywords are required:
*
* group
*
* an example URL might look like:
* adde://viper/imagedirectory?group=gvar&descr=east1km&band=1
*
* </pre>
*/
private StringBuffer decodeADIRString(String uCmd)
{
StringBuffer buf = new StringBuffer();
String testString;
String tempString;
// Mandatory strings
String groupString = null;
String descrString = "all";
String posString = "0";
String traceString = "trace=0";
String bandString = "band=all x";
String auxString = "aux=yes";
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
// group, descr and pos are mandatory
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("des"))
{
descrString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("pos"))
{
tempString =
testString.substring(testString.indexOf("=") + 1);
if (tempString.equals("")) { // null string
posString = "0";
} else {
// see if a single argument
StringTokenizer stp = new StringTokenizer(tempString," ");
if (stp.countTokens() == 1) {
if (tempString.equals("all")) { // put in numeric
posString = "1095519264";
} else if (tempString.equals("x")) {
posString = tempString;
} else {
int posval = Integer.parseInt(stp.nextToken().trim());
if (posval < 0) { // if value < 0 insert 0 as ending
posString = tempString + " 0";
} else {
posString = tempString; // else default
}
}
} else { // more than one value...just copy it
posString = tempString;
}
}
}
// now get the rest of the keywords (but filter out non-needed)
else
if (testString.startsWith("tra")) // trace keyword
{
traceString = testString;
}
else
if (testString.startsWith("aux")) // aux keyword
{
auxString = testString;
}
else
if (testString.startsWith("ban")) // band keyword
{
bandString = testString;
}
else
if (testString.startsWith("tim")) // time keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("day")) // time keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("id")) // id keyword
{
buf.append(" ");
buf.append(testString);
}
}
buf.append(" ");
buf.append(traceString);
buf.append(" ");
buf.append(bandString);
buf.append(" ");
buf.append(auxString);
// now create command string
String posParams =
//new String(
groupString + " " + descrString + " " + posString + " ";//);
try
{
buf.insert(0, posParams);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(e.toString());
buf = new StringBuffer("");
}
return buf;
}
/**
* Decode the ADDE request for a text file.
*
* <pre>
* there can be any valid combination of the following supported keywords:
*
* file=<filename> the text file name on the server
* descr=<dataset> the dataset name on the server
* group=<group> the ADDE group name for this TEXT
*
* the following keywords are required:
*
* file or descr
*
* an example URL might look like:
* adde://viper/text?group=textdata&file=myfile.txt
*
* </pre>
*/
public StringBuffer decodeTXTGString(String uCmd)
{
StringBuffer buf = new StringBuffer();
String testString;
String groupString = null;
String filenameString = null;
String descrString = null;
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
if (testString.startsWith("desc"))
{
descrString =
testString.substring(testString.indexOf("=") + 1);
}
if (testString.startsWith("file"))
{
filenameString = "FILE="+
testString.substring(testString.indexOf("=") + 1);
}
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
}
buf.append(groupString);
buf.append(" ");
buf.append(descrString);
buf.append(" ");
buf.append(filenameString);
return buf;
}
/**
* Decode the ADDE request for a weather text.
*
* <pre>
* there can be any valid combination of the following supported keywords:
*
* group=<group> weather text group (default= RTWXTEXT)
* prod=<product> predefind product name
* apro=<val1 .. valn> AFOS/AWIPS product headers to match (don't
* use with wmo keyword
* astn=<val1 .. valn> AFOS/AWIPS stations to match
* wmo= <val1 .. valn> WMO product headers to match (don't
* use with apro keyword
* wstn=<val1 .. valn> WMO stations to match
* day=<start end> range of days to search
* dtime=<numhours> maximum number of hours to search back (def=96)
* match=<match strings> list of character match strings to find from text
* num=<num> number of matches to find (def=1)
*
* the following keywords are required:
*
* day (should default to current, but there's a bug)
* apro, astn or wstn
*
* an example URL might look like:
* adde://viper/text?group=textdata&file=myfile.txt
*
* </pre>
*/
public StringBuffer decodeWTXGString(String uCmd)
{
StringBuffer buf = new StringBuffer();
String testString;
String tempString;
String numString = "NUM=1";
String dTimeString = "DTIME=96.0000";
String traceString = "TRACE=0";
// Mandatory strings
String groupString = "RTWXTEXT";
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
// group, descr and pos are mandatory
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("apro")) // apro keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("astn")) // astn keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("day")) // day keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("mat")) // match keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("prod")) // prod keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("sour")) // source keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("wmo")) // wmo keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("wstn")) // wstn keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("tra")) // trace keyword
{
traceString = testString;
}
else
if (testString.startsWith("num")) // num keyword
{
numString = testString;
}
else
if (testString.startsWith("dtim")) // dtime keyword
{
dTimeString = testString;
}
}
buf.append(" ");
buf.append(dTimeString);
buf.append(" ");
buf.append(numString);
buf.append(" ");
buf.append(traceString);
// now create command string
String posParams =
//new String(groupString + " ");
groupString + " ";
try
{
buf.insert(0, posParams);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(e.toString());
buf = new StringBuffer("");
}
return buf;
}
/**
* Decode the ADDE request for a weather observation text.
*
* <pre>
* there can be any valid combination of the following supported keywords:
*
*
* group=<group> weather text group (default= RTWXTEXT)
* descr=<descriptor> weather text subgroup (default=SFCHOURLY)
* id=<id1 id2 ... idn> list of station ids
* co=<co1 co2 ... con> list of countries
* reg=<reg1 reg2..regn> list of regions
* newest=<day hour> most recent time to allow in request
* (def=current time)
* oldest=<day hour> oldest observation time to allow in request
* type=<type> numeric value for the type of ob
* nhours=<numhours> maximum number of hours to search
* num=<num> number of matches to find (def=1)
*
* the following keywords are required:
*
* group
* descr
* id, co, or reg
*
* an example URL might look like:
* adde://adde.ucar.edu/obtext?group=rtwxtext&descr=sfchourly&id=kden&num=2
*
* </pre>
*/
public StringBuffer decodeOBTGString(String uCmd)
{
StringBuffer buf = new StringBuffer();
String testString;
String tempString;
String numString = "NUM=1";
String traceString = "TRACE=0";
// Mandatory strings
String groupString = "RTWXTEXT";
String descrString = "SFCHOURLY";
String idreqString = "IDREQ=LIST";
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
// group, descr and pos are mandatory
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("desc"))
{
descrString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("id")) // id keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("co")) // co keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("reg")) // reg keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("nhou")) // nhour keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("new")) // newest keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("old")) // oldest keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("type")) // type keyword
{
buf.append(" ");
buf.append(testString);
}
else
if (testString.startsWith("tra")) // trace keyword
{
traceString = testString;
}
else
if (testString.startsWith("num")) // num keyword
{
numString = testString;
}
}
buf.append(" ");
buf.append(numString);
buf.append(" ");
buf.append(traceString);
// now create command string
String posParams =
//new String(groupString + " " + descrString + " " + idreqString);
groupString + " " + descrString + " " + idreqString;
try
{
buf.insert(0, posParams);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(e.toString());
buf = new StringBuffer("");
}
return buf;
}
/**
* Decode the ADDE request for data set information.
*
* <pre>
* there can be any valid combination of the following supported keywords:
*
* group=<groupname> ADDE group name
* type=<datatype> ADDE data type. Must be one of the following:
* IMAGE, POINT, GRID, TEXT, NAV
* the default is the IMAGE type.
*
* the following keywords are required:
*
* group
*
* an example URL might look like:
* adde://viper/datasetinfo?group=gvar&type=image
*
* </pre>
*/
public StringBuffer decodeLWPRString(String uCmd)
{
StringBuffer buf = new StringBuffer();
String testString;
String tempString;
String groupString = null;
String typeString = "ala.";
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
// group, descr and pos are mandatory
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
if (testString.startsWith("type"))
{
tempString =
testString.substring(testString.indexOf("=") + 1);
if (tempString.startsWith("i"))
typeString = "ala.";
if (tempString.startsWith("g"))
typeString = "alg.";
else if (tempString.startsWith("p"))
typeString = "alm.";
else if (tempString.startsWith("t"))
typeString = "alt.";
else if (tempString.startsWith("n"))
typeString = "aln.";
else if (tempString.startsWith("s"))
typeString = "aln.";
}
}
buf.append(typeString);
buf.append(groupString);
return buf;
}
/**
* Decode the ADDE request for point data.
*
* If the request contains specific parameters (eg param=t),
* then the class variable binaryData is set to this param string
*
* group=<groupname> ADDE group name
* descr=<descriptor> ADDE descriptor name
* pos=<position> request an absolute or relative ADDE
* position number
* select=<select clause> to specify which data is required
* param=<param list> what parameters to return
* eg param=t[c]
* note that the units [c] are ignored by server
* it is the clients task to convert units
* Note that if "param=" is used,
* binaryData is set to the
* (processed) parameter list
* max=<max> maximum number of obs to return
* user=<user_id> ADDE user identification
* proj=<proj #> a valid ADDE project number
* trace=<0/1> setting to 1 tells server to write debug
* trace file (imagedata, imagedirectory)
* binaryData=<param list> because an unlimited number of parameters may
* be requested, these must be packaged up at the end
* of the adde request, and this is known as the
* "binary data" part of the request
*
* the following keywords are required:
*
* group
*
* an example URL might look like:
* adde://rtds/point?group=neons&descr=metar&user=jmk&proj=6999
*
* </pre>
*/
private StringBuffer decodeMDKSString(String uCmd)
{
StringBuffer buf = new StringBuffer();
String testString = null;
// Mandatory strings
String groupString = null;
String descrString = null;
String maxString = "max=1";
String numString = "";
// Options strings
String posString = "pos=0";
String traceString = "trace=0";
String selectString = "";
String parmString = "";
String justTheParametersString = "";
String justTheSelectString = "";
String sBinaryData = "";
boolean posInDescriptor = false;
// in hard coded notation, the binaryData for "param=t" would look like:
// binaryData = new byte[4];
// binaryData[0] = (byte) 'T';
// binaryData[1] = (byte) ' ';
// binaryData[2] = (byte) ' ';
// binaryData[3] = (byte) ' ';
StringTokenizer cmdTokens = new StringTokenizer(uCmd, "&");
while (cmdTokens.hasMoreTokens())
{
testString = cmdTokens.nextToken();
// group and descr
if (testString.startsWith("grou"))
{
groupString =
testString.substring(testString.indexOf("=") + 1);
}
else
if (testString.startsWith("des"))
{
descrString =
testString.substring(testString.indexOf("=") + 1);
int pos = descrString.indexOf(".");
if (pos >=0) {
posString = "pos=" + descrString.substring(pos+1);
descrString = descrString.substring(0,pos);
posInDescriptor = true;
}
}
else
// in McIDAS Clients the parameter request string contains param=
// but the adde server looks for parm=
// this bit of code forces this change so that Java Clients behave
// the same as McIDAS Clients
if (testString.startsWith("par"))
{
justTheParametersString =
testString.substring(testString.indexOf("=") + 1) ;
parmString =
"parm=" + justTheParametersString;
if (debug) System.out.println("paramString = " + parmString);
sBinaryData =
new String(decodePARAMString(justTheParametersString));
sBinaryData = sBinaryData.toUpperCase();
binaryData = sBinaryData.getBytes();
}
else
if (testString.startsWith("select"))
{
justTheSelectString =
testString.substring(testString.indexOf("=") + 1) ;
selectString =
"select=" + new String(
decodeSELECTString(justTheSelectString));
if (debug)
System.out.println("Server selectString = " + selectString);
}
else
// similarly, McIDAS Clients use num= but the server wants max=
if (testString.startsWith("num"))
{
maxString =
"max=" + testString.substring(testString.indexOf("=") + 1) ;
}
else
// allow for clever people who really know that the server uses
// max = :-)
if (testString.startsWith("max"))
{
maxString = testString;
}
// now get the rest of the keywords (but filter out non-needed)
else
if (testString.startsWith("tra")) // trace keyword
{
traceString = testString;
}
else
if (testString.startsWith("pos") && !posInDescriptor)
{
posString = testString;
}
}
// fudge the max string in case ALL is specified. Some servers
// don't handle all
if (maxString.trim().equalsIgnoreCase("max=all")) {
maxString="max=99999";
}
// now create command string
/*
StringBuffer posParams =
new StringBuffer(
groupString + " " + descrString + " " + parmString + " " + selectString + " " + posString + " " + traceString + " " + maxString);
*/
StringBuffer posParams = new StringBuffer();
posParams.append(groupString);
posParams.append(" ");
posParams.append(descrString);
posParams.append(" ");
posParams.append(parmString);
posParams.append(" ");
posParams.append(selectString);
posParams.append(" ");
posParams.append(posString);
posParams.append(" ");
posParams.append(traceString);
posParams.append(" ");
posParams.append(maxString);
if (debug) System.out.println("String passed to server = " + posParams);
// stuff it in at the beginning
try
{
buf.insert(0, posParams.toString());
if (debug) System.out.println("buf = " + buf);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(e.toString());
buf = new StringBuffer("");
}
return buf;
}
/**
* Helper function for decodeMDKSString to decode
* the "param=" part of a point data request
*
* Input
* justTheParametersString The parameter list which follows "param=" eg
* "id dir spd t[c] td[c]"
* Output
* method return String parameter list (padded to length 4 for server)
* without any units (units are ignored by server) eg
* "id dir spd t td "
* </pre>
*/
private String decodePARAMString(String justTheParametersString) {
String testString = null;
String thisParam = null;
String thisUnit = null;
StringBuffer buf = new StringBuffer();
StringTokenizer paramTokens =
new StringTokenizer(justTheParametersString, " ");
while (paramTokens.hasMoreTokens())
{
testString = (paramTokens.nextToken()).trim();
StringTokenizer thisParamToken =
new StringTokenizer(testString, "[]");
thisParam = new String((thisParamToken.nextToken()).trim());
buf.append(thisParam);
for (int i=thisParam.length(); i < 4; i++) {
buf.append(" ");
}
if (thisParamToken.hasMoreTokens()) {
// note that the units are ignored by the server
// it is the client's responsibility to do unit conversion
thisUnit = (thisParamToken.nextToken()).trim();
if (debug) System.out.println("This Unit = " + thisUnit);
}
}
return (buf.toString());
}
/**
* Helper function for decodeMDKSString to decode
* the "select=" part of a point data request
*
* Input
* justTheSelectString The select list which follows "select=" eg
* 'id ymml; time 12 18; day 1999316; t[c] 20 30; td 270 276'
* Output
* method return String The select list formatted for the server eg
* 'id ymml' 'time 12 to 18' 'day 1999316' 't 20 to 30 c' 'td 270 to 276'
*
* Reference
* McIDAS 7.6 source code: m0psort.for
*
* </pre>
*/
private String decodeSELECTString(String justTheSelectString) {
String testString = null;
String entireSelectString = null;
// String trimmedSelectString = null;
String thisSelect = null;
String thisUnit = null;
StringBuffer buf = new StringBuffer();
StringTokenizer entireSelectToken =
new StringTokenizer(justTheSelectString, "'");
entireSelectString = (entireSelectToken.nextToken()).trim();
//
// Break SELECT string up into parts
//
StringTokenizer selectTokens =
new StringTokenizer(entireSelectString, ";");
while (selectTokens.hasMoreTokens())
{
thisSelect = (selectTokens.nextToken()).trim();
if (debug) System.out.println(" this Select = " + thisSelect);
//
// Break into individual clauses eg:
// t[c] 20 30
//
StringTokenizer thisSelectToken =
new StringTokenizer(thisSelect, " ");
int tokenCount = thisSelectToken.countTokens();
thisSelect = new String(thisSelectToken.nextToken());
if (debug) System.out.println("this Select = " + thisSelect);
//
// Check to see if any units are involved eg:
// t[c]
if (thisSelect.indexOf("[") > 0) {
StringTokenizer thisUnitToken =
new StringTokenizer(thisSelect, "[]");
if (thisUnitToken.hasMoreTokens()) {
thisSelect = new String((thisUnitToken.nextToken()).trim());
buf.append("'" + thisSelect);
if (thisUnitToken.hasMoreTokens()) {
thisUnit =
new String((thisUnitToken.nextToken()).trim());
}
}
} else {
// no units involved eg:
// t
buf.append("'" + thisSelect);
}
//
// Check for first numeric value eg if select='t[c] 20 30':
// 20
//
if (thisSelectToken.hasMoreTokens()) {
thisSelect = thisSelectToken.nextToken();
if (debug) System.out.println("this Select = " + thisSelect);
buf.append(" " + thisSelect);
}
//
// Check for second numeric value eg if select='t[c] 20 30':
// 30
//
if (thisSelectToken.hasMoreTokens()) {
thisSelect = thisSelectToken.nextToken();
// server requires TO for a range of values eg:
// 20 to 30
buf.append(" TO " + thisSelect);
if (debug) System.out.println("this Select = " + thisSelect);
}
//
// add unit if specified
//
if (thisUnit != null) {
buf.append(" " + thisUnit);
thisUnit = null;
}
buf.append("' ");
}
return (buf.toString());
}
/* Ensures that a string is two values. If only one, then it
is returned as s + " " + s */
private String ensureTwoValues(String s)
{
String retVal = null;
if (s.trim().indexOf(" ") > 0) // has multiple values
{
StringTokenizer tok = new StringTokenizer(s);
// return null if more than 2
if (tok.countTokens() == 2) retVal = s;
}
else
{
//retVal = new String(s + " " + s);
retVal = s + " " + s;
}
return retVal;
}
/* Adjust the longitude from East Postitive to west positive */
private String adjustLongitudes(String input)
{
input = input.trim();
String lon1 = negateLongitude(input.substring(0, input.trim().indexOf(" ")).trim());
String lon2 = negateLongitude(input.substring(input.trim().indexOf(" ")).trim());
return (lon2 + " " + lon1);
}
private String negateLongitude(String eastLong)
{
if (eastLong.indexOf("-") >= 0) // (comes in as -)
return eastLong.substring(eastLong.indexOf("-") + 1);
else
return "-" + eastLong;
}
private static String[] replaceWith = {"&", "<", ">", "\'", "\"", "\r", "\n", " "};
private static String[] replaceString = {"&", "<", ">", "'", """, " ", " ", "%20" };
private URL normalizeURL(URL url) {
String x;
try {
x = URLDecoder.decode(url.toString());
}
catch (java.lang.Exception e) {
throw new RuntimeException(e.toString());
}
// common case no replacement
boolean ok = true;
for (int i=0; i<replaceString.length; i++) {
int pos = x.indexOf(replaceString[i]);
ok &= (pos < 0);
}
if (!ok) { // gotta do it
for (int i=0; i<replaceString.length; i++) {
int pos = -1;
while ((pos = x.indexOf(replaceString[i])) >=0) {
if (debug) System.out.println("found " + replaceString[i] + " at " + pos);
StringBuffer buf = new StringBuffer(x);
buf.replace(pos, pos+(replaceString[i].length()), replaceWith[i]);
x = buf.toString();
}
}
}
if (debug) System.out.println("normalized url = " + x);
try {
return new URL(x);
} catch (Exception e) {}
return url;
}
}
| false | true | synchronized public void connect ()
throws IOException, AddeURLException
{
// First, see if we can use the URL passed in
// verify the service is one we can handle
// get rid of leading /
// keep original to preserve case for user= clause
String requestOriginal = url.getFile().substring(1);
String request = requestOriginal.toLowerCase();
debug = debug || request.indexOf("debug=true") >= 0;
if (debug) System.out.println("host from URL: " + url.getHost());
if (debug) System.out.println("file from URL: " + url.getFile());
if (!request.startsWith("image") &&
(!request.startsWith("datasetinfo")) &&
(!request.startsWith("text")) &&
(!request.startsWith("wxtext")) &&
(!request.startsWith("obtext")) &&
(!request.startsWith("grid")) &&
(!request.startsWith("point")) )
{
throw new AddeURLException("Request for unknown data");
}
// service - for area files, it's either AGET (Area GET) or
// ADIR (AREA directory)
byte [] svc = null;
if (request.startsWith("imagedir"))
{
svc = "adir".getBytes();
reqType = ADIR;
}
else if (request.startsWith("datasetinfo"))
{
svc = "lwpr".getBytes();
reqType = LWPR;
}
else if (request.startsWith("text"))
{
svc = "txtg".getBytes();
reqType = TXTG;
}
else if (request.startsWith("wxtext"))
{
svc = "wtxg".getBytes();
reqType = WTXG;
}
else if (request.startsWith("obtext"))
{
svc = "obtg".getBytes();
reqType = OBTG;
}
else if (request.startsWith("image"))
{
svc = "aget".getBytes();
reqType = AGET;
}
else if (request.startsWith("griddir"))
{
svc = "gdir".getBytes();
reqType = GDIR;
}
else if (request.startsWith("grid"))
{
svc = "gget".getBytes();
reqType = GGET;
}
else if (request.startsWith("point"))
{
svc = "mdks".getBytes();
reqType = MDKS;
}
else
{
throw new AddeURLException(
"Invalid or unsupported ADDE service= "+svc.toString() );
}
if (debug) System.out.println("Service = " + new String(svc));
// prep for real thing - get cmd from file part of URL
int test = request.indexOf("?");
String uCmd = (test >=0) ? request.substring(test+1) : request;
if (debug) System.out.println("uCmd="+uCmd);
// build the command string
StringBuffer sb = new StringBuffer();
switch (reqType)
{
case AGET:
sb = decodeAGETString(uCmd);
break;
case ADIR:
sb = decodeADIRString(uCmd);
break;
case LWPR:
sb = decodeLWPRString(uCmd);
break;
case GDIR:
sb = decodeGDIRString(uCmd);
break;
case GGET:
sb = decodeGDIRString(uCmd);
break;
case MDKS:
sb = decodeMDKSString(uCmd);
break;
case TXTG:
sb = decodeTXTGString(uCmd);
break;
case WTXG:
sb = decodeWTXGString(uCmd);
break;
case OBTG:
sb = decodeOBTGString(uCmd);
break;
}
// indefinitely use ADDE version 1 unless it's a GGET request
sb.append(" version=");
sb.append((reqType == GGET || reqType == WTXG) ? "A" : "1");
// now convert to array of bytes for output since chars are two byte
String cmd = new String(sb);
cmd = cmd.toUpperCase();
if (debug) System.out.println(cmd);
byte [] ob = cmd.getBytes();
// get some other stuff
int startIdx;
int endIdx;
// user initials - pass on what client supplied in user= keyword
byte [] usr;
String userStr;
startIdx = request.indexOf("user=");
if (startIdx > 0) {
endIdx = request.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = request.length();
// use original to preserve case
userStr = requestOriginal.substring(startIdx + 5, endIdx);
} else {
userStr = "XXXX";
}
usr = userStr.getBytes();
// project number - we won't validate, but make sure it's there
startIdx = uCmd.indexOf("proj=");
String projStr;
int proj;
if (startIdx > 0) {
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
projStr = uCmd.substring(startIdx + 5, endIdx);
} else {
projStr = "0";
}
try {
proj = Integer.parseInt(projStr);
} catch (NumberFormatException e) {
throw new AddeURLException("Invalid project number: " + projStr);
}
// compression
startIdx = uCmd.indexOf("compress=");
String compType = "";
if (startIdx > 0) {
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
compType = uCmd.substring(startIdx + 9, endIdx);
}
if (compType.equalsIgnoreCase("gzip")) {
compressionType = GZIP;
} else if (compType.equalsIgnoreCase("compress") ||
compType.equalsIgnoreCase("true")) {
// check to see if we can do uncompression
try {
Class c = Class.forName("HTTPClient.UncompressInputStream");
compressionType = COMPRESS;
} catch (ClassNotFoundException cnfe) {
System.err.println(
"Uncompression code not found, turning compression off");
}
}
// end of request decoding
//-------------------------------------------------------------------------
// now write this all to the port
// first figure out which port to connect on. This can either be
// one specified by the user.
//
// The priority is URL port, port=keyword, compression port (default)
if (url.getPort() == -1) { // not specified as part of URL
// see if there is a port=keyword
// default to the compression type
portToUse = compressionType;
startIdx = uCmd.indexOf("port=");
if (startIdx > 0) {
String portStr;
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
portStr = uCmd.substring(startIdx + 5, endIdx);
try {
portToUse = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
throw new AddeURLException("Invalid port number: " + portStr);
}
}
} else { // specified
portToUse = url.getPort();
}
if (debug) {
System.out.println("connecting on port " + portToUse + " using " +
(compressionType == GZIP
? "gzip"
: compressionType == COMPRESS
? "compress"
: "no") + " compression.");
}
Socket t;
try {
t = new Socket(url.getHost(), portToUse); // DRM 03-Mar-2001
} catch (UnknownHostException e) {
throw new AddeURLException(e.toString());
}
dos = new DataOutputStream ( t.getOutputStream() );
/*
Now start pumping data to the server. The sequence is:
- ADDE version (1 for now)
- Server IP and Port number (latter used to determine compression)
- Service Type (AGET, ADIR, etc)
- Server IP and Port number (again)
- Client address
- User, project, password
- Service Type (again)
- Actual request
*/
// send version number - ADDE seems to be stuck at 1
dos.writeInt(VERSION_1);
// send IP address of server
// we know the server IP address is good cause we used it above
byte [] ipa = new byte[4];
InetAddress ia = InetAddress.getByName(url.getHost());
ipa = ia.getAddress();
dos.write(ipa, 0, ipa.length);
// send ADDE port number which server uses to determine compression
dos.writeInt(compressionType);
// send the service type
dos.write(svc, 0, svc.length);
// now build and send request block, repeat some stuff
// server IP address, port
dos.write(ipa, 0, ipa.length);
dos.writeInt(compressionType); // DRM 03-Mar-2001
// client IP address
InetAddress lh = InetAddress.getLocalHost();
ipa = lh.getAddress();
dos.write(ipa, 0, ipa.length);
// gotta send 4 user bytes, ADDE protocol expects it
if (usr.length <= 4) {
dos.write(usr, 0, usr.length);
for (int i = 0; i < 4 - usr.length; i++) {
dos.writeByte(' ');
}
} else {
// if id entered was > 4 chars, complain
throw new AddeURLException("Invalid user id: " + userStr);
}
dos.writeInt(proj);
// password chars - not used either
byte [] pwd = new byte[12];
dos.write(pwd, 0, pwd.length);
// service - resend svc array
dos.write(svc, 0, svc.length);
// Write out the data. There are 2 cases:
//
// 1) ob.length <= 120
// 2) ob.length > 120
//
// In either case, there may or may not be additional binary data
//
int numBinaryBytes = 0;
if (binaryData != null) numBinaryBytes = binaryData.length;
if (ob.length > REQUEST_SIZE)
{
dos.writeInt(ob.length + numBinaryBytes); // number of additional bytes
dos.writeInt(ob.length); // number of bytes in request
for (int i=0; i < REQUEST_SIZE - 4; i++) { // - 4 accounts for prev line
dos.writeByte(0);
}
dos.write(ob,0,ob.length);
} else {
if (debug) System.out.println("numBinaryBytes= " + numBinaryBytes);
dos.writeInt(numBinaryBytes);
dos.write(ob, 0, ob.length);
for (int i=0; i < REQUEST_SIZE - ob.length; i++) {
dos.writeByte(' ');
}
}
if (numBinaryBytes > 0) dos.write(binaryData, 0, numBinaryBytes);
is = (compressionType == GZIP)
? new GZIPInputStream(t.getInputStream())
: (compressionType == COMPRESS)
? new UncompressInputStream(t.getInputStream())
: t.getInputStream();
dis = new DataInputStream(is);
if (debug && (compressionType != portToUse) ) {
System.out.println("Compression is turned ON using " +
((compressionType == GZIP)?"GZIP":"compress"));
}
// get response from server, byte count coming back
numBytes = dis.readInt();
if (debug) System.out.println("server is sending: " + numBytes + " bytes");
// if server returns zero, there was an error so read trailer and exit
if (numBytes == 0) {
byte [] trailer = new byte[TRAILER_SIZE];
dis.readFully(trailer, 0, trailer.length);
String errMsg = new String(trailer, ERRMSG_OFFS, ERRMSG_SIZE);
throw new AddeURLException(errMsg);
}
// if we made it to here, we're getting data
connected = true;
}
| synchronized public void connect ()
throws IOException, AddeURLException
{
// First, see if we can use the URL passed in
// verify the service is one we can handle
// get rid of leading /
// keep original to preserve case for user= clause
String requestOriginal = url.getFile().substring(1);
String request = requestOriginal.toLowerCase();
debug = debug || request.indexOf("debug=true") >= 0;
if (debug) System.out.println("host from URL: " + url.getHost());
if (debug) System.out.println("file from URL: " + url.getFile());
if (!request.startsWith("image") &&
(!request.startsWith("datasetinfo")) &&
(!request.startsWith("text")) &&
(!request.startsWith("wxtext")) &&
(!request.startsWith("obtext")) &&
(!request.startsWith("grid")) &&
(!request.startsWith("point")) )
{
throw new AddeURLException("Request for unknown data");
}
// service - for area files, it's either AGET (Area GET) or
// ADIR (AREA directory)
byte [] svc = null;
if (request.startsWith("imagedir"))
{
svc = "adir".getBytes();
reqType = ADIR;
}
else if (request.startsWith("datasetinfo"))
{
svc = "lwpr".getBytes();
reqType = LWPR;
}
else if (request.startsWith("text"))
{
svc = "txtg".getBytes();
reqType = TXTG;
}
else if (request.startsWith("wxtext"))
{
svc = "wtxg".getBytes();
reqType = WTXG;
}
else if (request.startsWith("obtext"))
{
svc = "obtg".getBytes();
reqType = OBTG;
}
else if (request.startsWith("image"))
{
svc = "aget".getBytes();
reqType = AGET;
}
else if (request.startsWith("griddir"))
{
svc = "gdir".getBytes();
reqType = GDIR;
}
else if (request.startsWith("grid"))
{
svc = "gget".getBytes();
reqType = GGET;
}
else if (request.startsWith("point"))
{
svc = "mdks".getBytes();
reqType = MDKS;
}
else
{
throw new AddeURLException(
"Invalid or unsupported ADDE service= "+svc.toString() );
}
if (debug) System.out.println("Service = " + new String(svc));
// prep for real thing - get cmd from file part of URL
int test = request.indexOf("?");
String uCmd = (test >=0) ? request.substring(test+1) : request;
if (debug) System.out.println("uCmd="+uCmd);
// build the command string
StringBuffer sb = new StringBuffer();
switch (reqType)
{
case AGET:
sb = decodeAGETString(uCmd);
break;
case ADIR:
sb = decodeADIRString(uCmd);
break;
case LWPR:
sb = decodeLWPRString(uCmd);
break;
case GDIR:
sb = decodeGDIRString(uCmd);
break;
case GGET:
sb = decodeGDIRString(uCmd);
break;
case MDKS:
sb = decodeMDKSString(uCmd);
break;
case TXTG:
sb = decodeTXTGString(uCmd);
break;
case WTXG:
sb = decodeWTXGString(uCmd);
break;
case OBTG:
sb = decodeOBTGString(uCmd);
break;
}
// indefinitely use ADDE version 1 unless it's a GGET request
sb.append(" version=");
sb.append((reqType == GGET || reqType == WTXG) ? "A" : "1");
// now convert to array of bytes for output since chars are two byte
String cmd = new String(sb);
cmd = cmd.toUpperCase();
if (debug) System.out.println(cmd);
byte [] ob = cmd.getBytes();
// get some other stuff
int startIdx;
int endIdx;
// user initials - pass on what client supplied in user= keyword
byte [] usr;
String userStr;
startIdx = request.indexOf("user=");
if (startIdx >= 0) {
endIdx = request.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = request.length();
// use original to preserve case
userStr = requestOriginal.substring(startIdx + 5, endIdx);
} else {
userStr = "XXXX";
}
usr = userStr.getBytes();
// project number - we won't validate, but make sure it's there
startIdx = uCmd.indexOf("proj=");
String projStr;
int proj;
if (startIdx >= 0) {
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
projStr = uCmd.substring(startIdx + 5, endIdx);
} else {
projStr = "0";
}
try {
proj = Integer.parseInt(projStr);
} catch (NumberFormatException e) {
throw new AddeURLException("Invalid project number: " + projStr);
}
// compression
startIdx = uCmd.indexOf("compress=");
String compType = "";
if (startIdx >= 0) {
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
compType = uCmd.substring(startIdx + 9, endIdx);
}
if (compType.equalsIgnoreCase("gzip")) {
compressionType = GZIP;
} else if (compType.equalsIgnoreCase("compress") ||
compType.equalsIgnoreCase("true")) {
// check to see if we can do uncompression
try {
Class c = Class.forName("HTTPClient.UncompressInputStream");
compressionType = COMPRESS;
} catch (ClassNotFoundException cnfe) {
System.err.println(
"Uncompression code not found, turning compression off");
}
}
// end of request decoding
//-------------------------------------------------------------------------
// now write this all to the port
// first figure out which port to connect on. This can either be
// one specified by the user.
//
// The priority is URL port, port=keyword, compression port (default)
if (url.getPort() == -1) { // not specified as part of URL
// see if there is a port=keyword
// default to the compression type
portToUse = compressionType;
startIdx = uCmd.indexOf("port=");
if (startIdx >= 0) {
String portStr;
endIdx = uCmd.indexOf('&', startIdx);
if (endIdx == -1) // last on line
endIdx = uCmd.length();
portStr = uCmd.substring(startIdx + 5, endIdx);
try {
portToUse = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
throw new AddeURLException("Invalid port number: " + portStr);
}
}
} else { // specified
portToUse = url.getPort();
}
if (debug) {
System.out.println("connecting on port " + portToUse + " using " +
(compressionType == GZIP
? "gzip"
: compressionType == COMPRESS
? "compress"
: "no") + " compression.");
}
Socket t;
try {
t = new Socket(url.getHost(), portToUse); // DRM 03-Mar-2001
} catch (UnknownHostException e) {
throw new AddeURLException(e.toString());
}
dos = new DataOutputStream ( t.getOutputStream() );
/*
Now start pumping data to the server. The sequence is:
- ADDE version (1 for now)
- Server IP and Port number (latter used to determine compression)
- Service Type (AGET, ADIR, etc)
- Server IP and Port number (again)
- Client address
- User, project, password
- Service Type (again)
- Actual request
*/
// send version number - ADDE seems to be stuck at 1
dos.writeInt(VERSION_1);
// send IP address of server
// we know the server IP address is good cause we used it above
byte [] ipa = new byte[4];
InetAddress ia = InetAddress.getByName(url.getHost());
ipa = ia.getAddress();
dos.write(ipa, 0, ipa.length);
// send ADDE port number which server uses to determine compression
dos.writeInt(compressionType);
// send the service type
dos.write(svc, 0, svc.length);
// now build and send request block, repeat some stuff
// server IP address, port
dos.write(ipa, 0, ipa.length);
dos.writeInt(compressionType); // DRM 03-Mar-2001
// client IP address
InetAddress lh = InetAddress.getLocalHost();
ipa = lh.getAddress();
dos.write(ipa, 0, ipa.length);
// gotta send 4 user bytes, ADDE protocol expects it
if (usr.length <= 4) {
dos.write(usr, 0, usr.length);
for (int i = 0; i < 4 - usr.length; i++) {
dos.writeByte(' ');
}
} else {
// if id entered was > 4 chars, complain
throw new AddeURLException("Invalid user id: " + userStr);
}
dos.writeInt(proj);
// password chars - not used either
byte [] pwd = new byte[12];
dos.write(pwd, 0, pwd.length);
// service - resend svc array
dos.write(svc, 0, svc.length);
// Write out the data. There are 2 cases:
//
// 1) ob.length <= 120
// 2) ob.length > 120
//
// In either case, there may or may not be additional binary data
//
int numBinaryBytes = 0;
if (binaryData != null) numBinaryBytes = binaryData.length;
if (ob.length > REQUEST_SIZE)
{
dos.writeInt(ob.length + numBinaryBytes); // number of additional bytes
dos.writeInt(ob.length); // number of bytes in request
for (int i=0; i < REQUEST_SIZE - 4; i++) { // - 4 accounts for prev line
dos.writeByte(0);
}
dos.write(ob,0,ob.length);
} else {
if (debug) System.out.println("numBinaryBytes= " + numBinaryBytes);
dos.writeInt(numBinaryBytes);
dos.write(ob, 0, ob.length);
for (int i=0; i < REQUEST_SIZE - ob.length; i++) {
dos.writeByte(' ');
}
}
if (numBinaryBytes > 0) dos.write(binaryData, 0, numBinaryBytes);
is = (compressionType == GZIP)
? new GZIPInputStream(t.getInputStream())
: (compressionType == COMPRESS)
? new UncompressInputStream(t.getInputStream())
: t.getInputStream();
dis = new DataInputStream(is);
if (debug && (compressionType != portToUse) ) {
System.out.println("Compression is turned ON using " +
((compressionType == GZIP)?"GZIP":"compress"));
}
// get response from server, byte count coming back
numBytes = dis.readInt();
if (debug) System.out.println("server is sending: " + numBytes + " bytes");
// if server returns zero, there was an error so read trailer and exit
if (numBytes == 0) {
byte [] trailer = new byte[TRAILER_SIZE];
dis.readFully(trailer, 0, trailer.length);
String errMsg = new String(trailer, ERRMSG_OFFS, ERRMSG_SIZE);
throw new AddeURLException(errMsg);
}
// if we made it to here, we're getting data
connected = true;
}
|
diff --git a/navit/navit/android/src/org/navitproject/navit/NavitGraphics.java b/navit/navit/android/src/org/navitproject/navit/NavitGraphics.java
index 4170d19c..2520978c 100644
--- a/navit/navit/android/src/org/navitproject/navit/NavitGraphics.java
+++ b/navit/navit/android/src/org/navitproject/navit/NavitGraphics.java
@@ -1,971 +1,972 @@
/**
* Navit, a modular navigation system.
* Copyright (C) 2005-2008 Navit Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package org.navitproject.navit;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.navitproject.navit.Navit.Navit_Address_Result_Struct;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
public class NavitGraphics
{
private NavitGraphics parent_graphics;
private ArrayList<NavitGraphics> overlays = new ArrayList<NavitGraphics>();
int bitmap_w;
int bitmap_h;
int pos_x;
int pos_y;
int pos_wraparound;
int overlay_disabled;
float trackball_x, trackball_y;
View view;
RelativeLayout relativelayout;
NavitCamera camera;
Activity activity;
public static Boolean in_map = false;
// for menu key
private static long time_for_long_press = 300L;
private static long interval_for_long_press = 200L;
private Handler timer_handler = new Handler();
public void SetCamera(int use_camera)
{
if (use_camera != 0 && camera == null)
{
// activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
camera = new NavitCamera(activity);
relativelayout.addView(camera);
relativelayout.bringChildToFront(view);
}
}
private class NavitView extends View implements Runnable, MenuItem.OnMenuItemClickListener{
int touch_mode = NONE;
float oldDist = 0;
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int PRESSED = 3;
Method eventGetX = null;
Method eventGetY = null;
public PointF mPressedPosition = null;
public NavitView(Context context) {
super(context);
try
{
eventGetX = android.view.MotionEvent.class.getMethod("getX", int.class);
eventGetY = android.view.MotionEvent.class.getMethod("getY", int.class);
}
catch (Exception e)
{
Log.e("NavitGraphics", "Multitouch zoom not supported");
}
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
menu.setHeaderTitle("Position...");
menu.add(1, 1, NONE, Navit.get_text("drive here")).setOnMenuItemClickListener(this);
// menu.add(1, 2, NONE, Navit.get_text("Add to contacts")).setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()) {
case 1:
Message msg = Message.obtain(callback_handler, msg_type.CLB_SET_DISPLAY_DESTINATION.ordinal()
, (int)mPressedPosition.x, (int)mPressedPosition.y);
msg.sendToTarget();
break;
case 2:
break;
}
return false;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawBitmap(draw_bitmap, pos_x, pos_y, null);
if (overlay_disabled == 0)
{
//Log.e("NavitGraphics", "view -> onDraw 1");
// assume we ARE in map view mode!
in_map = true;
Object overlays_array[];
overlays_array = overlays.toArray();
for (Object overlay : overlays_array)
{
//Log.e("NavitGraphics","view -> onDraw 2");
NavitGraphics overlay_graphics = (NavitGraphics) overlay;
if (overlay_graphics.overlay_disabled == 0)
{
//Log.e("NavitGraphics","view -> onDraw 3");
int x = overlay_graphics.pos_x;
int y = overlay_graphics.pos_y;
if (overlay_graphics.pos_wraparound != 0 && x < 0) x += bitmap_w;
if (overlay_graphics.pos_wraparound != 0 && y < 0) y += bitmap_h;
canvas.drawBitmap(overlay_graphics.draw_bitmap, x, y, null);
}
}
}
else
{
if (Navit.show_soft_keyboard)
{
if (Navit.mgr != null)
{
//Log.e("NavitGraphics", "view -> SHOW SoftInput");
//Log.e("NavitGraphics", "view mgr=" + String.valueOf(Navit.mgr));
Navit.mgr.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT);
Navit.show_soft_keyboard_now_showing = true;
// clear the variable now, keyboard will stay on screen until backbutton pressed
Navit.show_soft_keyboard = false;
}
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
Log.e("Navit", "NavitGraphics -> onSizeChanged pixels x=" + w + " pixels y=" + h);
Log.e("Navit", "NavitGraphics -> onSizeChanged density=" + Navit.metrics.density);
Log.e("Navit", "NavitGraphics -> onSizeChanged scaledDensity="
+ Navit.metrics.scaledDensity);
super.onSizeChanged(w, h, oldw, oldh);
draw_bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
draw_canvas = new Canvas(draw_bitmap);
bitmap_w = w;
bitmap_h = h;
SizeChangedCallback(SizeChangedCallbackID, w, h);
}
public void do_longpress_action()
{
Log.e("NavitGraphics", "do_longpress_action enter");
activity.openContextMenu(this);
}
private int getActionField(String fieldname, Object obj)
{
int ret_value = -999;
try
{
java.lang.reflect.Field field = android.view.MotionEvent.class.getField(fieldname);
try
{
ret_value = field.getInt(obj);
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (NoSuchFieldException ex) {}
return ret_value;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
//Log.e("NavitGraphics", "onTouchEvent");
super.onTouchEvent(event);
int x = (int) event.getX();
int y = (int) event.getY();
int _ACTION_POINTER_UP_ = getActionField("ACTION_POINTER_UP", event);
int _ACTION_POINTER_DOWN_ = getActionField("ACTION_POINTER_DOWN", event);
int _ACTION_MASK_ = getActionField("ACTION_MASK", event);
int switch_value = event.getAction();
if (_ACTION_MASK_ != -999)
{
switch_value = (event.getAction() & _ACTION_MASK_);
}
if (switch_value == MotionEvent.ACTION_DOWN)
{
touch_mode = PRESSED;
+ if (!in_map) ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
mPressedPosition = new PointF(x, y);
postDelayed(this, time_for_long_press);
}
else if ((switch_value == MotionEvent.ACTION_UP) || (switch_value == _ACTION_POINTER_UP_))
{
Log.e("NavitGraphics", "ACTION_UP");
if ( touch_mode == DRAG )
{
Log.e("NavitGraphics", "onTouch move");
MotionCallback(MotionCallbackID, x, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
}
else if (touch_mode == ZOOM)
{
//Log.e("NavitGraphics", "onTouch zoom");
float newDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
float scale = 0;
if (newDist > 10f)
{
scale = newDist / oldDist;
}
if (scale > 1.3)
{
// zoom in
CallbackMessageChannel(1, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom in");
}
else if (scale < 0.8)
{
// zoom out
CallbackMessageChannel(2, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom out");
}
}
else if (touch_mode == PRESSED)
{
- ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
+ if (in_map) ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
}
touch_mode = NONE;
}
else if (switch_value == MotionEvent.ACTION_MOVE)
{
//Log.e("NavitGraphics", "ACTION_MOVE");
if (touch_mode == DRAG)
{
MotionCallback(MotionCallbackID, x, y);
}
else if (touch_mode == ZOOM)
{
float newDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
float scale = newDist / oldDist;
Log.e("NavitGraphics", "New scale = " + scale);
if (scale > 1.2)
{
// zoom in
CallbackMessageChannel(1, "");
oldDist = newDist;
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom in");
}
else if (scale < 0.8)
{
oldDist = newDist;
// zoom out
CallbackMessageChannel(2, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom out");
}
}
else if (touch_mode == PRESSED)
{
Log.e("NavitGraphics", "Start drag mode");
if ( spacing(mPressedPosition, new PointF(event.getX(), event.getY())) > 20f) {
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
touch_mode = DRAG;
}
}
}
else if (switch_value == _ACTION_POINTER_DOWN_)
{
//Log.e("NavitGraphics", "ACTION_POINTER_DOWN");
oldDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
if (oldDist > 2f)
{
touch_mode = ZOOM;
//Log.e("NavitGraphics", "--> zoom");
}
}
return true;
}
private float spacing(PointF a, PointF b)
{
float x = a.x - b.x;
float y = a.y - b.y;
return FloatMath.sqrt(x * x + y * y);
}
private PointF getFloatValue(Object instance, Object argument)
{
PointF pos = new PointF(0,0);
if (eventGetX != null && eventGetY != null)
{
try
{
Float x = (java.lang.Float) eventGetX.invoke(instance, argument);
Float y = (java.lang.Float) eventGetY.invoke(instance, argument);
pos.set(x.floatValue(), y.floatValue());
}
catch (Exception e){}
}
return pos;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
int i;
String s = null;
boolean handled = true;
i = event.getUnicodeChar();
//Log.e("NavitGraphics", "onKeyDown " + keyCode + " " + i);
// Log.e("NavitGraphics","Unicode "+event.getUnicodeChar());
if (i == 0)
{
if (keyCode == android.view.KeyEvent.KEYCODE_DEL)
{
s = java.lang.String.valueOf((char) 8);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_MENU)
{
if (!in_map)
{
// if last menukeypress is less than 0.2 seconds away then count longpress
if ((System.currentTimeMillis() - Navit.last_pressed_menu_key) < interval_for_long_press)
{
Navit.time_pressed_menu_key = Navit.time_pressed_menu_key
+ (System.currentTimeMillis() - Navit.last_pressed_menu_key);
//Log.e("NavitGraphics", "press time=" + Navit.time_pressed_menu_key);
// on long press let softkeyboard popup
if (Navit.time_pressed_menu_key > time_for_long_press)
{
//Log.e("NavitGraphics", "long press menu key!!");
Navit.show_soft_keyboard = true;
Navit.time_pressed_menu_key = 0L;
// need to draw to get the keyboard showing
this.postInvalidate();
}
}
else
{
Navit.time_pressed_menu_key = 0L;
}
Navit.last_pressed_menu_key = System.currentTimeMillis();
// if in menu view:
// use as OK (Enter) key
s = java.lang.String.valueOf((char) 13);
handled = true;
// dont use menu key here (use it in onKeyUp)
return handled;
}
else
{
// if on map view:
// volume UP
//s = java.lang.String.valueOf((char) 1);
handled = false;
return handled;
}
}
else if (keyCode == android.view.KeyEvent.KEYCODE_SEARCH)
{
s = java.lang.String.valueOf((char) 19);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_BACK)
{
//Log.e("NavitGraphics", "KEYCODE_BACK down");
s = java.lang.String.valueOf((char) 27);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_CALL)
{
s = java.lang.String.valueOf((char) 3);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_VOLUME_UP)
{
if (!in_map)
{
// if in menu view:
// use as UP key
s = java.lang.String.valueOf((char) 16);
handled = true;
}
else
{
// if on map view:
// volume UP
//s = java.lang.String.valueOf((char) 21);
handled = false;
return handled;
}
}
else if (keyCode == android.view.KeyEvent.KEYCODE_VOLUME_DOWN)
{
if (!in_map)
{
// if in menu view:
// use as DOWN key
s = java.lang.String.valueOf((char) 14);
handled = true;
}
else
{
// if on map view:
// volume DOWN
//s = java.lang.String.valueOf((char) 4);
handled = false;
return handled;
}
}
else if (keyCode == android.view.KeyEvent.KEYCODE_DPAD_CENTER)
{
s = java.lang.String.valueOf((char) 13);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_DPAD_DOWN)
{
s = java.lang.String.valueOf((char) 16);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT)
{
s = java.lang.String.valueOf((char) 2);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT)
{
s = java.lang.String.valueOf((char) 6);
}
else if (keyCode == android.view.KeyEvent.KEYCODE_DPAD_UP)
{
s = java.lang.String.valueOf((char) 14);
}
}
else if (i == 10)
{
s = java.lang.String.valueOf((char) 13);
}
else
{
s = java.lang.String.valueOf((char) i);
}
if (s != null)
{
KeypressCallback(KeypressCallbackID, s);
}
return handled;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
//Log.e("NavitGraphics", "onKeyUp " + keyCode);
int i;
String s = null;
boolean handled = true;
i = event.getUnicodeChar();
if (i == 0)
{
if (keyCode == android.view.KeyEvent.KEYCODE_VOLUME_UP)
{
if (!in_map)
{
//s = java.lang.String.valueOf((char) 16);
handled = true;
return handled;
}
else
{
//s = java.lang.String.valueOf((char) 21);
handled = false;
return handled;
}
}
else if (keyCode == android.view.KeyEvent.KEYCODE_VOLUME_DOWN)
{
if (!in_map)
{
//s = java.lang.String.valueOf((char) 14);
handled = true;
return handled;
}
else
{
//s = java.lang.String.valueOf((char) 4);
handled = false;
return handled;
}
}
else if (keyCode == android.view.KeyEvent.KEYCODE_BACK)
{
if (Navit.show_soft_keyboard_now_showing)
{
Navit.show_soft_keyboard_now_showing = false;
}
//Log.e("NavitGraphics", "KEYCODE_BACK up");
//s = java.lang.String.valueOf((char) 27);
handled = true;
return handled;
}
else if (keyCode == android.view.KeyEvent.KEYCODE_MENU)
{
if (!in_map)
{
if (Navit.show_soft_keyboard_now_showing)
{
// if soft keyboard showing on screen, dont use menu button as select key
}
else
{
// if in menu view:
// use as OK (Enter) key
s = java.lang.String.valueOf((char) 13);
handled = true;
}
}
else
{
// if on map view:
// volume UP
//s = java.lang.String.valueOf((char) 1);
handled = false;
return handled;
}
}
}
if (s != null)
{
KeypressCallback(KeypressCallbackID, s);
}
return handled;
}
@Override
public boolean onTrackballEvent(MotionEvent event)
{
//Log.e("NavitGraphics", "onTrackball " + event.getAction() + " " + event.getX() + " "
// + event.getY());
String s = null;
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN)
{
s = java.lang.String.valueOf((char) 13);
}
if (event.getAction() == android.view.MotionEvent.ACTION_MOVE)
{
trackball_x += event.getX();
trackball_y += event.getY();
//Log.e("NavitGraphics", "trackball " + trackball_x + " " + trackball_y);
if (trackball_x <= -1)
{
s = java.lang.String.valueOf((char) 2);
trackball_x += 1;
}
if (trackball_x >= 1)
{
s = java.lang.String.valueOf((char) 6);
trackball_x -= 1;
}
if (trackball_y <= -1)
{
s = java.lang.String.valueOf((char) 16);
trackball_y += 1;
}
if (trackball_y >= 1)
{
s = java.lang.String.valueOf((char) 14);
trackball_y -= 1;
}
}
if (s != null)
{
KeypressCallback(KeypressCallbackID, s);
}
return true;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction,
Rect previouslyFocusedRect)
{
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
//Log.e("NavitGraphics", "FocusChange " + gainFocus);
}
@Override
public void run() {
if (in_map && touch_mode == PRESSED)
{
do_longpress_action();
touch_mode = NONE;
}
}
}
public NavitGraphics(final Activity activity, NavitGraphics parent, int x, int y, int w, int h,
int alpha, int wraparound, int use_camera)
{
if (parent == null)
{
this.activity = activity;
view = new NavitView(activity);
//activity.registerForContextMenu(view);
view.setClickable(false);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.setKeepScreenOn(true);
relativelayout = new RelativeLayout(activity);
if (use_camera != 0)
{
SetCamera(use_camera);
}
relativelayout.addView(view);
activity.setContentView(relativelayout);
view.requestFocus();
}
else
{
draw_bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap_w = w;
bitmap_h = h;
pos_x = x;
pos_y = y;
pos_wraparound = wraparound;
draw_canvas = new Canvas(draw_bitmap);
parent.overlays.add(this);
}
parent_graphics = parent;
}
static public enum msg_type {
CLB_ZOOM_IN, CLB_ZOOM_OUT, CLB_REDRAW, CLB_MOVE, CLB_BUTTON_UP, CLB_BUTTON_DOWN, CLB_SET_DESTINATION
, CLB_SET_DISPLAY_DESTINATION, CLB_CALL_CMD, CLB_COUNTRY_CHOOSER
};
static public msg_type[] msg_values = msg_type.values();
public Handler callback_handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg_values[msg.what])
{
case CLB_ZOOM_IN:
CallbackMessageChannel(1, "");
break;
case CLB_ZOOM_OUT:
CallbackMessageChannel(2, "");
break;
case CLB_MOVE:
MotionCallback(MotionCallbackID, msg.getData().getInt("x"), msg.getData().getInt("y"));
break;
case CLB_SET_DESTINATION:
String lat = msg.getData().getString("lat");
String lon = msg.getData().getString("lon");
String q = msg.getData().getString("q");
CallbackMessageChannel(3, lat + "#" + lon + "#" + q);
break;
case CLB_SET_DISPLAY_DESTINATION:
int x = msg.arg1;
int y = msg.arg2;
CallbackMessageChannel(4, "" + x + "#" + y);
break;
case CLB_CALL_CMD:
String cmd = msg.getData().getString("cmd");
CallbackMessageChannel(5, cmd);
break;
case CLB_BUTTON_UP:
ButtonCallback(ButtonCallbackID, 0, 1, msg.getData().getInt("x"), msg.getData().getInt("y")); // up
break;
case CLB_BUTTON_DOWN:
ButtonCallback(ButtonCallbackID, 1, 1, msg.getData().getInt("x"), msg.getData().getInt("y")); // down
break;
case CLB_COUNTRY_CHOOSER:
break;
}
}
};
public native void SizeChangedCallback(int id, int x, int y);
public native void KeypressCallback(int id, String s);
public native int CallbackMessageChannel(int i, String s);
public native void ButtonCallback(int id, int pressed, int button, int x, int y);
public native void MotionCallback(int id, int x, int y);
public native String GetDefaultCountry(int id, String s);
public static native String[][] GetAllCountries();
private Canvas draw_canvas;
private Bitmap draw_bitmap;
private int SizeChangedCallbackID, ButtonCallbackID, MotionCallbackID, KeypressCallbackID;
// private int count;
public void setSizeChangedCallback(int id)
{
SizeChangedCallbackID = id;
}
public void setButtonCallback(int id)
{
ButtonCallbackID = id;
}
public void setMotionCallback(int id)
{
MotionCallbackID = id;
Navit.setMotionCallback(id, this);
}
public void setKeypressCallback(int id)
{
KeypressCallbackID = id;
// set callback id also in main intent (for menus)
Navit.setKeypressCallback(id, this);
}
protected void draw_polyline(Paint paint, int c[])
{
// Log.e("NavitGraphics","draw_polyline");
paint.setStyle(Paint.Style.STROKE);
//paint.setAntiAlias(true);
//paint.setStrokeWidth(0);
Path path = new Path();
path.moveTo(c[0], c[1]);
for (int i = 2; i < c.length; i += 2)
{
path.lineTo(c[i], c[i + 1]);
}
//global_path.close();
draw_canvas.drawPath(path, paint);
}
protected void draw_polygon(Paint paint, int c[])
{
//Log.e("NavitGraphics","draw_polygon");
paint.setStyle(Paint.Style.FILL);
//paint.setAntiAlias(true);
//paint.setStrokeWidth(0);
Path path = new Path();
path.moveTo(c[0], c[1]);
for (int i = 2; i < c.length; i += 2)
{
path.lineTo(c[i], c[i + 1]);
}
//global_path.close();
draw_canvas.drawPath(path, paint);
}
protected void draw_rectangle(Paint paint, int x, int y, int w, int h)
{
//Log.e("NavitGraphics","draw_rectangle");
Rect r = new Rect(x, y, x + w, y + h);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
//paint.setStrokeWidth(0);
draw_canvas.drawRect(r, paint);
}
protected void draw_circle(Paint paint, int x, int y, int r)
{
//Log.e("NavitGraphics","draw_circle");
// float fx = x;
// float fy = y;
// float fr = r / 2;
paint.setStyle(Paint.Style.STROKE);
draw_canvas.drawCircle(x, y, r / 2, paint);
}
protected void draw_text(Paint paint, int x, int y, String text, int size, int dx, int dy)
{
// float fx = x;
// float fy = y;
//Log.e("NavitGraphics","Text size "+size + " vs " + paint.getTextSize());
paint.setTextSize(size / 15);
paint.setStyle(Paint.Style.FILL);
if (dx == 0x10000 && dy == 0)
{
draw_canvas.drawText(text, x, y, paint);
}
else
{
Path path = new Path();
path.moveTo(x, y);
path.rLineTo(dx, dy);
paint.setTextAlign(android.graphics.Paint.Align.LEFT);
draw_canvas.drawTextOnPath(text, path, 0, 0, paint);
}
}
protected void draw_image(Paint paint, int x, int y, Bitmap bitmap)
{
//Log.e("NavitGraphics","draw_image");
// float fx = x;
// float fy = y;
draw_canvas.drawBitmap(bitmap, x, y, paint);
}
protected void draw_mode(int mode)
{
//Log.e("NavitGraphics", "draw_mode mode=" + mode + " parent_graphics="
// + String.valueOf(parent_graphics));
if (mode == 2 && parent_graphics == null) view.invalidate();
if (mode == 1 || (mode == 0 && parent_graphics != null)) draw_bitmap.eraseColor(0);
}
protected void draw_drag(int x, int y)
{
//Log.e("NavitGraphics","draw_drag");
pos_x = x;
pos_y = y;
}
protected void overlay_disable(int disable)
{
Log.e("NavitGraphics","overlay_disable: " + disable + "Parent: " + (parent_graphics != null));
// assume we are NOT in map view mode!
if (parent_graphics == null)
in_map = (disable==0);
overlay_disabled = disable;
}
protected void overlay_resize(int x, int y, int w, int h, int alpha, int wraparond)
{
//Log.e("NavitGraphics","overlay_resize");
pos_x = x;
pos_y = y;
}
public static String getLocalizedString(String text)
{
String ret = CallbackLocalizedString(text);
//Log.e("NavitGraphics", "callback_handler -> lozalized string=" + ret);
return ret;
}
/**
* start a search on the map
*/
public void fillStringArray(String s)
{
// Log.e("NavitGraphics", "**** fillStringArray s=" + s);
// deactivate the spinner
NavitDialogs.NavitAddressSearchSpinnerActive = false;
Navit.Navit_Address_Result_Struct tmp_addr = new Navit_Address_Result_Struct();
String[] tmp_s = s.split(":");
tmp_addr.result_type = tmp_s[0];
tmp_addr.item_id = tmp_s[1];
tmp_addr.lat = Float.parseFloat(tmp_s[2]);
tmp_addr.lon = Float.parseFloat(tmp_s[3]);
// the rest ist address
tmp_addr.addr = s.substring(4 + tmp_s[0].length() + tmp_s[1].length() + tmp_s[2].length()
+ tmp_s[3].length(), s.length());
Navit.NavitAddressResultList_foundItems.add(tmp_addr);
if (tmp_addr.result_type.equals("TWN"))
{
Navit.search_results_towns++;
}
else if (tmp_addr.result_type.equals("STR"))
{
Navit.search_results_streets++;
}
else if (tmp_addr.result_type.equals("SHN"))
{
Navit.search_results_streets_hn++;
}
// make the dialog move its bar ...
NavitDialogs.sendDialogMessage( NavitDialogs.MSG_PROGRESS_BAR_SEARCH
, Navit.get_text("loading search results")
, Navit.get_text("towns") + ":" + Navit.search_results_towns + " "
+ Navit.get_text("Streets") + ":" + Navit.search_results_streets + "/"
+ Navit.search_results_streets_hn
, NavitDialogs.DIALOG_SEARCHRESULTS_WAIT
, Navit.ADDRESS_RESULTS_DIALOG_MAX
, Navit.NavitAddressResultList_foundItems.size() % (Navit.ADDRESS_RESULTS_DIALOG_MAX + 1));
}
public native void CallbackSearchResultList(int partial_match, String country, String s);
/**
* get localized string
*/
public static native String CallbackLocalizedString(String s);
}
| false | true | public boolean onTouchEvent(MotionEvent event)
{
//Log.e("NavitGraphics", "onTouchEvent");
super.onTouchEvent(event);
int x = (int) event.getX();
int y = (int) event.getY();
int _ACTION_POINTER_UP_ = getActionField("ACTION_POINTER_UP", event);
int _ACTION_POINTER_DOWN_ = getActionField("ACTION_POINTER_DOWN", event);
int _ACTION_MASK_ = getActionField("ACTION_MASK", event);
int switch_value = event.getAction();
if (_ACTION_MASK_ != -999)
{
switch_value = (event.getAction() & _ACTION_MASK_);
}
if (switch_value == MotionEvent.ACTION_DOWN)
{
touch_mode = PRESSED;
mPressedPosition = new PointF(x, y);
postDelayed(this, time_for_long_press);
}
else if ((switch_value == MotionEvent.ACTION_UP) || (switch_value == _ACTION_POINTER_UP_))
{
Log.e("NavitGraphics", "ACTION_UP");
if ( touch_mode == DRAG )
{
Log.e("NavitGraphics", "onTouch move");
MotionCallback(MotionCallbackID, x, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
}
else if (touch_mode == ZOOM)
{
//Log.e("NavitGraphics", "onTouch zoom");
float newDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
float scale = 0;
if (newDist > 10f)
{
scale = newDist / oldDist;
}
if (scale > 1.3)
{
// zoom in
CallbackMessageChannel(1, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom in");
}
else if (scale < 0.8)
{
// zoom out
CallbackMessageChannel(2, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom out");
}
}
else if (touch_mode == PRESSED)
{
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
}
touch_mode = NONE;
}
else if (switch_value == MotionEvent.ACTION_MOVE)
{
//Log.e("NavitGraphics", "ACTION_MOVE");
if (touch_mode == DRAG)
{
MotionCallback(MotionCallbackID, x, y);
}
else if (touch_mode == ZOOM)
{
float newDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
float scale = newDist / oldDist;
Log.e("NavitGraphics", "New scale = " + scale);
if (scale > 1.2)
{
// zoom in
CallbackMessageChannel(1, "");
oldDist = newDist;
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom in");
}
else if (scale < 0.8)
{
oldDist = newDist;
// zoom out
CallbackMessageChannel(2, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom out");
}
}
else if (touch_mode == PRESSED)
{
Log.e("NavitGraphics", "Start drag mode");
if ( spacing(mPressedPosition, new PointF(event.getX(), event.getY())) > 20f) {
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
touch_mode = DRAG;
}
}
}
else if (switch_value == _ACTION_POINTER_DOWN_)
{
//Log.e("NavitGraphics", "ACTION_POINTER_DOWN");
oldDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
if (oldDist > 2f)
{
touch_mode = ZOOM;
//Log.e("NavitGraphics", "--> zoom");
}
}
return true;
}
| public boolean onTouchEvent(MotionEvent event)
{
//Log.e("NavitGraphics", "onTouchEvent");
super.onTouchEvent(event);
int x = (int) event.getX();
int y = (int) event.getY();
int _ACTION_POINTER_UP_ = getActionField("ACTION_POINTER_UP", event);
int _ACTION_POINTER_DOWN_ = getActionField("ACTION_POINTER_DOWN", event);
int _ACTION_MASK_ = getActionField("ACTION_MASK", event);
int switch_value = event.getAction();
if (_ACTION_MASK_ != -999)
{
switch_value = (event.getAction() & _ACTION_MASK_);
}
if (switch_value == MotionEvent.ACTION_DOWN)
{
touch_mode = PRESSED;
if (!in_map) ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
mPressedPosition = new PointF(x, y);
postDelayed(this, time_for_long_press);
}
else if ((switch_value == MotionEvent.ACTION_UP) || (switch_value == _ACTION_POINTER_UP_))
{
Log.e("NavitGraphics", "ACTION_UP");
if ( touch_mode == DRAG )
{
Log.e("NavitGraphics", "onTouch move");
MotionCallback(MotionCallbackID, x, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
}
else if (touch_mode == ZOOM)
{
//Log.e("NavitGraphics", "onTouch zoom");
float newDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
float scale = 0;
if (newDist > 10f)
{
scale = newDist / oldDist;
}
if (scale > 1.3)
{
// zoom in
CallbackMessageChannel(1, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom in");
}
else if (scale < 0.8)
{
// zoom out
CallbackMessageChannel(2, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom out");
}
}
else if (touch_mode == PRESSED)
{
if (in_map) ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
}
touch_mode = NONE;
}
else if (switch_value == MotionEvent.ACTION_MOVE)
{
//Log.e("NavitGraphics", "ACTION_MOVE");
if (touch_mode == DRAG)
{
MotionCallback(MotionCallbackID, x, y);
}
else if (touch_mode == ZOOM)
{
float newDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
float scale = newDist / oldDist;
Log.e("NavitGraphics", "New scale = " + scale);
if (scale > 1.2)
{
// zoom in
CallbackMessageChannel(1, "");
oldDist = newDist;
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom in");
}
else if (scale < 0.8)
{
oldDist = newDist;
// zoom out
CallbackMessageChannel(2, "");
// next lines are a hack, without it screen will not get updated anymore!
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
MotionCallback(MotionCallbackID, x + 15, y);
MotionCallback(MotionCallbackID, x - 15, y);
ButtonCallback(ButtonCallbackID, 0, 1, x, y); // up
this.postInvalidate();
//Log.e("NavitGraphics", "onTouch zoom out");
}
}
else if (touch_mode == PRESSED)
{
Log.e("NavitGraphics", "Start drag mode");
if ( spacing(mPressedPosition, new PointF(event.getX(), event.getY())) > 20f) {
ButtonCallback(ButtonCallbackID, 1, 1, x, y); // down
touch_mode = DRAG;
}
}
}
else if (switch_value == _ACTION_POINTER_DOWN_)
{
//Log.e("NavitGraphics", "ACTION_POINTER_DOWN");
oldDist = spacing(getFloatValue(event, 0), getFloatValue(event, 1));
if (oldDist > 2f)
{
touch_mode = ZOOM;
//Log.e("NavitGraphics", "--> zoom");
}
}
return true;
}
|
diff --git a/modules/resin/src/com/caucho/cloud/bam/BamQueueFullHandler.java b/modules/resin/src/com/caucho/cloud/bam/BamQueueFullHandler.java
index 05df1a726..3a9971af4 100644
--- a/modules/resin/src/com/caucho/cloud/bam/BamQueueFullHandler.java
+++ b/modules/resin/src/com/caucho/cloud/bam/BamQueueFullHandler.java
@@ -1,125 +1,127 @@
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.cloud.bam;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import com.caucho.bam.QueueFullException;
import com.caucho.bam.mailbox.Mailbox;
import com.caucho.env.service.ResinSystem;
import com.caucho.env.shutdown.ExitCode;
import com.caucho.env.shutdown.ShutdownSystem;
import com.caucho.util.CurrentTime;
import com.caucho.util.L10N;
/**
* Handler for queue full messages.
*/
public class BamQueueFullHandler // implements QueueFullHandler
{
private static final Logger log
= Logger.getLogger(BamQueueFullHandler.class.getName());
private static final L10N L = new L10N(BamQueueFullHandler.class);
public static final BamQueueFullHandler DEFAULT = new BamQueueFullHandler(null);
private final ResinSystem _resinSystem;
private final long _duplicateTimeout = 60 * 1000L;
private final long _fatalTimeout = 180 * 1000L;
private final AtomicLong _lastExceptionTime = new AtomicLong();
private final AtomicLong _firstSequenceTime = new AtomicLong();
private final AtomicInteger _repeatCount = new AtomicInteger();
BamQueueFullHandler(ResinSystem resinSystem)
{
_resinSystem = resinSystem;
}
// @Override
public void onQueueFull(Mailbox service,
int queueSize,
long timeout,
TimeUnit unit,
Object message)
{
long lastExceptionTime = _lastExceptionTime.get();
long firstSequenceTime = _firstSequenceTime.get();
int repeatCount = _repeatCount.get();
long now = CurrentTime.getCurrentTime();
_lastExceptionTime.set(now);
if (now - lastExceptionTime < _duplicateTimeout) {
_repeatCount.incrementAndGet();
}
else {
_repeatCount.set(0);
_firstSequenceTime.set(now);
firstSequenceTime = now;
}
_lastExceptionTime.set(now);
String msg;
- msg = L.l("Queue full in service {0} with queue-size {1} timeout {2}ms message {3}",
+ msg = L.l("Queue full in service {0}: queue-size={1}, timeout={2}ms, start={3}, now={4}, message={5}",
service,
queueSize,
unit.toMillis(timeout),
+ firstSequenceTime,
+ now,
message);
if (repeatCount > 0) {
msg += L.l(" repeats {0} times.", repeatCount);
}
if (_fatalTimeout < now - firstSequenceTime) {
ShutdownSystem.shutdownActive(ExitCode.NETWORK, msg);
}
if (repeatCount % 100 == 0 || _repeatCount.get() == 0) {
log.warning(msg);
}
RuntimeException exn;
exn = new QueueFullException(msg);
throw exn;
}
}
| false | true | public void onQueueFull(Mailbox service,
int queueSize,
long timeout,
TimeUnit unit,
Object message)
{
long lastExceptionTime = _lastExceptionTime.get();
long firstSequenceTime = _firstSequenceTime.get();
int repeatCount = _repeatCount.get();
long now = CurrentTime.getCurrentTime();
_lastExceptionTime.set(now);
if (now - lastExceptionTime < _duplicateTimeout) {
_repeatCount.incrementAndGet();
}
else {
_repeatCount.set(0);
_firstSequenceTime.set(now);
firstSequenceTime = now;
}
_lastExceptionTime.set(now);
String msg;
msg = L.l("Queue full in service {0} with queue-size {1} timeout {2}ms message {3}",
service,
queueSize,
unit.toMillis(timeout),
message);
if (repeatCount > 0) {
msg += L.l(" repeats {0} times.", repeatCount);
}
if (_fatalTimeout < now - firstSequenceTime) {
ShutdownSystem.shutdownActive(ExitCode.NETWORK, msg);
}
if (repeatCount % 100 == 0 || _repeatCount.get() == 0) {
log.warning(msg);
}
RuntimeException exn;
exn = new QueueFullException(msg);
throw exn;
}
| public void onQueueFull(Mailbox service,
int queueSize,
long timeout,
TimeUnit unit,
Object message)
{
long lastExceptionTime = _lastExceptionTime.get();
long firstSequenceTime = _firstSequenceTime.get();
int repeatCount = _repeatCount.get();
long now = CurrentTime.getCurrentTime();
_lastExceptionTime.set(now);
if (now - lastExceptionTime < _duplicateTimeout) {
_repeatCount.incrementAndGet();
}
else {
_repeatCount.set(0);
_firstSequenceTime.set(now);
firstSequenceTime = now;
}
_lastExceptionTime.set(now);
String msg;
msg = L.l("Queue full in service {0}: queue-size={1}, timeout={2}ms, start={3}, now={4}, message={5}",
service,
queueSize,
unit.toMillis(timeout),
firstSequenceTime,
now,
message);
if (repeatCount > 0) {
msg += L.l(" repeats {0} times.", repeatCount);
}
if (_fatalTimeout < now - firstSequenceTime) {
ShutdownSystem.shutdownActive(ExitCode.NETWORK, msg);
}
if (repeatCount % 100 == 0 || _repeatCount.get() == 0) {
log.warning(msg);
}
RuntimeException exn;
exn = new QueueFullException(msg);
throw exn;
}
|
diff --git a/PolicyProviderImpl/src/main/java/org/ebayopensource/turmeric/policyservice/model/RuleDAOImpl.java b/PolicyProviderImpl/src/main/java/org/ebayopensource/turmeric/policyservice/model/RuleDAOImpl.java
index ddfc913..be11f80 100644
--- a/PolicyProviderImpl/src/main/java/org/ebayopensource/turmeric/policyservice/model/RuleDAOImpl.java
+++ b/PolicyProviderImpl/src/main/java/org/ebayopensource/turmeric/policyservice/model/RuleDAOImpl.java
@@ -1,274 +1,274 @@
/*******************************************************************************
* Copyright (c) 2006-2010 eBay Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package org.ebayopensource.turmeric.policyservice.model;
import org.ebayopensource.turmeric.utils.jpa.AbstractDAO;
/**
* The Class RuleDAOImpl.
*
* @author muguerza
*/
public class RuleDAOImpl extends AbstractDAO implements RuleDAO {
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#persistRule(org.ebayopensource.turmeric.policyservice.model.Rule)
*/
@Override
public void persistRule(Rule rule) {
persistEntity(rule);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#persistCondition(org.ebayopensource.turmeric.policyservice.model.Condition)
*/
@Override
public void persistCondition(Condition condition) {
persistEntity(condition);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#persistExpression(org.ebayopensource.turmeric.policyservice.model.Expression)
*/
@Override
public void persistExpression(Expression expression) {
persistEntity(expression);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#persistPrimitiveValue(org.ebayopensource.turmeric.policyservice.model.PrimitiveValue)
*/
@Override
public void persistPrimitiveValue(PrimitiveValue primitiveValue) {
persistEntity(primitiveValue);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findRuleById(long)
*/
@Override
public Rule findRuleById(long id) {
return findEntity(Rule.class, id);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findConditionById(long)
*/
@Override
public Condition findConditionById(long conditionId) {
return findEntity(Condition.class, conditionId);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findExpressionById(long)
*/
@Override
public Expression findExpressionById(long expressionId) {
return findEntity(Expression.class, expressionId);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findPrimitiveValueById(long)
*/
@Override
public PrimitiveValue findPrimitiveValueById(long primitiveValueId) {
return findEntity(PrimitiveValue.class, primitiveValueId);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findConditionByRuleId(long)
*/
@Override
public Condition findConditionByRuleId(long ruleId) {
Rule rule = findRuleById(ruleId);
if (rule != null && rule.getCondition() != null) {
return rule.getCondition();
}
return null;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findExpressionByConditionId(long)
*/
@Override
public Expression findExpressionByConditionId(long conditionId) {
Condition condition = findConditionById(conditionId);
if (condition != null && condition.getExpression() != null) {
return condition.getExpression();
}
return null;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findPrimitiveValueByExpressionId(long)
*/
@Override
public PrimitiveValue findPrimitiveValueByExpressionId(long expressionId) {
Expression expression = findExpressionById(expressionId);
if (expression != null && expression.getPrimitiveValue() != null) {
return expression.getPrimitiveValue();
}
return null;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findExpressionByName(java.lang.String)
*/
@Override
public Expression findExpressionByName(String expressionName) {
return getSingleResultOrNull(Expression.class, "name", expressionName);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#removeRule(long)
*/
@Override
public void removeRule(long ruleId) {
removeEntity(Rule.class, ruleId);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#removePrimitiveValue(long)
*/
@Override
public void removePrimitiveValue(long primitiveValueId) {
removeEntity(PrimitiveValue.class, primitiveValueId);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#findRuleByName(java.lang.String)
*/
@Override
public Rule findRuleByName(String name) {
return getSingleResultOrNull(Rule.class, "ruleName", name);
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#isRuleNameUsed(java.lang.String)
*/
@Override
public boolean isRuleNameUsed(String ruleName) {
return findRuleByName(ruleName) != null;
}
/* (non-Javadoc)
* @see org.ebayopensource.turmeric.policyservice.model.RuleDAO#isRuleValid(org.ebayopensource.turmeric.policyservice.model.Rule, boolean)
*/
@Override
public boolean isRuleValid(Rule rule,boolean allowNull) {
// value should not be null as well as the type
// rulename required
boolean valid = false;
if(rule != null
&& rule.getCondition() != null
&& rule.getCondition().getExpression() != null
&& rule.getCondition().getExpression().getPrimitiveValue() != null
&& rule.getCondition().getExpression().getPrimitiveValue() != null
&& rule.getCondition().getExpression().getPrimitiveValue()
.getValue() != null
&& rule.getCondition().getExpression().getPrimitiveValue()
.getValue().length() > 0
&& rule.getCondition().getExpression().getPrimitiveValue()
.getType() != null
&& (rule.getRuleName() != null || rule.getRuleName().length() != 0)
){
String conditionRule = rule.getCondition().getExpression().getPrimitiveValue().getValue();
valid = isValidStructure(conditionRule);
}
return valid;
}
private boolean isValidStructure(final String conditionRule) {
boolean flag = true;
if (conditionRule != null) {
String[] operands;
if (conditionRule.contains("||")) {
operands = conditionRule.split("\\|\\|");
for (String operand : operands) {
operand = operand.trim();
- if ( ! (operand.trim().matches("\\w+(:\\w+)?.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("\\w+:\\w+.SubjectGroup.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("\\w+:hits[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("HITS[>,<,==,=>,>=,<=,=<][0-9]+")) ||
+ if ( ! (operand.trim().matches("\\w+(:\\w+)?.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("\\w+:\\w+.SubjectGroup.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("\\w+:hits(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("HITS(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+")) ||
! isValidCondition(operand)) {
return false;
}
}
}else{
if (conditionRule.contains("&&")) {
operands = conditionRule.split("\\&\\&");
for (String operand : operands) {
operand = operand.trim();
- if ( ! (operand.trim().matches("\\w+(:\\w+)?.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("\\w+:\\w+.SubjectGroup.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("\\w+:hits[>,<,==,=>,>=,<=,=<][0-9]+") ||
- operand.trim().matches("HITS[>,<,==,=>,>=,<=,=<][0-9]+")) ||
+ if ( ! (operand.trim().matches("\\w+(:\\w+)?.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("\\w+:\\w+.SubjectGroup.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("\\w+:hits(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ operand.trim().matches("HITS(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+")) ||
! isValidCondition(operand)) {
return false;
}
}
- }else if ( ! (conditionRule.trim().matches("\\w+(:\\w+)?.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
- conditionRule.trim().matches("\\w+:hits[>,<,==,=>,>=,<=,=<][0-9]+") ||
- conditionRule.trim().matches("HITS[>,<,==,=>,>=,<=,=<][0-9]+")) ||
+ }else if ( ! (conditionRule.trim().matches("\\w+(:\\w+)?.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ conditionRule.trim().matches("\\w+:hits(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
+ conditionRule.trim().matches("HITS(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+")) ||
! isValidCondition(conditionRule)) {
return false;
}
}
}
return flag;
}
private boolean isValidCondition(final String value) {
boolean flag =false;
if( value!=null ){
String[] expression = {">","<" ,"==" ,"=>",">=","<=","=<"};
String[] words;
for(String val:expression){
if(value ==null){
break;
}
if (value.contains(val)) {
words = value.split(val);
if(words[1]!=null){
words[1] = words[1].trim();
}
if(words[0]!=null){
words[0] = words[0].trim();
}
try{
Integer.valueOf(words[0]);
flag = true;
}catch (NumberFormatException e) {
try{
Integer.valueOf(words[1].trim());
flag = true;
}catch (NumberFormatException e1) {
}
}
}
}
}
return flag;
}
}
| false | true | private boolean isValidStructure(final String conditionRule) {
boolean flag = true;
if (conditionRule != null) {
String[] operands;
if (conditionRule.contains("||")) {
operands = conditionRule.split("\\|\\|");
for (String operand : operands) {
operand = operand.trim();
if ( ! (operand.trim().matches("\\w+(:\\w+)?.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("\\w+:hits[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("HITS[>,<,==,=>,>=,<=,=<][0-9]+")) ||
! isValidCondition(operand)) {
return false;
}
}
}else{
if (conditionRule.contains("&&")) {
operands = conditionRule.split("\\&\\&");
for (String operand : operands) {
operand = operand.trim();
if ( ! (operand.trim().matches("\\w+(:\\w+)?.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("\\w+:hits[>,<,==,=>,>=,<=,=<][0-9]+") ||
operand.trim().matches("HITS[>,<,==,=>,>=,<=,=<][0-9]+")) ||
! isValidCondition(operand)) {
return false;
}
}
}else if ( ! (conditionRule.trim().matches("\\w+(:\\w+)?.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count[>,<,==,=>,>=,<=,=<][0-9]+") ||
conditionRule.trim().matches("\\w+:hits[>,<,==,=>,>=,<=,=<][0-9]+") ||
conditionRule.trim().matches("HITS[>,<,==,=>,>=,<=,=<][0-9]+")) ||
! isValidCondition(conditionRule)) {
return false;
}
}
}
return flag;
}
| private boolean isValidStructure(final String conditionRule) {
boolean flag = true;
if (conditionRule != null) {
String[] operands;
if (conditionRule.contains("||")) {
operands = conditionRule.split("\\|\\|");
for (String operand : operands) {
operand = operand.trim();
if ( ! (operand.trim().matches("\\w+(:\\w+)?.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("\\w+:hits(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("HITS(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+")) ||
! isValidCondition(operand)) {
return false;
}
}
}else{
if (conditionRule.contains("&&")) {
operands = conditionRule.split("\\&\\&");
for (String operand : operands) {
operand = operand.trim();
if ( ! (operand.trim().matches("\\w+(:\\w+)?.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("\\w+:hits(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
operand.trim().matches("HITS(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+")) ||
! isValidCondition(operand)) {
return false;
}
}
}else if ( ! (conditionRule.trim().matches("\\w+(:\\w+)?.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
conditionRule.trim().matches("\\w+:\\w+.SubjectGroup.Subject.count(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
conditionRule.trim().matches("\\w+:hits(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+") ||
conditionRule.trim().matches("HITS(\\s)?(>=|==|<|=>|>|<=|=<)(\\s)?[0-9]+")) ||
! isValidCondition(conditionRule)) {
return false;
}
}
}
return flag;
}
|
diff --git a/src/com/difane/games/ticktacktoe/GameFSM.java b/src/com/difane/games/ticktacktoe/GameFSM.java
index 8fae355..ec8404f 100644
--- a/src/com/difane/games/ticktacktoe/GameFSM.java
+++ b/src/com/difane/games/ticktacktoe/GameFSM.java
@@ -1,1056 +1,1057 @@
package com.difane.games.ticktacktoe;
import com.difane.games.ticktacktoe.exceptions.GameBoardImpossibleException;
import com.difane.games.ticktacktoe.exceptions.GameBoardLineLengthException;
import com.difane.games.ticktacktoe.exceptions.GameBoardLinePointsCountException;
import com.difane.games.ticktacktoe.exceptions.GameBoardLinePositionException;
import com.difane.games.ticktacktoe.exceptions.GameBoardLineRequirementsException;
import com.livescribe.afp.PageInstance;
import com.livescribe.display.BrowseList;
import com.livescribe.event.HWRListener;
import com.livescribe.event.StrokeListener;
import com.livescribe.geom.Point;
import com.livescribe.geom.PolyLine;
import com.livescribe.geom.Rectangle;
import com.livescribe.geom.Stroke;
import com.livescribe.icr.ICRContext;
import com.livescribe.icr.Resource;
import com.livescribe.penlet.Region;
import com.livescribe.storage.StrokeStorage;
public class GameFSM implements StrokeListener, HWRListener {
/*
* DI Container
*/
private Container container;
/*
* Available game states
*/
static public final int FSM_STATE_UNDEFINED = -1;
static public final int FSM_STATE_START = 0;
static public final int FSM_STATE_MAIN_MENU_START_GAME = 1;
static public final int FSM_STATE_MAIN_MENU_HELP = 2;
static public final int FSM_STATE_HELP_MENU_RULES = 3;
static public final int FSM_STATE_HELP_MENU_RULES_DISPLAYED = 4;
static public final int FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD = 5;
static public final int FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED = 6;
static public final int FSM_STATE_HELP_MENU_HOW_TO_PLAY = 7;
static public final int FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED = 8;
static public final int FSM_STATE_MAIN_MENU_ABOUT = 9;
static public final int FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED = 10;
static public final int FSM_STATE_LEVEL_MENU_EASY = 11;
static public final int FSM_STATE_LEVEL_MENU_HARD = 12;
static public final int FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE = 13;
static public final int FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE = 14;
static public final int FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE = 15;
static public final int FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE = 16;
static public final int FSM_STATE_GAME_SELECT_PLAYER_ORDER = 17;
static public final int FSM_STATE_GAME_HUMAN_TURN = 18;
static public final int FSM_STATE_GAME_PEN_TURN = 19;
static public final int FSM_STATE_GAME_END_HUMAN_WINS = 20;
static public final int FSM_STATE_GAME_END_PEN_WINS = 21;
static public final int FSM_STATE_GAME_END_DRAW = 22;
static public final int FSM_STATE_END = 23;
/**
* Current game state
*/
private int currentState = FSM_STATE_UNDEFINED;
/**
* Context for an ICR
*/
protected ICRContext icrContext;
/**
* Next event, that must be handled after transition
*/
private int nextEvent = NEXT_EVENT_NONE;
/*
* Available next events, that can be handled diring and right after
* transition
*/
static public final int NEXT_EVENT_NONE = -1;
static public final int NEXT_EVENT_PLAYER_SELECTED_HUMAN_TURN_NEXT = 0;
static public final int NEXT_EVENT_PLAYER_SELECTED_PEN_TURN_NEXT = 1;
static public final int NEXT_EVENT_GAME_PEN_TURN_READY = 2;
static public final int NEXT_EVENT_GAME_END_HUMAN_WINS = 3;
static public final int NEXT_EVENT_GAME_END_PEN_WINS = 4;
static public final int NEXT_EVENT_GAME_END_DRAW = 5;
static public final int NEXT_EVENT_END = 6;
/**
* Constructor
*/
public GameFSM(Container c) {
this.container = c;
this.currentState = FSM_STATE_START;
this.getContainer()
.getLoggerComponent()
.debug("[GameFSM] Component initialized");
}
/**
* This event must be called, when application will be started. It will try
* to start application by displaying it's main menu
*/
public void eventStartApplication() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventStartApplication received");
initializeICRContext();
transition(currentState, FSM_STATE_MAIN_MENU_START_GAME);
}
/**
* This event must be called, when DOWN in the menu be pressed
*/
public boolean eventMenuDown() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventMenuDown received");
switch (currentState) {
case FSM_STATE_MAIN_MENU_START_GAME:
transition(currentState, FSM_STATE_MAIN_MENU_HELP);
break;
case FSM_STATE_MAIN_MENU_HELP:
transition(currentState, FSM_STATE_MAIN_MENU_ABOUT);
break;
case FSM_STATE_HELP_MENU_RULES:
transition(currentState, FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD);
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
transition(currentState, FSM_STATE_HELP_MENU_HOW_TO_PLAY);
break;
case FSM_STATE_LEVEL_MENU_EASY:
transition(currentState, FSM_STATE_LEVEL_MENU_HARD);
break;
default:
this.getContainer().getLoggerComponent().warn("[GameFSM] Unexpected eventMenuDown received");
}
// Menu down are always handled
return true;
}
/**
* This event must be called, when UP in the menu be pressed
*/
public boolean eventMenuUp() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventMenuUp received");
switch (currentState) {
case FSM_STATE_MAIN_MENU_HELP:
transition(currentState, FSM_STATE_MAIN_MENU_START_GAME);
break;
case FSM_STATE_MAIN_MENU_ABOUT:
transition(currentState, FSM_STATE_MAIN_MENU_HELP);
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
transition(currentState, FSM_STATE_HELP_MENU_RULES);
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY:
transition(currentState, FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD);
break;
case FSM_STATE_LEVEL_MENU_HARD:
transition(currentState, FSM_STATE_LEVEL_MENU_EASY);
break;
default:
this.getContainer().getLoggerComponent().warn("[GameFSM] Unexpected eventMenuUp received");
}
// Menu up are always handled
return true;
}
/**
* This event must be called, when LEFT in the menu be pressed
*/
public boolean eventMenuLeft() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventMenuLeft received");
boolean result = false;
switch (currentState) {
case FSM_STATE_LEVEL_MENU_EASY:
case FSM_STATE_LEVEL_MENU_HARD:
transition(currentState, FSM_STATE_MAIN_MENU_START_GAME);
result = true;
break;
case FSM_STATE_HELP_MENU_RULES:
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
case FSM_STATE_HELP_MENU_HOW_TO_PLAY:
transition(currentState, FSM_STATE_MAIN_MENU_HELP);
result = true;
break;
case FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED:
transition(currentState, FSM_STATE_MAIN_MENU_ABOUT);
result = true;
break;
case FSM_STATE_HELP_MENU_RULES_DISPLAYED:
transition(currentState, FSM_STATE_HELP_MENU_RULES);
result = true;
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED:
transition(currentState, FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD);
result = true;
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED:
transition(currentState, FSM_STATE_HELP_MENU_HOW_TO_PLAY);
result = true;
break;
default:
result = false;
this.getContainer().getLoggerComponent().warn("[GameFSM] Unexpected eventMenuLeft received");
}
return result;
}
/**
* This event must be called, when RIGHT in the menu be pressed
*/
public boolean eventMenuRight() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventMenuRight received");
switch (currentState) {
case FSM_STATE_MAIN_MENU_START_GAME:
transition(currentState, FSM_STATE_LEVEL_MENU_EASY);
break;
case FSM_STATE_MAIN_MENU_HELP:
transition(currentState, FSM_STATE_HELP_MENU_RULES);
break;
case FSM_STATE_MAIN_MENU_ABOUT:
transition(currentState, FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED);
break;
case FSM_STATE_HELP_MENU_RULES:
transition(currentState, FSM_STATE_HELP_MENU_RULES_DISPLAYED);
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
transition(currentState,
FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED);
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY:
transition(currentState, FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED);
break;
case FSM_STATE_LEVEL_MENU_EASY:
this.getContainer().getGameLogicComponent().setAiLevel(GameLogic.AI_LEVEL_EASY);
transition(currentState, FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE);
break;
case FSM_STATE_LEVEL_MENU_HARD:
this.getContainer().getGameLogicComponent().setAiLevel(GameLogic.AI_LEVEL_HARD);
transition(currentState, FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE);
break;
default:
this.getContainer().getLoggerComponent().warn("[GameFSM] Unexpected eventMenuRight received");
}
// Menu right are always handled
return true;
}
/**
* This event must be called, when first board vertical line be ready
*/
public void eventFirstVerticalLineReady() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventFirstVerticalLineReady received");
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE) {
transition(currentState, FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE);
}
}
/**
* This event must be called, when second board vertical line be ready
*/
public void eventSecondVerticalLineReady() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventSecondVerticalLineReady received");
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE) {
transition(currentState, FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE);
}
}
/**
* This event must be called, when first board horizontal line be ready
*/
public void eventFirstHorizontalLineReady() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventFirstHorizontalLineReady received");
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE) {
transition(currentState,
FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE);
}
}
/**
* This event must be called, when second board horizontal line be ready
*/
public void eventSecondHorizontalLineReady() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventSecondHorizontalLineReady received");
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE) {
transition(currentState, FSM_STATE_GAME_SELECT_PLAYER_ORDER);
}
}
/**
* This event must be called, when player order is selected and next turn is
* human's
*/
public void eventPlayerSelectedHumanTurnNext() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventPlayerSelectedHumanTurnNext received");
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER) {
this.getContainer().getGameDisplayComponent().displayHumanStartsGame();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// If no sleep will made - it is not error at this time
}
this.transition(currentState, FSM_STATE_GAME_HUMAN_TURN);
}
}
/**
* This event must be called, when player order is selected and next turn is
* pen's
*/
public void eventPlayerSelectedPenTurnNext() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventPlayerSelectedPenTurnNext received");
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER) {
this.getContainer().getGameDisplayComponent().displayPenStartsGame();
this.transition(currentState, FSM_STATE_GAME_PEN_TURN);
}
}
/**
* This event must be called, when player makes his turn
*/
public void eventHumanTurnReady() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventHumanTurnReady received");
if (currentState == FSM_STATE_GAME_HUMAN_TURN) {
this.transition(currentState, FSM_STATE_GAME_PEN_TURN);
}
}
/**
* This event must be called, when pen makes his turn
*/
public void eventPenTurnReady() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventPenTurnReady received");
if (currentState == FSM_STATE_GAME_PEN_TURN) {
this.transition(currentState, FSM_STATE_GAME_HUMAN_TURN);
}
}
/**
* This event must be called, when game ends and human wins
*/
public void eventHumanWins() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventHumanWins received");
if (currentState == FSM_STATE_GAME_HUMAN_TURN) {
this.transition(currentState, FSM_STATE_GAME_END_HUMAN_WINS);
} else {
this.getContainer().getLoggerComponent()
.error("[GameFSM] Impossible situation - human wins without making a turn");
}
}
/**
* This event must be called, when game ends and pen wins
*/
public void eventPenWins() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventPenWins received");
// Pen can win during human turn also
if (currentState == FSM_STATE_GAME_PEN_TURN
|| currentState == FSM_STATE_GAME_HUMAN_TURN) {
this.transition(currentState, FSM_STATE_GAME_END_PEN_WINS);
} else {
this.getContainer().getLoggerComponent()
.error("[GameFSM] Impossible situation - pen wins without making a turn");
}
}
/**
* This event must be called, when game ends and draw appears
*/
public void eventDraw() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventDraw received");
if (currentState == FSM_STATE_GAME_HUMAN_TURN
|| currentState == FSM_STATE_GAME_PEN_TURN) {
this.transition(currentState, FSM_STATE_GAME_END_DRAW);
}
}
/**
* This event ends application
*/
public void eventEndApplication() {
this.getContainer().getLoggerComponent().debug("[GameFSM] eventEndApplication received");
this.destroyICRContext();
if (currentState == FSM_STATE_GAME_END_HUMAN_WINS
|| currentState == FSM_STATE_GAME_END_PEN_WINS
|| currentState == FSM_STATE_GAME_END_DRAW) {
this.transition(currentState, FSM_STATE_END);
}
}
private void transition(int currentState, int transitionState) {
this.getContainer().getLoggerComponent().debug("[GameFSM] ---> transition started ( " + currentState
+ " -> " + transitionState + " )");
try {
switch (transitionState) {
case FSM_STATE_MAIN_MENU_START_GAME:
if (currentState == FSM_STATE_START
|| currentState == FSM_STATE_LEVEL_MENU_EASY
|| currentState == FSM_STATE_LEVEL_MENU_HARD) {
// Select "Help" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(0);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 0");
} else if (currentState == FSM_STATE_MAIN_MENU_HELP) {
// Main menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusMainMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 0 was activated");
}
break;
case FSM_STATE_MAIN_MENU_HELP:
if (currentState == FSM_STATE_MAIN_MENU_START_GAME) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusMainMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 1 was activated");
} else if (currentState == FSM_STATE_MAIN_MENU_ABOUT) {
// Main menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusMainMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 1 was activated");
} else if (currentState == FSM_STATE_HELP_MENU_RULES
|| currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD
|| currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
// Select "Help" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(1);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 1");
}
break;
case FSM_STATE_MAIN_MENU_ABOUT:
if (currentState == FSM_STATE_MAIN_MENU_HELP) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusMainMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 2 was activated");
} else if (currentState == FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED) {
// Select "About" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(2);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 2");
}
break;
case FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED:
if (currentState == FSM_STATE_MAIN_MENU_ABOUT) {
this.getContainer().getGameDisplayComponent().displayAbout();
this.getContainer().getLoggerComponent().debug("[GameFSM] About was displayed");
}
break;
case FSM_STATE_LEVEL_MENU_EASY:
if (currentState == FSM_STATE_MAIN_MENU_START_GAME) {
// Select "Easy" in the level select menu, if not selected
this.getContainer().getGameDisplayComponent().selectLevelSelectMenuItemIfNotSelected(0);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayLevelSelectMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu was displayed");
} else if (currentState == FSM_STATE_LEVEL_MENU_HARD) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusLevelSelectMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu item 0 was activated");
}
break;
case FSM_STATE_LEVEL_MENU_HARD:
if (currentState == FSM_STATE_LEVEL_MENU_EASY) {
this.getContainer().getGameDisplayComponent().focusLevelSelectMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu item 1 was activated");
}
break;
case FSM_STATE_HELP_MENU_RULES:
if (currentState == FSM_STATE_MAIN_MENU_HELP
|| currentState == FSM_STATE_HELP_MENU_RULES_DISPLAYED) {
// Select "Rules" in the help menu, if not selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(0);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
// Help menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusHelpMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 0 was activated");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED) {
// Select "How to draw board" in the help menu, if not
// selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(1);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_RULES) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 1 was activated");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 1 was activated");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED) {
// Select "How to play" in the help menu, if not selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(2);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 2 was activated");
}
break;
case FSM_STATE_HELP_MENU_RULES_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_RULES) {
this.getContainer().getGameDisplayComponent().displayRules();
this.getContainer().getLoggerComponent().debug("[GameFSM] Rules was displayed");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
this.getContainer().getGameDisplayComponent().displayHowToDrawBoard();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] How to draw board was displayed");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
this.getContainer().getGameDisplayComponent().displayHowToPlay();
this.getContainer().getLoggerComponent().debug("[GameFSM] How to play was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE:
if (currentState == FSM_STATE_LEVEL_MENU_EASY
|| currentState == FSM_STATE_LEVEL_MENU_HARD) {
this.getContainer().getGameDisplayComponent().displayDrawFirstVerticalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw first vertical line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawSecondVerticalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw second vertical line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawFirstHorizontalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw first horizontal line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawSecondHorizontalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw second horizontal line was displayed");
}
break;
case FSM_STATE_GAME_SELECT_PLAYER_ORDER:
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE) {
boolean humanFirst = this.getContainer()
.getGameLogicComponent().selectPlayersOrder();
if (humanFirst) {
this.setNextEvent(NEXT_EVENT_PLAYER_SELECTED_HUMAN_TURN_NEXT);
} else {
this.setNextEvent(NEXT_EVENT_PLAYER_SELECTED_PEN_TURN_NEXT);
}
}
break;
case FSM_STATE_GAME_HUMAN_TURN:
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER
|| currentState == FSM_STATE_GAME_PEN_TURN) {
// 1. Checking, that game is not end
if (this.checkGameStatus()) {
// 2. Redrawing board with text "Your turn"
this.getContainer().getGameDisplayComponent().redrawBoard(true);
}
}
break;
case FSM_STATE_GAME_PEN_TURN:
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER
|| currentState == FSM_STATE_GAME_HUMAN_TURN) {
// 1. Checking, that game is not end
if (this.checkGameStatus()) {
// 2. Redrawing board with text "Your turn"
this.getContainer().getGameDisplayComponent().redrawBoard(false);
// 3. Performing pen turn;
this.getContainer().getGameLogicComponent().aiTurn();
this.setNextEvent(NEXT_EVENT_GAME_PEN_TURN_READY);
}
}
break;
case FSM_STATE_GAME_END_HUMAN_WINS:
this.getContainer().getGameDisplayComponent().displayHumanWins();
this.getContainer().getLoggerComponent().debug("[GameFSM] Human wins was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_GAME_END_PEN_WINS:
this.getContainer().getGameDisplayComponent().displayPenWins();
this.getContainer().getLoggerComponent().debug("[GameFSM] Pen wins was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_GAME_END_DRAW:
this.getContainer().getGameDisplayComponent().displayDraw();
this.getContainer().getLoggerComponent().debug("[GameFSM] Draw was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_END:
this.getContainer().getGameDisplayComponent().displayEnd();
this.getContainer().getLoggerComponent().debug("[GameFSM] Game end reached");
+ break;
default:
// Unrecognized target state. Rejecting it
this.getContainer().getLoggerComponent().warn("[GameFSM] Unrecognized target state: "
+ transitionState);
return;
} // switch (transitionState)
this.currentState = transitionState;
} catch (Exception e) {
this.getContainer().getLoggerComponent().error("[GameFSM] Exception appears: " + e);
}
this.getContainer().getLoggerComponent().debug("[GameFSM] Starting processing next event");
this.processNextEvent();
this.getContainer().getLoggerComponent().debug("[GameFSM] Next event was processed");
this.getContainer().getLoggerComponent().debug("[GameFSM] <--- transition");
}
/**
* Checks game status and forwards to the corresponded state, if game
* completed
* @return false, if game status changed and game end, true otherwise
*/
private boolean checkGameStatus() {
int status = this.getContainer().getGameLogicComponent().getGameStatus();
this.getContainer().getLoggerComponent().debug("[GameFSM].checkGameStatus. Game status is: "
+ status + ". Current state is" + currentState);
boolean result = true;
switch (status) {
case GameLogic.GAME_STATUS_X_WINS:
this.getContainer().getLoggerComponent().debug("[GameFSM].checkGameStatus. 'X' player wins");
if (this.getContainer().getGameLogicComponent().getHumanType() == GameLogic.FIELD_X) {
this.getContainer().getLoggerComponent()
.debug("[GameFSM].checkGameStatus. 'X' was played by human. Human wins");
// Human wins
this.setNextEvent(NEXT_EVENT_GAME_END_HUMAN_WINS);
} else {
this.getContainer().getLoggerComponent()
.debug("[GameFSM].checkGameStatus. 'X' was played by pen. Pen wins");
// Pen wins
this.setNextEvent(NEXT_EVENT_GAME_END_PEN_WINS);
}
result = false;
break;
case GameLogic.GAME_STATUS_O_WINS:
this.getContainer().getLoggerComponent().debug("[GameFSM].checkGameStatus. 'O' player wins");
if (this.getContainer().getGameLogicComponent().getHumanType() == GameLogic.FIELD_O) {
this.getContainer().getLoggerComponent()
.debug("[GameFSM].checkGameStatus. 'O' was played by human. Human wins");
// Human wins
this.setNextEvent(NEXT_EVENT_GAME_END_HUMAN_WINS);
} else {
this.getContainer().getLoggerComponent()
.debug("[GameFSM].checkGameStatus. 'O' was played by pen. Pen wins");
// Pen wins
this.setNextEvent(NEXT_EVENT_GAME_END_PEN_WINS);
}
result = false;
break;
case GameLogic.GAME_STATUS_DRAW:
this.getContainer().getLoggerComponent().debug("[GameFSM].checkGameStatus. Game draw");
this.setNextEvent(NEXT_EVENT_GAME_END_DRAW);
result = false;
break;
default:
this.getContainer().getLoggerComponent()
.debug("[GameFSM].checkGameStatus. Game is not completed yet");
// Game continues. Do nothing
result = true;
break;
}
return result;
}
public void strokeCreated(long time, Region region,
PageInstance pageInstance) {
this.getContainer().getLoggerComponent()
.debug("[GameFSM] New stroke was created. Current state: "
+ this.currentState);
PolyLine line = null;
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE
|| currentState == FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE
|| currentState == FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE
|| currentState == FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE) {
this.getContainer().getLoggerComponent().debug("[GameFSM] Trying to get line from stroke");
StrokeStorage ss = new StrokeStorage(pageInstance);
Stroke stroke = ss.getStroke(time);
// Create a line, based on the first and last points of the stroke
int numPoints = stroke.getNumberofVertices();
this.getContainer().getLoggerComponent().debug("[GameFSM] Number of vertices in the stroke is "
+ numPoints);
if (numPoints >= 2) {
line = new PolyLine(2);
line.setXY(0, stroke.getX(0), stroke.getY(0));
line.setXY(1, stroke.getX(numPoints - 1), stroke
.getY(numPoints - 1));
this.getContainer().getLoggerComponent().debug("[GameFSM] Creating line from two points: "+line);
}
}
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE) {
try {
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Trying to use this line as first vertical line");
this.getContainer().getGameBoardComponent().setFirstVerticalLine(line);
this.getContainer().getLoggerComponent()
.debug("[GameFSM] First vertical line was successfully created");
this.eventFirstVerticalLineReady();
} catch (GameBoardLinePointsCountException e) {
// TODO Auto-generated catch block
this.getContainer().getLoggerComponent().error("GameBoardLinePointsCountException");
this.getContainer().getGameDisplayComponent().displayErrorDrawFirstVerticalLine();
} catch (GameBoardLineLengthException e) {
// TODO Auto-generated catch block
this.getContainer().getLoggerComponent()
.error("GameBoardLineLengthException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawFirstVerticalLine();
}
} else if (currentState == FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE) {
try {
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Trying to use this line as second vertical line");
this.getContainer().getGameBoardComponent().setSecondVerticalLine(line);
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Second vertical line was successfully created");
this.eventSecondVerticalLineReady();
} catch (GameBoardLinePointsCountException e) {
// TODO Auto-generated catch block
this.getContainer().getLoggerComponent().error("GameBoardLinePointsCountException");
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondVerticalLine();
} catch (GameBoardLineRequirementsException e) {
// TODO Auto-generated catch block
this.getContainer().getLoggerComponent().error("GameBoardLineRequirementsException");
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondVerticalLine();
} catch (GameBoardLineLengthException e) {
// TODO Auto-generated catch block
this.getContainer().getLoggerComponent()
.error("GameBoardLineLengthException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondVerticalLine();
} catch (GameBoardLinePositionException e) {
// TODO Auto-generated catch block
this.getContainer().getLoggerComponent()
.error("GameBoardLinePositionException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondVerticalLine();
}
} else if (currentState == FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE) {
try {
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Trying to use this line as first horizontal line");
this.getContainer().getGameBoardComponent().setFirstHorizontalLine(line);
this.getContainer().getLoggerComponent()
.debug("[GameFSM] First horizontal line was successfully created");
this.eventFirstHorizontalLineReady();
} catch (GameBoardLineRequirementsException e) {
this.getContainer().getLoggerComponent().error("GameBoardLineRequirementsException");
this.getContainer().getGameDisplayComponent().displayErrorDrawFirstHorizontalLine();
} catch (GameBoardLinePointsCountException e) {
this.getContainer().getLoggerComponent().error("GameBoardLinePointsCountException");
this.getContainer().getGameDisplayComponent().displayErrorDrawFirstHorizontalLine();
} catch (GameBoardLinePositionException e) {
this.getContainer().getLoggerComponent()
.error("GameBoardLinePositionException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawFirstHorizontalLine();
} catch (GameBoardLineLengthException e) {
this.getContainer().getLoggerComponent()
.error("GameBoardLineLengthException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawFirstHorizontalLine();
}
} else if (currentState == FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE) {
try {
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Trying to use this line as second horizontal line");
this.getContainer().getGameBoardComponent().setSecondHorizontalLine(line);
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Second horizontal line was successfully created. Calculating game board");
this.getContainer().getGameBoardComponent().calculateBoard();
this.eventSecondHorizontalLineReady();
} catch (GameBoardLineRequirementsException e) {
this.getContainer().getLoggerComponent().error("GameBoardLineRequirementsException");
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondHorizontalLine();
} catch (GameBoardLinePointsCountException e) {
this.getContainer().getLoggerComponent().error("GameBoardLinePointsCountException");
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondHorizontalLine();
} catch (GameBoardLinePositionException e) {
this.getContainer().getLoggerComponent()
.error("GameBoardLinePositionException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondHorizontalLine();
} catch (GameBoardLineLengthException e) {
this.getContainer().getLoggerComponent()
.error("GameBoardLineLengthException. Reason: "
+ e.getReason());
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondHorizontalLine();
} catch (GameBoardImpossibleException e) {
this.getContainer().getLoggerComponent().error("GameBoardImpossibleException");
this.getContainer().getGameDisplayComponent().displayErrorDrawSecondHorizontalLine();
}
} else if (currentState == FSM_STATE_GAME_HUMAN_TURN) {
this.icrContext.addStroke(pageInstance, time);
this.getContainer().getLoggerComponent()
.debug("[GameFSM] StrokeCreated. Stroke was added to ICR context");
}
}
/**
* Called when the user crosses out text
*/
public void hwrCrossingOut(long time, String result) {
}
/**
* Called when an error occurs during handwriting recognition
*/
public void hwrError(long time, String error) {
}
/**
* When the ICR engine detects an acceptable series or strokes
*/
public void hwrResult(long time, String result) {
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] Intermediate result: " + result);
}
/**
* When the user pauses (pause time specified by the wizard), all strokes in
* the ICRContext are cleared
*/
public void hwrUserPause(long time, String result) {
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] Result: " + result
+ " (x) | Human type: " + this.getContainer().getGameLogicComponent().getHumanType());
// At first we must check, that result is the required symbol
boolean symbolCorrect = false;
if (result.equalsIgnoreCase("x")) {
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] User has draw X");
if (this.getContainer().getGameLogicComponent().getHumanType() == GameLogic.FIELD_X) {
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] User played with X");
symbolCorrect = true;
}
} else if (result.equalsIgnoreCase("o")) {
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] User has draw O");
if (this.getContainer().getGameLogicComponent().getHumanType() == GameLogic.FIELD_O) {
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] User played with O");
symbolCorrect = true;
}
}
if (symbolCorrect) {
this.getContainer().getLoggerComponent()
.debug("[GameFSM][ICR] User has draw required symbol. Trying to get it's position.");
// Required symbol appears. Now we must check, which field is used
// Retrieving center of the user symbol
this.getContainer().getLoggerComponent()
.debug("[GameFSM][ICR] Receiving symbol rectangle. ICRContext: "
+ this.icrContext);
Rectangle r = this.icrContext.getTextBoundingBox();
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] Rectangle: " + r);
this.getContainer().getLoggerComponent()
.debug("[GameFSM][ICR] symbol rectangle was received ("
+ r.toString() + "). Calculating it's center point");
Point p = new Point(r.getX() + r.getWidth() / 2, r.getY()
+ r.getHeight() / 2);
this.getContainer().getLoggerComponent().debug("[GameFSM][ICR] Point of the user symbol is ("
+ p.getX() + "," + p.getY() + ")");
int field = this.container.getGameBoardComponent().getTurnField(p);
if (field != -1) {
this.getContainer().getLoggerComponent()
.debug("[GameFSM][ICR] Turn was done in the correct field");
this.getContainer().getGameLogicComponent().humanTurn(field);
this.eventHumanTurnReady();
} else {
this.getContainer().getLoggerComponent()
.debug("[GameFSM][ICR] Turn was done outside board");
}
} else {
this.getContainer().getLoggerComponent()
.debug("[GameFSM][ICR] User has not draw required symbol");
}
// ICR Strokes clearing must be done in any case
this.icrContext.clearStrokes();
}
/**
* Initializes ICR context for an application
*/
private void initializeICRContext() {
this.getContainer().getLoggerComponent().info("[GameFSM] Initializing ICR context");
try {
this.icrContext = this.getContainer().getPenletComponent().getContext().getICRContext(1000, this);
Resource[] resources = {
this.icrContext.getDefaultAlphabetKnowledgeResource(),
this.icrContext
.createAppResource("/icr/LEX_smartpen-ticktacktoe.res"),
this.icrContext
.createAppResource("/icr/SK_smartpen-ticktacktoe.res") };
this.icrContext.addResourceSet(resources);
this.getContainer().getLoggerComponent().info("[GameFSM] ICR context was successfully initialized");
} catch (Exception e) {
String msg = "[GameFSM] Error initializing handwriting recognition resources: "
+ e.getMessage();
this.getContainer().getLoggerComponent().error(msg);
this.getContainer().getGameDisplayComponent().displayMessage(msg, true);
}
}
/**
* Destroys ICR context
*/
private void destroyICRContext() {
icrContext.dispose();
icrContext = null;
this.getContainer().getLoggerComponent().info("[GameFSM] ICR context was destroyed");
}
/**
* Processing of the next event, scheduled during transition
*/
private void processNextEvent() {
if (nextEvent != NEXT_EVENT_NONE) {
switch (nextEvent) {
case NEXT_EVENT_PLAYER_SELECTED_HUMAN_TURN_NEXT:
eventPlayerSelectedHumanTurnNext();
break;
case NEXT_EVENT_PLAYER_SELECTED_PEN_TURN_NEXT:
eventPlayerSelectedPenTurnNext();
break;
case NEXT_EVENT_GAME_PEN_TURN_READY:
eventPenTurnReady();
break;
case NEXT_EVENT_GAME_END_HUMAN_WINS:
eventHumanWins();
break;
case NEXT_EVENT_GAME_END_PEN_WINS:
eventPenWins();
break;
case NEXT_EVENT_GAME_END_DRAW:
eventDraw();
break;
case NEXT_EVENT_END:
eventEndApplication();
break;
default:
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Invalid next event, that cannot be processed ("
+ nextEvent + ")");
break;
}
}
}
/**
* Set's new next event to process
*
* @param nextEvent
*/
public void setNextEvent(int nextEvent) {
this.nextEvent = nextEvent;
}
/**
* Returns container
*
* @return container
*/
public Container getContainer() {
return container;
}
}
| true | true | private void transition(int currentState, int transitionState) {
this.getContainer().getLoggerComponent().debug("[GameFSM] ---> transition started ( " + currentState
+ " -> " + transitionState + " )");
try {
switch (transitionState) {
case FSM_STATE_MAIN_MENU_START_GAME:
if (currentState == FSM_STATE_START
|| currentState == FSM_STATE_LEVEL_MENU_EASY
|| currentState == FSM_STATE_LEVEL_MENU_HARD) {
// Select "Help" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(0);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 0");
} else if (currentState == FSM_STATE_MAIN_MENU_HELP) {
// Main menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusMainMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 0 was activated");
}
break;
case FSM_STATE_MAIN_MENU_HELP:
if (currentState == FSM_STATE_MAIN_MENU_START_GAME) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusMainMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 1 was activated");
} else if (currentState == FSM_STATE_MAIN_MENU_ABOUT) {
// Main menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusMainMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 1 was activated");
} else if (currentState == FSM_STATE_HELP_MENU_RULES
|| currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD
|| currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
// Select "Help" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(1);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 1");
}
break;
case FSM_STATE_MAIN_MENU_ABOUT:
if (currentState == FSM_STATE_MAIN_MENU_HELP) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusMainMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 2 was activated");
} else if (currentState == FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED) {
// Select "About" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(2);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 2");
}
break;
case FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED:
if (currentState == FSM_STATE_MAIN_MENU_ABOUT) {
this.getContainer().getGameDisplayComponent().displayAbout();
this.getContainer().getLoggerComponent().debug("[GameFSM] About was displayed");
}
break;
case FSM_STATE_LEVEL_MENU_EASY:
if (currentState == FSM_STATE_MAIN_MENU_START_GAME) {
// Select "Easy" in the level select menu, if not selected
this.getContainer().getGameDisplayComponent().selectLevelSelectMenuItemIfNotSelected(0);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayLevelSelectMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu was displayed");
} else if (currentState == FSM_STATE_LEVEL_MENU_HARD) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusLevelSelectMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu item 0 was activated");
}
break;
case FSM_STATE_LEVEL_MENU_HARD:
if (currentState == FSM_STATE_LEVEL_MENU_EASY) {
this.getContainer().getGameDisplayComponent().focusLevelSelectMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu item 1 was activated");
}
break;
case FSM_STATE_HELP_MENU_RULES:
if (currentState == FSM_STATE_MAIN_MENU_HELP
|| currentState == FSM_STATE_HELP_MENU_RULES_DISPLAYED) {
// Select "Rules" in the help menu, if not selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(0);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
// Help menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusHelpMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 0 was activated");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED) {
// Select "How to draw board" in the help menu, if not
// selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(1);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_RULES) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 1 was activated");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 1 was activated");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED) {
// Select "How to play" in the help menu, if not selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(2);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 2 was activated");
}
break;
case FSM_STATE_HELP_MENU_RULES_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_RULES) {
this.getContainer().getGameDisplayComponent().displayRules();
this.getContainer().getLoggerComponent().debug("[GameFSM] Rules was displayed");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
this.getContainer().getGameDisplayComponent().displayHowToDrawBoard();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] How to draw board was displayed");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
this.getContainer().getGameDisplayComponent().displayHowToPlay();
this.getContainer().getLoggerComponent().debug("[GameFSM] How to play was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE:
if (currentState == FSM_STATE_LEVEL_MENU_EASY
|| currentState == FSM_STATE_LEVEL_MENU_HARD) {
this.getContainer().getGameDisplayComponent().displayDrawFirstVerticalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw first vertical line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawSecondVerticalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw second vertical line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawFirstHorizontalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw first horizontal line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawSecondHorizontalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw second horizontal line was displayed");
}
break;
case FSM_STATE_GAME_SELECT_PLAYER_ORDER:
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE) {
boolean humanFirst = this.getContainer()
.getGameLogicComponent().selectPlayersOrder();
if (humanFirst) {
this.setNextEvent(NEXT_EVENT_PLAYER_SELECTED_HUMAN_TURN_NEXT);
} else {
this.setNextEvent(NEXT_EVENT_PLAYER_SELECTED_PEN_TURN_NEXT);
}
}
break;
case FSM_STATE_GAME_HUMAN_TURN:
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER
|| currentState == FSM_STATE_GAME_PEN_TURN) {
// 1. Checking, that game is not end
if (this.checkGameStatus()) {
// 2. Redrawing board with text "Your turn"
this.getContainer().getGameDisplayComponent().redrawBoard(true);
}
}
break;
case FSM_STATE_GAME_PEN_TURN:
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER
|| currentState == FSM_STATE_GAME_HUMAN_TURN) {
// 1. Checking, that game is not end
if (this.checkGameStatus()) {
// 2. Redrawing board with text "Your turn"
this.getContainer().getGameDisplayComponent().redrawBoard(false);
// 3. Performing pen turn;
this.getContainer().getGameLogicComponent().aiTurn();
this.setNextEvent(NEXT_EVENT_GAME_PEN_TURN_READY);
}
}
break;
case FSM_STATE_GAME_END_HUMAN_WINS:
this.getContainer().getGameDisplayComponent().displayHumanWins();
this.getContainer().getLoggerComponent().debug("[GameFSM] Human wins was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_GAME_END_PEN_WINS:
this.getContainer().getGameDisplayComponent().displayPenWins();
this.getContainer().getLoggerComponent().debug("[GameFSM] Pen wins was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_GAME_END_DRAW:
this.getContainer().getGameDisplayComponent().displayDraw();
this.getContainer().getLoggerComponent().debug("[GameFSM] Draw was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_END:
this.getContainer().getGameDisplayComponent().displayEnd();
this.getContainer().getLoggerComponent().debug("[GameFSM] Game end reached");
default:
// Unrecognized target state. Rejecting it
this.getContainer().getLoggerComponent().warn("[GameFSM] Unrecognized target state: "
+ transitionState);
return;
} // switch (transitionState)
this.currentState = transitionState;
} catch (Exception e) {
this.getContainer().getLoggerComponent().error("[GameFSM] Exception appears: " + e);
}
this.getContainer().getLoggerComponent().debug("[GameFSM] Starting processing next event");
this.processNextEvent();
this.getContainer().getLoggerComponent().debug("[GameFSM] Next event was processed");
this.getContainer().getLoggerComponent().debug("[GameFSM] <--- transition");
}
| private void transition(int currentState, int transitionState) {
this.getContainer().getLoggerComponent().debug("[GameFSM] ---> transition started ( " + currentState
+ " -> " + transitionState + " )");
try {
switch (transitionState) {
case FSM_STATE_MAIN_MENU_START_GAME:
if (currentState == FSM_STATE_START
|| currentState == FSM_STATE_LEVEL_MENU_EASY
|| currentState == FSM_STATE_LEVEL_MENU_HARD) {
// Select "Help" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(0);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 0");
} else if (currentState == FSM_STATE_MAIN_MENU_HELP) {
// Main menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusMainMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 0 was activated");
}
break;
case FSM_STATE_MAIN_MENU_HELP:
if (currentState == FSM_STATE_MAIN_MENU_START_GAME) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusMainMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 1 was activated");
} else if (currentState == FSM_STATE_MAIN_MENU_ABOUT) {
// Main menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusMainMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 1 was activated");
} else if (currentState == FSM_STATE_HELP_MENU_RULES
|| currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD
|| currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
// Select "Help" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(1);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 1");
}
break;
case FSM_STATE_MAIN_MENU_ABOUT:
if (currentState == FSM_STATE_MAIN_MENU_HELP) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusMainMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu item 2 was activated");
} else if (currentState == FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED) {
// Select "About" in the main menu, if not selected
this.getContainer().getGameDisplayComponent().selectMainMenuItemIfNotSelected(2);
// Main menu must be displayed
this.getContainer().getGameDisplayComponent().displayMainMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Main menu was displayed with active item 2");
}
break;
case FSM_STATE_MAIN_MENU_ABOUT_DISPLAYED:
if (currentState == FSM_STATE_MAIN_MENU_ABOUT) {
this.getContainer().getGameDisplayComponent().displayAbout();
this.getContainer().getLoggerComponent().debug("[GameFSM] About was displayed");
}
break;
case FSM_STATE_LEVEL_MENU_EASY:
if (currentState == FSM_STATE_MAIN_MENU_START_GAME) {
// Select "Easy" in the level select menu, if not selected
this.getContainer().getGameDisplayComponent().selectLevelSelectMenuItemIfNotSelected(0);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayLevelSelectMenu();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu was displayed");
} else if (currentState == FSM_STATE_LEVEL_MENU_HARD) {
// Main menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusLevelSelectMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu item 0 was activated");
}
break;
case FSM_STATE_LEVEL_MENU_HARD:
if (currentState == FSM_STATE_LEVEL_MENU_EASY) {
this.getContainer().getGameDisplayComponent().focusLevelSelectMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Level select menu item 1 was activated");
}
break;
case FSM_STATE_HELP_MENU_RULES:
if (currentState == FSM_STATE_MAIN_MENU_HELP
|| currentState == FSM_STATE_HELP_MENU_RULES_DISPLAYED) {
// Select "Rules" in the help menu, if not selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(0);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
// Help menu must be focused to the previous item
this.getContainer().getGameDisplayComponent().focusHelpMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 0 was activated");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED) {
// Select "How to draw board" in the help menu, if not
// selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(1);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_RULES) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 1 was activated");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToPrevious();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 1 was activated");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED) {
// Select "How to play" in the help menu, if not selected
this.getContainer().getGameDisplayComponent().selectHelpMenuItemIfNotSelected(2);
// Level select menu must be displayed
this.getContainer().getGameDisplayComponent().displayHelpMenu();
this.getContainer().getLoggerComponent().debug("[GameFSM] Help menu was displayed");
} else if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
// Help menu must be focused to the next item
this.getContainer().getGameDisplayComponent().focusHelpMenuToNext();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Help menu item 2 was activated");
}
break;
case FSM_STATE_HELP_MENU_RULES_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_RULES) {
this.getContainer().getGameDisplayComponent().displayRules();
this.getContainer().getLoggerComponent().debug("[GameFSM] Rules was displayed");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_DRAW_BOARD) {
this.getContainer().getGameDisplayComponent().displayHowToDrawBoard();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] How to draw board was displayed");
}
break;
case FSM_STATE_HELP_MENU_HOW_TO_PLAY_DISPLAYED:
if (currentState == FSM_STATE_HELP_MENU_HOW_TO_PLAY) {
this.getContainer().getGameDisplayComponent().displayHowToPlay();
this.getContainer().getLoggerComponent().debug("[GameFSM] How to play was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE:
if (currentState == FSM_STATE_LEVEL_MENU_EASY
|| currentState == FSM_STATE_LEVEL_MENU_HARD) {
this.getContainer().getGameDisplayComponent().displayDrawFirstVerticalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw first vertical line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_VERTICAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawSecondVerticalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw second vertical line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_VERTICAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawFirstHorizontalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw first horizontal line was displayed");
}
break;
case FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE:
if (currentState == FSM_STATE_DRAW_BOARD_FIRST_HORIZONTAL_LINE) {
this.getContainer().getGameDisplayComponent().displayDrawSecondHorizontalLine();
this.getContainer().getLoggerComponent()
.debug("[GameFSM] Draw second horizontal line was displayed");
}
break;
case FSM_STATE_GAME_SELECT_PLAYER_ORDER:
if (currentState == FSM_STATE_DRAW_BOARD_SECOND_HORIZONTAL_LINE) {
boolean humanFirst = this.getContainer()
.getGameLogicComponent().selectPlayersOrder();
if (humanFirst) {
this.setNextEvent(NEXT_EVENT_PLAYER_SELECTED_HUMAN_TURN_NEXT);
} else {
this.setNextEvent(NEXT_EVENT_PLAYER_SELECTED_PEN_TURN_NEXT);
}
}
break;
case FSM_STATE_GAME_HUMAN_TURN:
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER
|| currentState == FSM_STATE_GAME_PEN_TURN) {
// 1. Checking, that game is not end
if (this.checkGameStatus()) {
// 2. Redrawing board with text "Your turn"
this.getContainer().getGameDisplayComponent().redrawBoard(true);
}
}
break;
case FSM_STATE_GAME_PEN_TURN:
if (currentState == FSM_STATE_GAME_SELECT_PLAYER_ORDER
|| currentState == FSM_STATE_GAME_HUMAN_TURN) {
// 1. Checking, that game is not end
if (this.checkGameStatus()) {
// 2. Redrawing board with text "Your turn"
this.getContainer().getGameDisplayComponent().redrawBoard(false);
// 3. Performing pen turn;
this.getContainer().getGameLogicComponent().aiTurn();
this.setNextEvent(NEXT_EVENT_GAME_PEN_TURN_READY);
}
}
break;
case FSM_STATE_GAME_END_HUMAN_WINS:
this.getContainer().getGameDisplayComponent().displayHumanWins();
this.getContainer().getLoggerComponent().debug("[GameFSM] Human wins was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_GAME_END_PEN_WINS:
this.getContainer().getGameDisplayComponent().displayPenWins();
this.getContainer().getLoggerComponent().debug("[GameFSM] Pen wins was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_GAME_END_DRAW:
this.getContainer().getGameDisplayComponent().displayDraw();
this.getContainer().getLoggerComponent().debug("[GameFSM] Draw was displayed");
Thread.sleep(2000);
this.setNextEvent(NEXT_EVENT_END);
break;
case FSM_STATE_END:
this.getContainer().getGameDisplayComponent().displayEnd();
this.getContainer().getLoggerComponent().debug("[GameFSM] Game end reached");
break;
default:
// Unrecognized target state. Rejecting it
this.getContainer().getLoggerComponent().warn("[GameFSM] Unrecognized target state: "
+ transitionState);
return;
} // switch (transitionState)
this.currentState = transitionState;
} catch (Exception e) {
this.getContainer().getLoggerComponent().error("[GameFSM] Exception appears: " + e);
}
this.getContainer().getLoggerComponent().debug("[GameFSM] Starting processing next event");
this.processNextEvent();
this.getContainer().getLoggerComponent().debug("[GameFSM] Next event was processed");
this.getContainer().getLoggerComponent().debug("[GameFSM] <--- transition");
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.richfaces.test/src/org/jboss/tools/jsf/vpe/richfaces/test/jbide/JBIDE1713Test.java b/jsf/tests/org.jboss.tools.jsf.vpe.richfaces.test/src/org/jboss/tools/jsf/vpe/richfaces/test/jbide/JBIDE1713Test.java
index ca37df4b4..b7b22d37f 100644
--- a/jsf/tests/org.jboss.tools.jsf.vpe.richfaces.test/src/org/jboss/tools/jsf/vpe/richfaces/test/jbide/JBIDE1713Test.java
+++ b/jsf/tests/org.jboss.tools.jsf.vpe.richfaces.test/src/org/jboss/tools/jsf/vpe/richfaces/test/jbide/JBIDE1713Test.java
@@ -1,183 +1,183 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jsf.vpe.richfaces.test.jbide;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.jboss.tools.jst.jsp.jspeditor.JSPMultiPageEditor;
import org.jboss.tools.vpe.editor.util.HTML;
import org.jboss.tools.vpe.ui.test.TestUtil;
import org.jboss.tools.vpe.ui.test.VpeTest;
import org.mozilla.interfaces.nsIDOMDocument;
import org.mozilla.interfaces.nsIDOMElement;
import org.mozilla.interfaces.nsIDOMNode;
/**
* Test JBIDE-1713
*
* @author Dzmitry Sakovich ([email protected])
*
*/
public class JBIDE1713Test extends VpeTest {
public static final String IMPORT_PROJECT_NAME = "richFacesTest";
private static final String TEST_PAGE_NAME = "JBIDE/1713/JBIDE-1713.xhtml";
public JBIDE1713Test(String name) {
super(name);
}
// test method for JBIDE 1713 component
public void testJBIDE_1713() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(TEST_PAGE_NAME,
IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + file.getFullPath(),
file);
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
// get dom document
nsIDOMDocument document = getVpeVisualDocument(part);
nsIDOMElement element = document.getDocumentElement();
// check that element is not null
assertNotNull(element);
// get root node
nsIDOMNode node = (nsIDOMNode) element
.queryInterface(nsIDOMNode.NS_IDOMNODE_IID);
List<nsIDOMNode> elements = new ArrayList<nsIDOMNode>();
// find "table" elements
TestUtil.findElementsByName(node, elements, HTML.TAG_TABLE);
assertEquals(1, elements.size());
nsIDOMElement table = (nsIDOMElement) elements.get(0).queryInterface(
nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(table);
// Check applying styleClass
String styleClass = table.getAttribute(HTML.ATTR_CLASS);
assertNotNull("styleClass attribute not apply", styleClass);
assertEquals("dr-pnlbar rich-panelbar dr-pnlbar-b myClass", styleClass);
// Check applying style
String stylePanel = table.getAttribute(HTML.ATTR_STYLE);
assertNotNull("style attribute not apply", stylePanel);
assertEquals(
"padding: 0px; height: 207px; width: 453px; font-weight: bold;",
stylePanel);
elements.clear();
TestUtil.findAllElementsByName(node, elements, HTML.TAG_DIV);
assertEquals(9, elements.size());
nsIDOMElement activeToggle = (nsIDOMElement) elements.get(4)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(activeToggle);
String activeToggleClass = activeToggle.getAttribute(HTML.ATTR_CLASS);
assertNotNull(activeToggleClass);
assertEquals(
- "dr-pnlbar-h rich-panelbar-header myHeaderStyleActive myHeaderStyleActive",
+ "dr-pnlbar-h rich-panelbar-header myHeaderStyle1 myHeaderStyle myHeaderStyleActive1 myHeaderStyleActive",
activeToggleClass);
String activeToggleStyle = activeToggle.getAttribute(HTML.ATTR_STYLE);
assertNotNull(activeToggleStyle);
assertEquals(
"background: red none repeat scroll 0%; color: blue; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;",
activeToggleStyle);
// check active content
List<nsIDOMNode> contentElements = new ArrayList<nsIDOMNode>();
TestUtil.findAllElementsByName(node, contentElements, HTML.TAG_TD);
assertEquals(2, contentElements.size());
nsIDOMElement contentElement = (nsIDOMElement) contentElements.get(1)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
String activeContentStyle = contentElement
.getAttribute(HTML.ATTR_STYLE);
assertNotNull(activeContentStyle);
assertEquals("color: green;", activeContentStyle);
String activeContentClass = contentElement
.getAttribute(HTML.ATTR_CLASS);
assertNotNull(activeContentClass);
assertEquals(
- "dr-pnlbar-c rich-panelbar-content myContentStyle myContentStyle",
+ "dr-pnlbar-c rich-panelbar-content myContentStyle1 myContentStyle",
activeContentClass);
// check facet
nsIDOMElement disabledToggle = (nsIDOMElement) elements.get(6)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
String disabledContentStyle = disabledToggle
.getAttribute(HTML.ATTR_STYLE);
assertNotNull(disabledContentStyle);
assertEquals("color: green;", disabledContentStyle);
String disabledContentClass = disabledToggle
.getAttribute(HTML.ATTR_CLASS);
assertNotNull(disabledContentClass);
assertEquals("dr-pnlbar-h rich-panelbar-header myHeaderStyle1",
disabledContentClass);
contentElements.clear();
TestUtil.findElementsByName((nsIDOMNode) disabledToggle,
contentElements, HTML.TAG_IMG);
assertEquals(1, contentElements.size());
disabledToggle = (nsIDOMElement) elements.get(8).queryInterface(
nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
disabledContentStyle = disabledToggle.getAttribute(HTML.ATTR_STYLE);
assertNotNull(disabledContentStyle);
assertEquals("color: green;", disabledContentStyle);
disabledContentClass = disabledToggle.getAttribute(HTML.ATTR_CLASS);
assertNotNull(disabledContentClass);
assertEquals("dr-pnlbar-h rich-panelbar-header myHeaderStyle1",
disabledContentClass);
if (getException() != null) {
throw getException();
}
}
}
| false | true | public void testJBIDE_1713() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(TEST_PAGE_NAME,
IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + file.getFullPath(),
file);
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
// get dom document
nsIDOMDocument document = getVpeVisualDocument(part);
nsIDOMElement element = document.getDocumentElement();
// check that element is not null
assertNotNull(element);
// get root node
nsIDOMNode node = (nsIDOMNode) element
.queryInterface(nsIDOMNode.NS_IDOMNODE_IID);
List<nsIDOMNode> elements = new ArrayList<nsIDOMNode>();
// find "table" elements
TestUtil.findElementsByName(node, elements, HTML.TAG_TABLE);
assertEquals(1, elements.size());
nsIDOMElement table = (nsIDOMElement) elements.get(0).queryInterface(
nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(table);
// Check applying styleClass
String styleClass = table.getAttribute(HTML.ATTR_CLASS);
assertNotNull("styleClass attribute not apply", styleClass);
assertEquals("dr-pnlbar rich-panelbar dr-pnlbar-b myClass", styleClass);
// Check applying style
String stylePanel = table.getAttribute(HTML.ATTR_STYLE);
assertNotNull("style attribute not apply", stylePanel);
assertEquals(
"padding: 0px; height: 207px; width: 453px; font-weight: bold;",
stylePanel);
elements.clear();
TestUtil.findAllElementsByName(node, elements, HTML.TAG_DIV);
assertEquals(9, elements.size());
nsIDOMElement activeToggle = (nsIDOMElement) elements.get(4)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(activeToggle);
String activeToggleClass = activeToggle.getAttribute(HTML.ATTR_CLASS);
assertNotNull(activeToggleClass);
assertEquals(
"dr-pnlbar-h rich-panelbar-header myHeaderStyleActive myHeaderStyleActive",
activeToggleClass);
String activeToggleStyle = activeToggle.getAttribute(HTML.ATTR_STYLE);
assertNotNull(activeToggleStyle);
assertEquals(
"background: red none repeat scroll 0%; color: blue; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;",
activeToggleStyle);
// check active content
List<nsIDOMNode> contentElements = new ArrayList<nsIDOMNode>();
TestUtil.findAllElementsByName(node, contentElements, HTML.TAG_TD);
assertEquals(2, contentElements.size());
nsIDOMElement contentElement = (nsIDOMElement) contentElements.get(1)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
String activeContentStyle = contentElement
.getAttribute(HTML.ATTR_STYLE);
assertNotNull(activeContentStyle);
assertEquals("color: green;", activeContentStyle);
String activeContentClass = contentElement
.getAttribute(HTML.ATTR_CLASS);
assertNotNull(activeContentClass);
assertEquals(
"dr-pnlbar-c rich-panelbar-content myContentStyle myContentStyle",
activeContentClass);
// check facet
nsIDOMElement disabledToggle = (nsIDOMElement) elements.get(6)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
String disabledContentStyle = disabledToggle
.getAttribute(HTML.ATTR_STYLE);
assertNotNull(disabledContentStyle);
assertEquals("color: green;", disabledContentStyle);
String disabledContentClass = disabledToggle
.getAttribute(HTML.ATTR_CLASS);
assertNotNull(disabledContentClass);
assertEquals("dr-pnlbar-h rich-panelbar-header myHeaderStyle1",
disabledContentClass);
contentElements.clear();
TestUtil.findElementsByName((nsIDOMNode) disabledToggle,
contentElements, HTML.TAG_IMG);
assertEquals(1, contentElements.size());
disabledToggle = (nsIDOMElement) elements.get(8).queryInterface(
nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
disabledContentStyle = disabledToggle.getAttribute(HTML.ATTR_STYLE);
assertNotNull(disabledContentStyle);
assertEquals("color: green;", disabledContentStyle);
disabledContentClass = disabledToggle.getAttribute(HTML.ATTR_CLASS);
assertNotNull(disabledContentClass);
assertEquals("dr-pnlbar-h rich-panelbar-header myHeaderStyle1",
disabledContentClass);
if (getException() != null) {
throw getException();
}
}
| public void testJBIDE_1713() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(TEST_PAGE_NAME,
IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + file.getFullPath(),
file);
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input);
// open and get editor
JSPMultiPageEditor part = openEditor(input);
// get dom document
nsIDOMDocument document = getVpeVisualDocument(part);
nsIDOMElement element = document.getDocumentElement();
// check that element is not null
assertNotNull(element);
// get root node
nsIDOMNode node = (nsIDOMNode) element
.queryInterface(nsIDOMNode.NS_IDOMNODE_IID);
List<nsIDOMNode> elements = new ArrayList<nsIDOMNode>();
// find "table" elements
TestUtil.findElementsByName(node, elements, HTML.TAG_TABLE);
assertEquals(1, elements.size());
nsIDOMElement table = (nsIDOMElement) elements.get(0).queryInterface(
nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(table);
// Check applying styleClass
String styleClass = table.getAttribute(HTML.ATTR_CLASS);
assertNotNull("styleClass attribute not apply", styleClass);
assertEquals("dr-pnlbar rich-panelbar dr-pnlbar-b myClass", styleClass);
// Check applying style
String stylePanel = table.getAttribute(HTML.ATTR_STYLE);
assertNotNull("style attribute not apply", stylePanel);
assertEquals(
"padding: 0px; height: 207px; width: 453px; font-weight: bold;",
stylePanel);
elements.clear();
TestUtil.findAllElementsByName(node, elements, HTML.TAG_DIV);
assertEquals(9, elements.size());
nsIDOMElement activeToggle = (nsIDOMElement) elements.get(4)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(activeToggle);
String activeToggleClass = activeToggle.getAttribute(HTML.ATTR_CLASS);
assertNotNull(activeToggleClass);
assertEquals(
"dr-pnlbar-h rich-panelbar-header myHeaderStyle1 myHeaderStyle myHeaderStyleActive1 myHeaderStyleActive",
activeToggleClass);
String activeToggleStyle = activeToggle.getAttribute(HTML.ATTR_STYLE);
assertNotNull(activeToggleStyle);
assertEquals(
"background: red none repeat scroll 0%; color: blue; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;",
activeToggleStyle);
// check active content
List<nsIDOMNode> contentElements = new ArrayList<nsIDOMNode>();
TestUtil.findAllElementsByName(node, contentElements, HTML.TAG_TD);
assertEquals(2, contentElements.size());
nsIDOMElement contentElement = (nsIDOMElement) contentElements.get(1)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
String activeContentStyle = contentElement
.getAttribute(HTML.ATTR_STYLE);
assertNotNull(activeContentStyle);
assertEquals("color: green;", activeContentStyle);
String activeContentClass = contentElement
.getAttribute(HTML.ATTR_CLASS);
assertNotNull(activeContentClass);
assertEquals(
"dr-pnlbar-c rich-panelbar-content myContentStyle1 myContentStyle",
activeContentClass);
// check facet
nsIDOMElement disabledToggle = (nsIDOMElement) elements.get(6)
.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
String disabledContentStyle = disabledToggle
.getAttribute(HTML.ATTR_STYLE);
assertNotNull(disabledContentStyle);
assertEquals("color: green;", disabledContentStyle);
String disabledContentClass = disabledToggle
.getAttribute(HTML.ATTR_CLASS);
assertNotNull(disabledContentClass);
assertEquals("dr-pnlbar-h rich-panelbar-header myHeaderStyle1",
disabledContentClass);
contentElements.clear();
TestUtil.findElementsByName((nsIDOMNode) disabledToggle,
contentElements, HTML.TAG_IMG);
assertEquals(1, contentElements.size());
disabledToggle = (nsIDOMElement) elements.get(8).queryInterface(
nsIDOMElement.NS_IDOMELEMENT_IID);
assertNotNull(contentElement);
disabledContentStyle = disabledToggle.getAttribute(HTML.ATTR_STYLE);
assertNotNull(disabledContentStyle);
assertEquals("color: green;", disabledContentStyle);
disabledContentClass = disabledToggle.getAttribute(HTML.ATTR_CLASS);
assertNotNull(disabledContentClass);
assertEquals("dr-pnlbar-h rich-panelbar-header myHeaderStyle1",
disabledContentClass);
if (getException() != null) {
throw getException();
}
}
|
diff --git a/src/main/java/com/threerings/config/tools/ResourceEditor.java b/src/main/java/com/threerings/config/tools/ResourceEditor.java
index aefeccf4..bbe50058 100644
--- a/src/main/java/com/threerings/config/tools/ResourceEditor.java
+++ b/src/main/java/com/threerings/config/tools/ResourceEditor.java
@@ -1,477 +1,478 @@
//
// $Id$
//
// Clyde library - tools for developing networked games
// Copyright (C) 2005-2011 Three Rings Design, Inc.
// http://code.google.com/p/clyde/
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.threerings.config.tools;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import com.google.common.base.Objects;
import com.google.common.collect.Sets;
import com.samskivert.swing.util.SwingUtil;
import com.threerings.media.image.ColorPository;
import com.threerings.resource.ResourceManager;
import com.threerings.util.ChangeBlock;
import com.threerings.util.MessageManager;
import com.threerings.editor.swing.EditorPanel;
import com.threerings.export.BinaryExporter;
import com.threerings.export.BinaryImporter;
import com.threerings.export.XMLExporter;
import com.threerings.export.XMLImporter;
import com.threerings.config.ConfigEvent;
import com.threerings.config.ConfigGroup;
import com.threerings.config.ConfigManager;
import com.threerings.config.ConfigUpdateListener;
import com.threerings.config.ManagedConfig;
import com.threerings.config.ParameterizedConfig;
import static com.threerings.ClydeLog.*;
/**
* Allows editing single configurations stored as resources.
*/
public class ResourceEditor extends BaseConfigEditor
implements ChangeListener, ConfigUpdateListener<ManagedConfig>
{
/**
* The program entry point.
*/
public static void main (String[] args)
{
ResourceManager rsrcmgr = new ResourceManager("rsrc/");
MessageManager msgmgr = new MessageManager("rsrc.i18n");
ConfigManager cfgmgr = new ConfigManager(rsrcmgr, msgmgr, "config/");
ColorPository colorpos = ColorPository.loadColorPository(rsrcmgr);
new ResourceEditor(
msgmgr, cfgmgr, colorpos, args.length > 0 ? args[0] : null).setVisible(true);
}
/**
* Creates a new resource editor.
*/
public ResourceEditor (MessageManager msgmgr, ConfigManager cfgmgr, ColorPository colorpos)
{
this(msgmgr, cfgmgr, colorpos, null);
}
/**
* Creates a new resource editor.
*/
public ResourceEditor (
MessageManager msgmgr, ConfigManager cfgmgr, ColorPository colorpos, String config)
{
super(msgmgr, cfgmgr, colorpos, "resource");
setSize(550, 600);
SwingUtil.centerWindow(this);
// populate the menu bar
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu file = createMenu("file", KeyEvent.VK_F);
menubar.add(file);
JMenu nmenu = createMenu("new", KeyEvent.VK_N);
file.add(nmenu);
nmenu.add(createMenuItem("window", KeyEvent.VK_W, KeyEvent.VK_N));
nmenu.addSeparator();
file.add(createMenuItem("open", KeyEvent.VK_O, KeyEvent.VK_O));
file.addSeparator();
file.add(_save = createMenuItem("save", KeyEvent.VK_S, KeyEvent.VK_S));
_save.setEnabled(false);
file.add(_saveAs = createMenuItem("save_as", KeyEvent.VK_A, KeyEvent.VK_A));
_saveAs.setEnabled(false);
file.add(_revert = createMenuItem("revert", KeyEvent.VK_R, KeyEvent.VK_R));
_revert.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("import", KeyEvent.VK_I, -1));
file.add(_export = createMenuItem("export", KeyEvent.VK_E, -1));
_export.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("close", KeyEvent.VK_C, KeyEvent.VK_W));
file.add(createMenuItem("quit", KeyEvent.VK_Q, KeyEvent.VK_Q));
JMenu edit = createMenu("edit", KeyEvent.VK_E);
menubar.add(edit);
edit.add(createMenuItem("update", KeyEvent.VK_U, KeyEvent.VK_U));
addFindMenu(edit);
edit.addSeparator();
edit.add(createMenuItem("configs", KeyEvent.VK_C, KeyEvent.VK_G));
edit.add(createMenuItem("preferences", KeyEvent.VK_P, KeyEvent.VK_P));
// add the new items now that we've initialized the config manager
Set<Character> mnems = Sets.newHashSet();
mnems.add('w');
int idx = 0;
for (final Class<?> clazz : cfgmgr.getResourceClasses()) {
String label = getLabel(clazz, ConfigGroup.getName(clazz));
JMenuItem item = new JMenuItem(label);
for (int ii = 0, nn = label.length(); ii < nn; ii++) {
char c = Character.toLowerCase(label.charAt(ii));
if (Character.isLetter(c) && mnems.add(c)) {
item.setMnemonic(c);
break;
}
}
if (++idx <= 9) {
item.setAccelerator(KeyStroke.getKeyStroke(
Character.forDigit(idx, 10), KeyEvent.CTRL_MASK));
}
nmenu.add(item);
item.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
newConfig(clazz);
}
});
}
// create the file chooser
_chooser = new JFileChooser(_prefs.get("config_dir", null));
_chooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
- return file.isDirectory() || file.toString().toLowerCase().endsWith(".dat");
+ return file != null && (file.isDirectory() ||
+ file.toString().toLowerCase().endsWith(".dat"));
}
public String getDescription () {
return _msgs.get("m.config_files");
}
});
// and the export the file chooser
_exportChooser = new JFileChooser(_prefs.get("export_dir", null));
_exportChooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".xml");
}
public String getDescription () {
return _msgs.get("m.xml_files");
}
});
// create and add the editor panel
add(_epanel = new EditorPanel(this, EditorPanel.CategoryMode.TABS, null),
BorderLayout.CENTER);
_epanel.addChangeListener(this);
// open the initial config, if one was specified
if (config != null) {
open(new File(config));
}
}
// documentation inherited from interface ChangeListener
public void stateChanged (ChangeEvent event)
{
if (!_block.enter()) {
return;
}
try {
ManagedConfig config = (ManagedConfig)_epanel.getObject();
config.updateFromSource(this, false);
config.wasUpdated();
} finally {
_block.leave();
}
}
// documentation inherited from interface ConfigUpdateListener
public void configUpdated (ConfigEvent<ManagedConfig> event)
{
if (!_block.enter()) {
return;
}
try {
_epanel.update();
} finally {
_block.leave();
}
}
@Override // documentation inherited
public void actionPerformed (ActionEvent event)
{
String action = event.getActionCommand();
if (action.equals("window")) {
showFrame(new ResourceEditor(_msgmgr, _cfgmgr, _colorpos));
} else if (action.equals("open")) {
open();
} else if (action.equals("save")) {
if (_file != null) {
save(_file);
} else {
save();
}
} else if (action.equals("save_as")) {
save();
} else if (action.equals("revert")) {
if (showCantUndo()) {
open(_file);
}
} else if (action.equals("import")) {
importConfig();
} else if (action.equals("export")) {
exportConfig();
} else if (action.equals("update")) {
ManagedConfig config = (ManagedConfig)_epanel.getObject();
config.updateFromSource(this, true);
config.wasUpdated();
} else if (action.equals("configs")) {
showFrame(new ConfigEditor(_msgmgr, getConfigManager(), _colorpos));
} else {
super.actionPerformed(event);
}
}
@Override // documentation inherited
public void removeNotify ()
{
super.removeNotify();
setConfig(null, null);
}
@Override // documentation inherited
public ConfigManager getConfigManager ()
{
Object config = _epanel.getObject();
return (config instanceof ParameterizedConfig) ?
((ParameterizedConfig)config).getConfigManager() : _cfgmgr;
}
/**
* Creates a new configuration of the specified class.
*/
protected void newConfig (Class<?> clazz)
{
try {
ManagedConfig config = (ManagedConfig)clazz.newInstance();
config.init(_cfgmgr);
setConfig(config, null);
} catch (Exception e) {
log.warning("Error creating config.", "class", clazz, e);
}
}
/**
* Brings up the open dialog.
*/
protected void open ()
{
if (_chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
open(_chooser.getSelectedFile());
}
_prefs.put("config_dir", _chooser.getCurrentDirectory().toString());
}
/**
* Attempts to open the specified config file.
*/
protected void open (File file)
{
ManagedConfig config;
try {
BinaryImporter in = new BinaryImporter(new FileInputStream(file));
config = (ManagedConfig)in.readObject();
config.init(_cfgmgr);
in.close();
} catch (IOException e) {
log.warning("Failed to open config [file=" + file + "].", e);
return;
}
// retrieve the instance through the cache
String path = _rsrcmgr.getResourcePath(file);
if (path != null) {
config.setName(path);
config = _cfgmgr.updateResourceConfig(path, config);
}
setConfig(config, file);
}
/**
* Brings up the save dialog.
*/
protected void save ()
{
if (_chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
save(_chooser.getSelectedFile());
}
_prefs.put("config_dir", _chooser.getCurrentDirectory().toString());
}
/**
* Attempts to save to the specified file.
*/
protected void save (File file)
{
ManagedConfig config = (ManagedConfig)_epanel.getObject();
String oname = config.getName();
config.setName(null);
try {
BinaryExporter out = new BinaryExporter(new FileOutputStream(file));
out.writeObject(config);
out.close();
} catch (IOException e) {
log.warning("Failed to save config [file=" + file + "].", e);
return;
} finally {
config.setName(oname);
}
// do some special handling to make sure we play nice with the cache
String opath = (_file == null) ? null : _rsrcmgr.getResourcePath(_file);
String npath = _rsrcmgr.getResourcePath(file);
if (!Objects.equal(opath, npath)) {
if (opath != null) {
config = (ManagedConfig)config.clone();
config.init(_cfgmgr);
}
if (npath != null) {
config.setName(npath);
config = _cfgmgr.updateResourceConfig(npath, config);
}
}
setConfig(config, file);
}
/**
* Brings up the import dialog.
*/
protected void importConfig ()
{
if (_exportChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = _exportChooser.getSelectedFile();
try {
XMLImporter in = new XMLImporter(new FileInputStream(file));
ManagedConfig config = (ManagedConfig)in.readObject();
config.init(_cfgmgr);
setConfig(config, null);
in.close();
} catch (IOException e) {
log.warning("Failed to import config [file=" + file +"].", e);
}
}
_prefs.put("export_dir", _exportChooser.getCurrentDirectory().toString());
}
/**
* Brings up the export dialog.
*/
protected void exportConfig ()
{
if (_exportChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = _exportChooser.getSelectedFile();
ManagedConfig config = (ManagedConfig)_epanel.getObject();
String oname = config.getName();
config.setName(null);
try {
XMLExporter out = new XMLExporter(new FileOutputStream(file));
out.writeObject(config);
out.close();
} catch (IOException e) {
log.warning("Failed to export config [file=" + file + "].", e);
} finally {
config.setName(oname);
}
}
_prefs.put("export_dir", _exportChooser.getCurrentDirectory().toString());
}
/**
* Sets the configuration being edited.
*/
protected void setConfig (ManagedConfig config, File file)
{
ManagedConfig oconfig = (ManagedConfig)_epanel.getObject();
if (oconfig != null) {
oconfig.removeListener(this);
}
_epanel.setObject(config);
boolean enable = (config != null);
if (enable) {
config.addListener(this);
}
_file = file;
_save.setEnabled(enable);
_saveAs.setEnabled(enable);
_revert.setEnabled(file != null);
_export.setEnabled(enable);
setTitle(_msgs.get("m.title") + (file == null ? "" : (": " + file)));
}
/**
* Shows a confirm dialog.
*/
protected boolean showCantUndo ()
{
return JOptionPane.showConfirmDialog(this, _msgs.get("m.cant_undo"),
_msgs.get("t.cant_undo"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE) == 0;
}
@Override // documentation inherited
protected EditorPanel getFindEditorPanel ()
{
return _epanel;
}
/** The file menu items. */
protected JMenuItem _save, _saveAs, _revert, _export;
/** The file chooser for opening and saving config files. */
protected JFileChooser _chooser;
/** The file chooser for opening and saving export files. */
protected JFileChooser _exportChooser;
/** The editor panel. */
protected EditorPanel _epanel;
/** The loaded config file. */
protected File _file;
/** Indicates that we should ignore any changes, because we're the one effecting them. */
protected ChangeBlock _block = new ChangeBlock();
}
| true | true | public ResourceEditor (
MessageManager msgmgr, ConfigManager cfgmgr, ColorPository colorpos, String config)
{
super(msgmgr, cfgmgr, colorpos, "resource");
setSize(550, 600);
SwingUtil.centerWindow(this);
// populate the menu bar
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu file = createMenu("file", KeyEvent.VK_F);
menubar.add(file);
JMenu nmenu = createMenu("new", KeyEvent.VK_N);
file.add(nmenu);
nmenu.add(createMenuItem("window", KeyEvent.VK_W, KeyEvent.VK_N));
nmenu.addSeparator();
file.add(createMenuItem("open", KeyEvent.VK_O, KeyEvent.VK_O));
file.addSeparator();
file.add(_save = createMenuItem("save", KeyEvent.VK_S, KeyEvent.VK_S));
_save.setEnabled(false);
file.add(_saveAs = createMenuItem("save_as", KeyEvent.VK_A, KeyEvent.VK_A));
_saveAs.setEnabled(false);
file.add(_revert = createMenuItem("revert", KeyEvent.VK_R, KeyEvent.VK_R));
_revert.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("import", KeyEvent.VK_I, -1));
file.add(_export = createMenuItem("export", KeyEvent.VK_E, -1));
_export.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("close", KeyEvent.VK_C, KeyEvent.VK_W));
file.add(createMenuItem("quit", KeyEvent.VK_Q, KeyEvent.VK_Q));
JMenu edit = createMenu("edit", KeyEvent.VK_E);
menubar.add(edit);
edit.add(createMenuItem("update", KeyEvent.VK_U, KeyEvent.VK_U));
addFindMenu(edit);
edit.addSeparator();
edit.add(createMenuItem("configs", KeyEvent.VK_C, KeyEvent.VK_G));
edit.add(createMenuItem("preferences", KeyEvent.VK_P, KeyEvent.VK_P));
// add the new items now that we've initialized the config manager
Set<Character> mnems = Sets.newHashSet();
mnems.add('w');
int idx = 0;
for (final Class<?> clazz : cfgmgr.getResourceClasses()) {
String label = getLabel(clazz, ConfigGroup.getName(clazz));
JMenuItem item = new JMenuItem(label);
for (int ii = 0, nn = label.length(); ii < nn; ii++) {
char c = Character.toLowerCase(label.charAt(ii));
if (Character.isLetter(c) && mnems.add(c)) {
item.setMnemonic(c);
break;
}
}
if (++idx <= 9) {
item.setAccelerator(KeyStroke.getKeyStroke(
Character.forDigit(idx, 10), KeyEvent.CTRL_MASK));
}
nmenu.add(item);
item.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
newConfig(clazz);
}
});
}
// create the file chooser
_chooser = new JFileChooser(_prefs.get("config_dir", null));
_chooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".dat");
}
public String getDescription () {
return _msgs.get("m.config_files");
}
});
// and the export the file chooser
_exportChooser = new JFileChooser(_prefs.get("export_dir", null));
_exportChooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".xml");
}
public String getDescription () {
return _msgs.get("m.xml_files");
}
});
// create and add the editor panel
add(_epanel = new EditorPanel(this, EditorPanel.CategoryMode.TABS, null),
BorderLayout.CENTER);
_epanel.addChangeListener(this);
// open the initial config, if one was specified
if (config != null) {
open(new File(config));
}
}
| public ResourceEditor (
MessageManager msgmgr, ConfigManager cfgmgr, ColorPository colorpos, String config)
{
super(msgmgr, cfgmgr, colorpos, "resource");
setSize(550, 600);
SwingUtil.centerWindow(this);
// populate the menu bar
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu file = createMenu("file", KeyEvent.VK_F);
menubar.add(file);
JMenu nmenu = createMenu("new", KeyEvent.VK_N);
file.add(nmenu);
nmenu.add(createMenuItem("window", KeyEvent.VK_W, KeyEvent.VK_N));
nmenu.addSeparator();
file.add(createMenuItem("open", KeyEvent.VK_O, KeyEvent.VK_O));
file.addSeparator();
file.add(_save = createMenuItem("save", KeyEvent.VK_S, KeyEvent.VK_S));
_save.setEnabled(false);
file.add(_saveAs = createMenuItem("save_as", KeyEvent.VK_A, KeyEvent.VK_A));
_saveAs.setEnabled(false);
file.add(_revert = createMenuItem("revert", KeyEvent.VK_R, KeyEvent.VK_R));
_revert.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("import", KeyEvent.VK_I, -1));
file.add(_export = createMenuItem("export", KeyEvent.VK_E, -1));
_export.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("close", KeyEvent.VK_C, KeyEvent.VK_W));
file.add(createMenuItem("quit", KeyEvent.VK_Q, KeyEvent.VK_Q));
JMenu edit = createMenu("edit", KeyEvent.VK_E);
menubar.add(edit);
edit.add(createMenuItem("update", KeyEvent.VK_U, KeyEvent.VK_U));
addFindMenu(edit);
edit.addSeparator();
edit.add(createMenuItem("configs", KeyEvent.VK_C, KeyEvent.VK_G));
edit.add(createMenuItem("preferences", KeyEvent.VK_P, KeyEvent.VK_P));
// add the new items now that we've initialized the config manager
Set<Character> mnems = Sets.newHashSet();
mnems.add('w');
int idx = 0;
for (final Class<?> clazz : cfgmgr.getResourceClasses()) {
String label = getLabel(clazz, ConfigGroup.getName(clazz));
JMenuItem item = new JMenuItem(label);
for (int ii = 0, nn = label.length(); ii < nn; ii++) {
char c = Character.toLowerCase(label.charAt(ii));
if (Character.isLetter(c) && mnems.add(c)) {
item.setMnemonic(c);
break;
}
}
if (++idx <= 9) {
item.setAccelerator(KeyStroke.getKeyStroke(
Character.forDigit(idx, 10), KeyEvent.CTRL_MASK));
}
nmenu.add(item);
item.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent event) {
newConfig(clazz);
}
});
}
// create the file chooser
_chooser = new JFileChooser(_prefs.get("config_dir", null));
_chooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file != null && (file.isDirectory() ||
file.toString().toLowerCase().endsWith(".dat"));
}
public String getDescription () {
return _msgs.get("m.config_files");
}
});
// and the export the file chooser
_exportChooser = new JFileChooser(_prefs.get("export_dir", null));
_exportChooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".xml");
}
public String getDescription () {
return _msgs.get("m.xml_files");
}
});
// create and add the editor panel
add(_epanel = new EditorPanel(this, EditorPanel.CategoryMode.TABS, null),
BorderLayout.CENTER);
_epanel.addChangeListener(this);
// open the initial config, if one was specified
if (config != null) {
open(new File(config));
}
}
|
diff --git a/examServer/src/de/thorstenberger/examServer/tasks/TaskFactoryImpl.java b/examServer/src/de/thorstenberger/examServer/tasks/TaskFactoryImpl.java
index 4acd6f4..94ec9fb 100644
--- a/examServer/src/de/thorstenberger/examServer/tasks/TaskFactoryImpl.java
+++ b/examServer/src/de/thorstenberger/examServer/tasks/TaskFactoryImpl.java
@@ -1,489 +1,489 @@
/*
Copyright (C) 2006 Thorsten Berger
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
*
*/
package de.thorstenberger.examServer.tasks;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.thorstenberger.examServer.dao.TaskDefDao;
import de.thorstenberger.examServer.dao.TaskHandlingDao;
import de.thorstenberger.examServer.model.TaskDefVO;
import de.thorstenberger.examServer.model.TaskletAnnotationVO;
import de.thorstenberger.examServer.model.TaskletVO;
import de.thorstenberger.examServer.model.User;
import de.thorstenberger.examServer.service.ExamServerManager;
import de.thorstenberger.examServer.service.UserManager;
import de.thorstenberger.taskmodel.Annotation;
import de.thorstenberger.taskmodel.CategoryFilter;
import de.thorstenberger.taskmodel.MethodNotSupportedException;
import de.thorstenberger.taskmodel.TaskApiException;
import de.thorstenberger.taskmodel.TaskCategory;
import de.thorstenberger.taskmodel.TaskContants;
import de.thorstenberger.taskmodel.TaskDef;
import de.thorstenberger.taskmodel.TaskFactory;
import de.thorstenberger.taskmodel.TaskFilter;
import de.thorstenberger.taskmodel.TaskFilterException;
import de.thorstenberger.taskmodel.TaskModelPersistenceException;
import de.thorstenberger.taskmodel.Tasklet;
import de.thorstenberger.taskmodel.TaskletCorrection;
import de.thorstenberger.taskmodel.TaskmodelUtil;
import de.thorstenberger.taskmodel.UserInfo;
import de.thorstenberger.taskmodel.complex.ComplexTaskBuilder;
import de.thorstenberger.taskmodel.complex.ComplexTasklet;
import de.thorstenberger.taskmodel.complex.ComplexTaskletImpl;
import de.thorstenberger.taskmodel.complex.TaskDef_Complex;
import de.thorstenberger.taskmodel.complex.TaskDef_ComplexImpl;
import de.thorstenberger.taskmodel.complex.complextaskdef.ComplexTaskDefDAO;
import de.thorstenberger.taskmodel.complex.complextaskhandling.ComplexTaskHandlingDAO;
import de.thorstenberger.taskmodel.impl.AbstractTaskFactory;
import de.thorstenberger.taskmodel.impl.AnnotationImpl;
import de.thorstenberger.taskmodel.impl.TaskletCorrectionImpl;
import de.thorstenberger.taskmodel.impl.UserInfoImpl;
/**
* @author Thorsten Berger
* FIXME: move caching into TaskManagerImpl of Taskmodel-core
*/
public class TaskFactoryImpl extends AbstractTaskFactory implements TaskFactory {
// the taskhandling file is saved under user's home directory
public static final String COMPLEX_TASKHANDLING_FILE_PREFIX = "complextask_";
public static final String COMPLEX_TASKHANDLING_FILE_SUFFIX = ".xml";
public static final String COMPLEX_TASKHANDLING_BACKUP_FILE_SUFFIX = ".bak";
private List<String> availableTypes;
private ExamServerManager examServerManager;
private UserManager userManager;
private TaskDefDao taskDefDao;
private TaskHandlingDao taskHandlingDao;
private ComplexTaskDefDAO complexTaskDefDAO;
private ComplexTaskHandlingDAO complexTaskHandlingDAO;
private ComplexTaskBuilder complexTaskBuilder;
private Log log = LogFactory.getLog( "TaskLogger" );
private List<TaskDef> taskDefCache = null;
/**
*
*/
public TaskFactoryImpl( ExamServerManager examServerManager, UserManager userManager, TaskDefDao taskDefDao, TaskHandlingDao taskHandlingDao, ComplexTaskDefDAO complexTaskDefDAO, ComplexTaskHandlingDAO complexTaskHandlingDAO, ComplexTaskBuilder complexTaskBuilder ) {
this.examServerManager = examServerManager;
this.userManager = userManager;
this.taskDefDao = taskDefDao;
this.complexTaskDefDAO = complexTaskDefDAO;
this.taskHandlingDao = taskHandlingDao;
this.complexTaskHandlingDAO = complexTaskHandlingDAO;
this.complexTaskBuilder = complexTaskBuilder;
availableTypes = new ArrayList<String>();
availableTypes.add( TaskContants.TYPE_COMPLEX );
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#availableTypes()
*/
public List<String> availableTypes() {
return availableTypes;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getCategories()
*/
public List<TaskCategory> getCategories() {
throw new MethodNotSupportedException();
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getCategories(de.thorstenberger.taskmodel.CategoryFilter)
*/
public List<TaskCategory> getCategories(CategoryFilter categoryFilter) {
throw new MethodNotSupportedException();
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getTaskDef(long)
*/
public synchronized TaskDef getTaskDef(long taskId) {
List<TaskDef> taskDefs = getTaskDefs();
Iterator it = taskDefs.iterator();
while( it.hasNext() ){
TaskDef td = (TaskDef)it.next();
if( td.getId() == taskId )
return td;
}
return null;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getTaskDefs()
*/
public synchronized List<TaskDef> getTaskDefs() {
if( taskDefCache == null ){
List<TaskDefVO> taskDefVOs = taskDefDao.getTaskDefs();
taskDefCache = new ArrayList<TaskDef>();
for( TaskDefVO t : taskDefVOs ){
TaskDef_ComplexImpl tdci;
try {
tdci = new TaskDef_ComplexImpl( t.getId(), t.getTitle(),
t.getShortDescription(), t.getDeadline(), t.isStopped(), t.getFollowingTaskId(), complexTaskDefDAO, new FileInputStream( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.TASKDEFS + File.separatorChar + t.getComplexTaskFile() ) );
} catch (FileNotFoundException e) {
throw new TaskModelPersistenceException( e );
}
tdci.setShowCorrectionToUsers( t.isShowSolutionToStudents() );
tdci.setVisible( t.isVisible() );
taskDefCache.add( tdci );
}
}
return taskDefCache;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getTaskDefs(de.thorstenberger.taskmodel.TaskFilter)
*/
public List<TaskDef> getTaskDefs(TaskFilter filter)
throws TaskFilterException {
throw new MethodNotSupportedException();
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getTasklet(java.lang.String, long)
*/
public Tasklet getTasklet(String userId, long taskId) {
TaskletVO taskletVO = taskHandlingDao.getTasklet( taskId, userId );
if( taskletVO == null )
return null;
TaskDefVO taskDefVO = taskDefDao.getTaskDef( taskId );
if( taskDefVO == null )
throw new RuntimeException( "No corresponding taskDef found: " + taskId );
File homeDir = new File( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.HOME + File.separatorChar + userId );
File complexTaskHandlingFile = new File( homeDir.getAbsolutePath() + File.separatorChar + COMPLEX_TASKHANDLING_FILE_PREFIX + taskId + COMPLEX_TASKHANDLING_FILE_SUFFIX );
return instantiateTasklet( taskletVO, taskDefVO, complexTaskHandlingFile );
}
private Tasklet instantiateTasklet( TaskletVO taskletVO, TaskDefVO taskDefVO, File complexTaskHandlingFile ){
// for now, we just support one corrector annotation
String correctorAnnotation = null;
if( taskletVO.getCorrectorAnnotations().size() > 0 )
correctorAnnotation = taskletVO.getCorrectorAnnotations().get( 0 ).getText();
List<Annotation> studentAnnotations = new ArrayList<Annotation>();
for( TaskletAnnotationVO tavo : taskletVO.getStudentAnnotations() )
studentAnnotations.add( new AnnotationImpl( tavo.getText(), tavo.getDate(), tavo.isAcknowledged() ) );
TaskletCorrection correction =
new TaskletCorrectionImpl( taskletVO.getPoints(), correctorAnnotation,
taskletVO.getCorrectorLogin(), taskletVO.getCorrectorHistory(), studentAnnotations );
FileInputStream fis;
try {
if( !complexTaskHandlingFile.exists() )
complexTaskHandlingFile.createNewFile();
fis = new FileInputStream( complexTaskHandlingFile );
}catch( IOException e ){
throw new TaskModelPersistenceException( e );
}
ComplexTasklet tasklet =
new ComplexTaskletImpl( this, complexTaskBuilder, taskletVO.getLogin(), taskDefVO.getId(),
TaskmodelUtil.getStatus( taskletVO.getStatus() ), taskletVO.getFlags(), correction, (TaskDef_Complex)getTaskDef( taskDefVO.getId() ), complexTaskHandlingDAO, fis );
return tasklet;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#createTasklet(java.lang.String, long)
*/
public Tasklet createTasklet(String userId, long taskId)
throws TaskApiException {
TaskletVO taskletVO = taskHandlingDao.getTasklet( taskId, userId );
TaskDefVO taskDefVO = taskDefDao.getTaskDef( taskId );
if( taskDefVO == null )
throw new TaskApiException( "TaskDef " + taskId + " does not exist!" );
if( taskletVO != null )
throw new TaskApiException( "Tasklet (" + userId + ", " + taskId + ") does already exist!" );
taskletVO = new TaskletVO();
taskletVO.setLogin( userId );
taskletVO.setTaskDefId( taskId );
taskletVO.setStatus( Tasklet.Status.INITIALIZED.getValue() );
taskletVO.setPoints( null );
taskletVO.setFlags( new ArrayList<String>() );
taskletVO.setStudentAnnotations( new ArrayList<TaskletAnnotationVO>() );
taskletVO.setCorrectorAnnotations( new ArrayList<TaskletAnnotationVO>() );
File homeDir = new File( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.HOME + File.separatorChar + userId );
if( !homeDir.exists() )
homeDir.mkdirs();
File complexTaskHandlingFile = new File( homeDir.getAbsolutePath() + File.separatorChar + COMPLEX_TASKHANDLING_FILE_PREFIX + taskId + COMPLEX_TASKHANDLING_FILE_SUFFIX );
taskHandlingDao.saveTasklet( taskletVO );
return instantiateTasklet( taskletVO, taskDefVO, complexTaskHandlingFile );
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getTasklets(long)
*/
public List<Tasklet> getTasklets(long taskId) {
List<Tasklet> ret = new ArrayList<Tasklet>();
List<TaskletVO> taskletVOs = taskHandlingDao.getTasklets( taskId );
TaskDefVO taskDefVO = taskDefDao.getTaskDef( taskId );
for( TaskletVO taskletVO : taskletVOs ){
File homeDir = new File( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.HOME + File.separatorChar + taskletVO.getLogin() );
File complexTaskHandlingFile = new File( homeDir.getAbsolutePath() + File.separatorChar + COMPLEX_TASKHANDLING_FILE_PREFIX + taskId + COMPLEX_TASKHANDLING_FILE_SUFFIX );
ret.add( instantiateTasklet( taskletVO, taskDefVO, complexTaskHandlingFile ) );
}
return ret;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.impl.AbstractTaskFactory#getUserIdsOfAvailableTasklets(long)
*/
@Override
public List<String> getUserIdsOfAvailableTasklets(long taskId) {
return taskHandlingDao.getUserIdsOfAvailableTasklets( taskId );
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.impl.AbstractTaskFactory#getUserIdsOfTaskletsAssignedToCorrector(long, java.lang.String, boolean)
*/
@Override
public List<String> getUserIdsOfTaskletsAssignedToCorrector(long taskId, String correctorId) {
return taskHandlingDao.getUserIdsOfTaskletsAssignedToCorrector( taskId, correctorId );
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#storeTasklet(de.thorstenberger.taskmodel.Tasklet)
*/
public void storeTasklet(Tasklet tasklet) throws TaskApiException {
TaskletVO taskletVO = taskHandlingDao.getTasklet( tasklet.getTaskId(), tasklet.getUserId() );
boolean changed = false;
if( taskletVO == null ){
taskletVO = new TaskletVO();
changed = true;
}
if( taskletVO.getTaskDefId() != tasklet.getTaskId() ){
taskletVO.setTaskDefId( tasklet.getTaskId() );
changed = true;
}
if( objectsDiffer( taskletVO.getLogin(), tasklet.getUserId() ) ){
taskletVO.setLogin( tasklet.getUserId() );
changed = true;
}
if( objectsDiffer( taskletVO.getStatus(), tasklet.getStatus().getValue() ) ){
taskletVO.setStatus( tasklet.getStatus().getValue() );
changed = true;
}
if( objectsDiffer( taskletVO.getCorrectorLogin(), tasklet.getTaskletCorrection().getCorrector() ) ){
taskletVO.setCorrectorLogin( tasklet.getTaskletCorrection().getCorrector() );
changed = true;
}
try {
if( objectsDiffer( taskletVO.getCorrectorAnnotations().get( 0 ).getText(), tasklet.getTaskletCorrection().getCorrectorAnnotation() ) ){
taskletVO.getCorrectorAnnotations().get(0).setText( tasklet.getTaskletCorrection().getCorrectorAnnotation() );
changed = true;
}
} catch (IndexOutOfBoundsException e) {
if( tasklet.getTaskletCorrection().getCorrectorAnnotation() != null )
taskletVO.getCorrectorAnnotations().add( 0, new TaskletAnnotationVO( tasklet.getTaskletCorrection().getCorrectorAnnotation(), null, false ) );
changed = true;
}
if( objectsDiffer( taskletVO.getPoints(), tasklet.getTaskletCorrection().getPoints() ) ){
taskletVO.setPoints( tasklet.getTaskletCorrection().getPoints() );
changed = true;
}
if( objectsDiffer( taskletVO.getCorrectorHistory(), tasklet.getTaskletCorrection().getCorrectorHistory() ) ){
taskletVO.setCorrectorHistory( tasklet.getTaskletCorrection().getCorrectorHistory() );
changed = true;
}
if( objectsDiffer( taskletVO.getFlags(), tasklet.getFlags() ) ){
taskletVO.setFlags( tasklet.getFlags() );
changed = true;
}
if( taskletVO.getStudentAnnotations().size() != tasklet.getTaskletCorrection().getStudentAnnotations().size() ){
taskletVO.setStudentAnnotations( copyAnnotations( tasklet.getTaskletCorrection().getStudentAnnotations() ) );
changed = true;
}else{
for( int i = 0; i < tasklet.getTaskletCorrection().getStudentAnnotations().size(); i++ ){
Annotation a = tasklet.getTaskletCorrection().getStudentAnnotations().get( i );
TaskletAnnotationVO tavo = taskletVO.getStudentAnnotations().get( i );
- if( objectsDiffer( a.getText(), tavo.getText() ) || objectsDiffer( a.getDate(), tavo.getDate() ) ){
+ if( objectsDiffer( a.getText(), tavo.getText() ) || objectsDiffer( a.getDate(), tavo.getDate() ) || objectsDiffer( a.isAcknowledged(), tavo.isAcknowledged() ) ){
taskletVO.setStudentAnnotations( copyAnnotations( tasklet.getTaskletCorrection().getStudentAnnotations() ) );
changed = true;
break;
}
}
}
if( tasklet instanceof ComplexTasklet ){
// get the taskHandling xml file!
File homeDir = new File( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.HOME + File.separatorChar + tasklet.getUserId() );
String pathOfCTHfile = homeDir.getAbsolutePath() + File.separatorChar + COMPLEX_TASKHANDLING_FILE_PREFIX + tasklet.getTaskId() + COMPLEX_TASKHANDLING_FILE_SUFFIX;
File complexTaskHandlingFile = new File( pathOfCTHfile );
ComplexTasklet ct = (ComplexTasklet)tasklet;
try {
File backup = new File( pathOfCTHfile + COMPLEX_TASKHANDLING_BACKUP_FILE_SUFFIX );
backup.delete();
complexTaskHandlingFile.renameTo( backup );
complexTaskHandlingFile = new File( pathOfCTHfile );
complexTaskHandlingDAO.save( ct.getComplexTaskHandlingRoot(), new FileOutputStream( complexTaskHandlingFile ) );
} catch (FileNotFoundException e) {
throw new TaskModelPersistenceException( e );
}
}
if( changed )
taskHandlingDao.saveTasklet( taskletVO );
}
private List<TaskletAnnotationVO> copyAnnotations( List<Annotation> annotations ){
List<TaskletAnnotationVO> ret = new ArrayList<TaskletAnnotationVO>();
for( Annotation a : annotations )
ret.add( new TaskletAnnotationVO( a.getText(), a.getDate(), a.isAcknowledged() ) );
return ret;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#removeTasklet(java.lang.String, long)
*/
public void removeTasklet(String userId, long taskId)
throws TaskApiException {
throw new MethodNotSupportedException();
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#logPostData(java.lang.String, de.thorstenberger.taskmodel.Tasklet, java.lang.String)
*/
public void logPostData(String msg, Tasklet tasklet, String ip) {
String prefix = tasklet.getUserId() + "@" + ip + ": ";
log.info( prefix + msg );
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#logPostData(java.lang.String, java.lang.Throwable, de.thorstenberger.taskmodel.Tasklet, java.lang.String)
*/
public void logPostData(String msg, Throwable throwable, Tasklet tasklet, String ip) {
String prefix = tasklet.getUserId() + "@" + ip + ": ";
log.info( prefix + msg, throwable );
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.TaskFactory#getUserInfo(java.lang.String)
*/
public UserInfo getUserInfo(String login) {
User user;
try {
user = userManager.getUserByUsername( login );
} catch (UsernameNotFoundException e) {
return null;
}
UserInfoImpl ret = new UserInfoImpl();
ret.setLogin( user.getUsername() );
ret.setFirstName( user.getFirstName() );
ret.setName( user.getLastName() );
ret.setEMail( user.getEmail() );
return ret;
}
private boolean objectsDiffer( Object a, Object b ){
if( a == null && b == null )
return false;
if( a == null && b != null )
return true;
if( b == null && a != null )
return true;
return !a.equals( b );
}
}
| true | true | public void storeTasklet(Tasklet tasklet) throws TaskApiException {
TaskletVO taskletVO = taskHandlingDao.getTasklet( tasklet.getTaskId(), tasklet.getUserId() );
boolean changed = false;
if( taskletVO == null ){
taskletVO = new TaskletVO();
changed = true;
}
if( taskletVO.getTaskDefId() != tasklet.getTaskId() ){
taskletVO.setTaskDefId( tasklet.getTaskId() );
changed = true;
}
if( objectsDiffer( taskletVO.getLogin(), tasklet.getUserId() ) ){
taskletVO.setLogin( tasklet.getUserId() );
changed = true;
}
if( objectsDiffer( taskletVO.getStatus(), tasklet.getStatus().getValue() ) ){
taskletVO.setStatus( tasklet.getStatus().getValue() );
changed = true;
}
if( objectsDiffer( taskletVO.getCorrectorLogin(), tasklet.getTaskletCorrection().getCorrector() ) ){
taskletVO.setCorrectorLogin( tasklet.getTaskletCorrection().getCorrector() );
changed = true;
}
try {
if( objectsDiffer( taskletVO.getCorrectorAnnotations().get( 0 ).getText(), tasklet.getTaskletCorrection().getCorrectorAnnotation() ) ){
taskletVO.getCorrectorAnnotations().get(0).setText( tasklet.getTaskletCorrection().getCorrectorAnnotation() );
changed = true;
}
} catch (IndexOutOfBoundsException e) {
if( tasklet.getTaskletCorrection().getCorrectorAnnotation() != null )
taskletVO.getCorrectorAnnotations().add( 0, new TaskletAnnotationVO( tasklet.getTaskletCorrection().getCorrectorAnnotation(), null, false ) );
changed = true;
}
if( objectsDiffer( taskletVO.getPoints(), tasklet.getTaskletCorrection().getPoints() ) ){
taskletVO.setPoints( tasklet.getTaskletCorrection().getPoints() );
changed = true;
}
if( objectsDiffer( taskletVO.getCorrectorHistory(), tasklet.getTaskletCorrection().getCorrectorHistory() ) ){
taskletVO.setCorrectorHistory( tasklet.getTaskletCorrection().getCorrectorHistory() );
changed = true;
}
if( objectsDiffer( taskletVO.getFlags(), tasklet.getFlags() ) ){
taskletVO.setFlags( tasklet.getFlags() );
changed = true;
}
if( taskletVO.getStudentAnnotations().size() != tasklet.getTaskletCorrection().getStudentAnnotations().size() ){
taskletVO.setStudentAnnotations( copyAnnotations( tasklet.getTaskletCorrection().getStudentAnnotations() ) );
changed = true;
}else{
for( int i = 0; i < tasklet.getTaskletCorrection().getStudentAnnotations().size(); i++ ){
Annotation a = tasklet.getTaskletCorrection().getStudentAnnotations().get( i );
TaskletAnnotationVO tavo = taskletVO.getStudentAnnotations().get( i );
if( objectsDiffer( a.getText(), tavo.getText() ) || objectsDiffer( a.getDate(), tavo.getDate() ) ){
taskletVO.setStudentAnnotations( copyAnnotations( tasklet.getTaskletCorrection().getStudentAnnotations() ) );
changed = true;
break;
}
}
}
if( tasklet instanceof ComplexTasklet ){
// get the taskHandling xml file!
File homeDir = new File( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.HOME + File.separatorChar + tasklet.getUserId() );
String pathOfCTHfile = homeDir.getAbsolutePath() + File.separatorChar + COMPLEX_TASKHANDLING_FILE_PREFIX + tasklet.getTaskId() + COMPLEX_TASKHANDLING_FILE_SUFFIX;
File complexTaskHandlingFile = new File( pathOfCTHfile );
ComplexTasklet ct = (ComplexTasklet)tasklet;
try {
File backup = new File( pathOfCTHfile + COMPLEX_TASKHANDLING_BACKUP_FILE_SUFFIX );
backup.delete();
complexTaskHandlingFile.renameTo( backup );
complexTaskHandlingFile = new File( pathOfCTHfile );
complexTaskHandlingDAO.save( ct.getComplexTaskHandlingRoot(), new FileOutputStream( complexTaskHandlingFile ) );
} catch (FileNotFoundException e) {
throw new TaskModelPersistenceException( e );
}
}
if( changed )
taskHandlingDao.saveTasklet( taskletVO );
}
| public void storeTasklet(Tasklet tasklet) throws TaskApiException {
TaskletVO taskletVO = taskHandlingDao.getTasklet( tasklet.getTaskId(), tasklet.getUserId() );
boolean changed = false;
if( taskletVO == null ){
taskletVO = new TaskletVO();
changed = true;
}
if( taskletVO.getTaskDefId() != tasklet.getTaskId() ){
taskletVO.setTaskDefId( tasklet.getTaskId() );
changed = true;
}
if( objectsDiffer( taskletVO.getLogin(), tasklet.getUserId() ) ){
taskletVO.setLogin( tasklet.getUserId() );
changed = true;
}
if( objectsDiffer( taskletVO.getStatus(), tasklet.getStatus().getValue() ) ){
taskletVO.setStatus( tasklet.getStatus().getValue() );
changed = true;
}
if( objectsDiffer( taskletVO.getCorrectorLogin(), tasklet.getTaskletCorrection().getCorrector() ) ){
taskletVO.setCorrectorLogin( tasklet.getTaskletCorrection().getCorrector() );
changed = true;
}
try {
if( objectsDiffer( taskletVO.getCorrectorAnnotations().get( 0 ).getText(), tasklet.getTaskletCorrection().getCorrectorAnnotation() ) ){
taskletVO.getCorrectorAnnotations().get(0).setText( tasklet.getTaskletCorrection().getCorrectorAnnotation() );
changed = true;
}
} catch (IndexOutOfBoundsException e) {
if( tasklet.getTaskletCorrection().getCorrectorAnnotation() != null )
taskletVO.getCorrectorAnnotations().add( 0, new TaskletAnnotationVO( tasklet.getTaskletCorrection().getCorrectorAnnotation(), null, false ) );
changed = true;
}
if( objectsDiffer( taskletVO.getPoints(), tasklet.getTaskletCorrection().getPoints() ) ){
taskletVO.setPoints( tasklet.getTaskletCorrection().getPoints() );
changed = true;
}
if( objectsDiffer( taskletVO.getCorrectorHistory(), tasklet.getTaskletCorrection().getCorrectorHistory() ) ){
taskletVO.setCorrectorHistory( tasklet.getTaskletCorrection().getCorrectorHistory() );
changed = true;
}
if( objectsDiffer( taskletVO.getFlags(), tasklet.getFlags() ) ){
taskletVO.setFlags( tasklet.getFlags() );
changed = true;
}
if( taskletVO.getStudentAnnotations().size() != tasklet.getTaskletCorrection().getStudentAnnotations().size() ){
taskletVO.setStudentAnnotations( copyAnnotations( tasklet.getTaskletCorrection().getStudentAnnotations() ) );
changed = true;
}else{
for( int i = 0; i < tasklet.getTaskletCorrection().getStudentAnnotations().size(); i++ ){
Annotation a = tasklet.getTaskletCorrection().getStudentAnnotations().get( i );
TaskletAnnotationVO tavo = taskletVO.getStudentAnnotations().get( i );
if( objectsDiffer( a.getText(), tavo.getText() ) || objectsDiffer( a.getDate(), tavo.getDate() ) || objectsDiffer( a.isAcknowledged(), tavo.isAcknowledged() ) ){
taskletVO.setStudentAnnotations( copyAnnotations( tasklet.getTaskletCorrection().getStudentAnnotations() ) );
changed = true;
break;
}
}
}
if( tasklet instanceof ComplexTasklet ){
// get the taskHandling xml file!
File homeDir = new File( examServerManager.getRepositoryFile().getAbsolutePath() + File.separatorChar + ExamServerManager.HOME + File.separatorChar + tasklet.getUserId() );
String pathOfCTHfile = homeDir.getAbsolutePath() + File.separatorChar + COMPLEX_TASKHANDLING_FILE_PREFIX + tasklet.getTaskId() + COMPLEX_TASKHANDLING_FILE_SUFFIX;
File complexTaskHandlingFile = new File( pathOfCTHfile );
ComplexTasklet ct = (ComplexTasklet)tasklet;
try {
File backup = new File( pathOfCTHfile + COMPLEX_TASKHANDLING_BACKUP_FILE_SUFFIX );
backup.delete();
complexTaskHandlingFile.renameTo( backup );
complexTaskHandlingFile = new File( pathOfCTHfile );
complexTaskHandlingDAO.save( ct.getComplexTaskHandlingRoot(), new FileOutputStream( complexTaskHandlingFile ) );
} catch (FileNotFoundException e) {
throw new TaskModelPersistenceException( e );
}
}
if( changed )
taskHandlingDao.saveTasklet( taskletVO );
}
|
diff --git a/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java b/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java
index dcefe7f8c..ee94797ba 100644
--- a/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java
+++ b/src/main/java/tconstruct/armor/modelblock/DryingRackSpecialRender.java
@@ -1,99 +1,95 @@
package tconstruct.armor.modelblock;
import cpw.mods.fml.relauncher.*;
import net.minecraft.client.renderer.entity.*;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.item.*;
import net.minecraft.tileentity.TileEntity;
import org.lwjgl.opengl.GL11;
import tconstruct.blocks.logic.DryingRackLogic;
import tconstruct.tools.entity.FancyEntityItem;
/* Special renderer, only used for drawing tools */
@SideOnly(Side.CLIENT)
public class DryingRackSpecialRender extends TileEntitySpecialRenderer
{
public void render (DryingRackLogic logic, double posX, double posY, double posZ, float var8)
{
GL11.glPushMatrix();
float var10 = (float) (posX - 0.5F);
float var11 = (float) (posY - 0.5F);
float var12 = (float) (posZ - 0.5F);
GL11.glTranslatef(var10, var11, var12);
this.func_82402_b(logic);
GL11.glPopMatrix();
}
private void func_82402_b (DryingRackLogic logic)
{
ItemStack stack = logic.getStackInSlot(0);
if (stack != null)
renderItem(logic, stack);
}
void renderItem (DryingRackLogic logic, ItemStack stack)
{
FancyEntityItem entityitem = new FancyEntityItem(logic.getWorldObj(), 0.0D, 0.0D, 0.0D, stack);
entityitem.getEntityItem().stackSize = 1;
entityitem.hoverStart = 0.0F;
GL11.glPushMatrix();
int meta = logic.getWorldObj().getBlockMetadata(logic.xCoord, logic.yCoord, logic.zCoord);
if (meta <= 1)
GL11.glTranslatef(1F, -0.375F, 0.905F);
else
{
GL11.glTranslatef(1F, 0.375F, 0.905F);
if (meta / 2 == 2)
{
GL11.glRotatef(90F, 0F, 1F, 0F);
GL11.glTranslatef(-0.0625F, 0F, 0F);
}
if (meta == 2)
GL11.glTranslatef(0F, 0F, 0.375F);
if (meta == 3)
{
- /**
- * Rotate the image as it is flipped, translate to the correct spot.
- */
+ // Rotate, Flip.
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(0F, 0F, 0.2F);
//GL11.glTranslatef(0F, 0F, -0.375F);
}
if (meta == 4)
{
GL11.glTranslatef(0F, 0F, 0.2875F);
}
if (meta == 5)
{
- /**
- * Rotate the image as it is flipped, translate to the correct spot.
- */
+ //Rotate, Flip.
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(0F, 0F, 0.3F);
//GL11.glTranslatef(0F, 0F, -0.5F);
}
}
GL11.glScalef(2F, 2F, 2F);
if (stack.getItem() instanceof ItemBlock)
{
// GL11.glRotatef(90F, -1, 0F, 0F);
GL11.glTranslatef(0F, 0.2125F, 0.0375F);
}
RenderItem.renderInFrame = true;
RenderManager.instance.renderEntityWithPosYaw(entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F);
RenderItem.renderInFrame = false;
GL11.glPopMatrix();
}
@Override
public void renderTileEntityAt (TileEntity logic, double var2, double var4, double var6, float var8)
{
this.render((DryingRackLogic) logic, var2, var4, var6, var8);
}
}
| false | true | void renderItem (DryingRackLogic logic, ItemStack stack)
{
FancyEntityItem entityitem = new FancyEntityItem(logic.getWorldObj(), 0.0D, 0.0D, 0.0D, stack);
entityitem.getEntityItem().stackSize = 1;
entityitem.hoverStart = 0.0F;
GL11.glPushMatrix();
int meta = logic.getWorldObj().getBlockMetadata(logic.xCoord, logic.yCoord, logic.zCoord);
if (meta <= 1)
GL11.glTranslatef(1F, -0.375F, 0.905F);
else
{
GL11.glTranslatef(1F, 0.375F, 0.905F);
if (meta / 2 == 2)
{
GL11.glRotatef(90F, 0F, 1F, 0F);
GL11.glTranslatef(-0.0625F, 0F, 0F);
}
if (meta == 2)
GL11.glTranslatef(0F, 0F, 0.375F);
if (meta == 3)
{
/**
* Rotate the image as it is flipped, translate to the correct spot.
*/
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(0F, 0F, 0.2F);
//GL11.glTranslatef(0F, 0F, -0.375F);
}
if (meta == 4)
{
GL11.glTranslatef(0F, 0F, 0.2875F);
}
if (meta == 5)
{
/**
* Rotate the image as it is flipped, translate to the correct spot.
*/
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(0F, 0F, 0.3F);
//GL11.glTranslatef(0F, 0F, -0.5F);
}
}
GL11.glScalef(2F, 2F, 2F);
if (stack.getItem() instanceof ItemBlock)
{
// GL11.glRotatef(90F, -1, 0F, 0F);
GL11.glTranslatef(0F, 0.2125F, 0.0375F);
}
RenderItem.renderInFrame = true;
RenderManager.instance.renderEntityWithPosYaw(entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F);
RenderItem.renderInFrame = false;
GL11.glPopMatrix();
}
| void renderItem (DryingRackLogic logic, ItemStack stack)
{
FancyEntityItem entityitem = new FancyEntityItem(logic.getWorldObj(), 0.0D, 0.0D, 0.0D, stack);
entityitem.getEntityItem().stackSize = 1;
entityitem.hoverStart = 0.0F;
GL11.glPushMatrix();
int meta = logic.getWorldObj().getBlockMetadata(logic.xCoord, logic.yCoord, logic.zCoord);
if (meta <= 1)
GL11.glTranslatef(1F, -0.375F, 0.905F);
else
{
GL11.glTranslatef(1F, 0.375F, 0.905F);
if (meta / 2 == 2)
{
GL11.glRotatef(90F, 0F, 1F, 0F);
GL11.glTranslatef(-0.0625F, 0F, 0F);
}
if (meta == 2)
GL11.glTranslatef(0F, 0F, 0.375F);
if (meta == 3)
{
// Rotate, Flip.
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(0F, 0F, 0.2F);
//GL11.glTranslatef(0F, 0F, -0.375F);
}
if (meta == 4)
{
GL11.glTranslatef(0F, 0F, 0.2875F);
}
if (meta == 5)
{
//Rotate, Flip.
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(0F, 0F, 0.3F);
//GL11.glTranslatef(0F, 0F, -0.5F);
}
}
GL11.glScalef(2F, 2F, 2F);
if (stack.getItem() instanceof ItemBlock)
{
// GL11.glRotatef(90F, -1, 0F, 0F);
GL11.glTranslatef(0F, 0.2125F, 0.0375F);
}
RenderItem.renderInFrame = true;
RenderManager.instance.renderEntityWithPosYaw(entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F);
RenderItem.renderInFrame = false;
GL11.glPopMatrix();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.