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/com/massivecraft/factions/integration/LWCFeatures.java b/src/com/massivecraft/factions/integration/LWCFeatures.java
index 837b7094..9cacb807 100644
--- a/src/com/massivecraft/factions/integration/LWCFeatures.java
+++ b/src/com/massivecraft/factions/integration/LWCFeatures.java
@@ -1,86 +1,86 @@
package com.massivecraft.factions.integration;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.griefcraft.lwc.LWC;
import com.griefcraft.lwc.LWCPlugin;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
public class LWCFeatures
{
private static LWC lwc;
public static void integrateLWC(LWCPlugin test)
{
lwc = test.getLWC();
P.p.log("Successfully hooked into LWC!"+(Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\")."));
}
public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
- if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getBukkitOwner())))
+ if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static void clearAllChests(FLocation flocation)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static boolean getEnabled()
{
return Conf.lwcIntegration && lwc != null;
}
}
| true | true | public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getBukkitOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
| public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
|
diff --git a/src/com/boh/flatmate/FlatFragment.java b/src/com/boh/flatmate/FlatFragment.java
index 49893d9..489dffa 100644
--- a/src/com/boh/flatmate/FlatFragment.java
+++ b/src/com/boh/flatmate/FlatFragment.java
@@ -1,110 +1,111 @@
package com.boh.flatmate;
import com.boh.flatmate.R;
import com.boh.flatmate.FlatMate.FlatDataExchanger;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class FlatFragment extends Fragment {
private ViewGroup c;
FlatListFragment flatList;
private int debtsOpen = 0;
private int settingsOpen = 0;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v1 = inflater.inflate(R.layout.flat_mate_page, container, false);
c = container;
return v1;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
flatList = new FlatListFragment();
//ft.setCustomAnimations(R.anim.slide_up_in, R.anim.slide_out_down);
ft.replace(R.id.list, flatList,"flat_fragment");
ft.commit();
if(settingsOpen == 1){
+ android.support.v4.app.FragmentTransaction ft2 = getFragmentManager().beginTransaction();
Fragment settings = new FlatSettingsFragment();
//ft.setCustomAnimations(R.anim.slide_up_in, R.anim.slide_out_down);
- ft.replace(R.id.list, settings,"Set_fragment");
- ft.addToBackStack(null);
- ft.commit();
+ ft2.replace(R.id.list, settings,"Set_fragment");
+ ft2.addToBackStack(null);
+ ft2.commit();
((ImageView) c.findViewById(R.id.settingsButton)).setImageResource(R.drawable.flatmates_tab);
c.findViewById(R.id.map_button).setVisibility(View.GONE);
}
final Button button = (Button) c.findViewById(R.id.map_button);
button.setText("View Debts");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(debtsOpen == 0){
button.setText("View Contact Buttons");
debtsOpen = 1;
flatList.setDebtsVisible(1);
}else{
debtsOpen = 0;
button.setText("View Debts");
flatList.setDebtsVisible(0);
}
}
});
getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener(){
public void onBackStackChanged(){
if(settingsOpen == 1 && getFragmentManager().getBackStackEntryCount() == 0){
settingsOpen = 0;
button.setVisibility(View.VISIBLE);
}
}
});
final ImageButton settings = (ImageButton) c.findViewById(R.id.settingsButton);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(settingsOpen == 0){
settingsOpen = 1;
settings.setImageResource(R.drawable.flatmates_tab);
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment set = new FlatSettingsFragment();
ft.replace(R.id.list, set, "Set_fragment");
ft.addToBackStack(null);
ft.commit();
button.setVisibility(View.GONE);
}else{
settingsOpen = 0;
settings.setImageResource(R.drawable.settings);
getFragmentManager().popBackStack();
button.setVisibility(View.VISIBLE);
}
}
});
- TextView flatName = (TextView) c.findViewById(R.id.flatName);
+ TextView flatName = (TextView) c.findViewById(R.id.flatNameTop);
flatName.setText(FlatDataExchanger.flatData.getNickname());
TextView atFlat = (TextView) c.findViewById(R.id.atFlatText);
atFlat.setText(FlatDataExchanger.flatData.getNoAtFlat()+" flat mates at home");
ImageButton messageButton = (ImageButton)c.findViewById(R.id.messageButton);
messageButton.setOnClickListener(FlatDataExchanger.flatData.messageListener);
}
}
| false | true | public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
flatList = new FlatListFragment();
//ft.setCustomAnimations(R.anim.slide_up_in, R.anim.slide_out_down);
ft.replace(R.id.list, flatList,"flat_fragment");
ft.commit();
if(settingsOpen == 1){
Fragment settings = new FlatSettingsFragment();
//ft.setCustomAnimations(R.anim.slide_up_in, R.anim.slide_out_down);
ft.replace(R.id.list, settings,"Set_fragment");
ft.addToBackStack(null);
ft.commit();
((ImageView) c.findViewById(R.id.settingsButton)).setImageResource(R.drawable.flatmates_tab);
c.findViewById(R.id.map_button).setVisibility(View.GONE);
}
final Button button = (Button) c.findViewById(R.id.map_button);
button.setText("View Debts");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(debtsOpen == 0){
button.setText("View Contact Buttons");
debtsOpen = 1;
flatList.setDebtsVisible(1);
}else{
debtsOpen = 0;
button.setText("View Debts");
flatList.setDebtsVisible(0);
}
}
});
getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener(){
public void onBackStackChanged(){
if(settingsOpen == 1 && getFragmentManager().getBackStackEntryCount() == 0){
settingsOpen = 0;
button.setVisibility(View.VISIBLE);
}
}
});
final ImageButton settings = (ImageButton) c.findViewById(R.id.settingsButton);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(settingsOpen == 0){
settingsOpen = 1;
settings.setImageResource(R.drawable.flatmates_tab);
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment set = new FlatSettingsFragment();
ft.replace(R.id.list, set, "Set_fragment");
ft.addToBackStack(null);
ft.commit();
button.setVisibility(View.GONE);
}else{
settingsOpen = 0;
settings.setImageResource(R.drawable.settings);
getFragmentManager().popBackStack();
button.setVisibility(View.VISIBLE);
}
}
});
TextView flatName = (TextView) c.findViewById(R.id.flatName);
flatName.setText(FlatDataExchanger.flatData.getNickname());
TextView atFlat = (TextView) c.findViewById(R.id.atFlatText);
atFlat.setText(FlatDataExchanger.flatData.getNoAtFlat()+" flat mates at home");
ImageButton messageButton = (ImageButton)c.findViewById(R.id.messageButton);
messageButton.setOnClickListener(FlatDataExchanger.flatData.messageListener);
}
| public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
flatList = new FlatListFragment();
//ft.setCustomAnimations(R.anim.slide_up_in, R.anim.slide_out_down);
ft.replace(R.id.list, flatList,"flat_fragment");
ft.commit();
if(settingsOpen == 1){
android.support.v4.app.FragmentTransaction ft2 = getFragmentManager().beginTransaction();
Fragment settings = new FlatSettingsFragment();
//ft.setCustomAnimations(R.anim.slide_up_in, R.anim.slide_out_down);
ft2.replace(R.id.list, settings,"Set_fragment");
ft2.addToBackStack(null);
ft2.commit();
((ImageView) c.findViewById(R.id.settingsButton)).setImageResource(R.drawable.flatmates_tab);
c.findViewById(R.id.map_button).setVisibility(View.GONE);
}
final Button button = (Button) c.findViewById(R.id.map_button);
button.setText("View Debts");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(debtsOpen == 0){
button.setText("View Contact Buttons");
debtsOpen = 1;
flatList.setDebtsVisible(1);
}else{
debtsOpen = 0;
button.setText("View Debts");
flatList.setDebtsVisible(0);
}
}
});
getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener(){
public void onBackStackChanged(){
if(settingsOpen == 1 && getFragmentManager().getBackStackEntryCount() == 0){
settingsOpen = 0;
button.setVisibility(View.VISIBLE);
}
}
});
final ImageButton settings = (ImageButton) c.findViewById(R.id.settingsButton);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(settingsOpen == 0){
settingsOpen = 1;
settings.setImageResource(R.drawable.flatmates_tab);
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment set = new FlatSettingsFragment();
ft.replace(R.id.list, set, "Set_fragment");
ft.addToBackStack(null);
ft.commit();
button.setVisibility(View.GONE);
}else{
settingsOpen = 0;
settings.setImageResource(R.drawable.settings);
getFragmentManager().popBackStack();
button.setVisibility(View.VISIBLE);
}
}
});
TextView flatName = (TextView) c.findViewById(R.id.flatNameTop);
flatName.setText(FlatDataExchanger.flatData.getNickname());
TextView atFlat = (TextView) c.findViewById(R.id.atFlatText);
atFlat.setText(FlatDataExchanger.flatData.getNoAtFlat()+" flat mates at home");
ImageButton messageButton = (ImageButton)c.findViewById(R.id.messageButton);
messageButton.setOnClickListener(FlatDataExchanger.flatData.messageListener);
}
|
diff --git a/test-runner/android/test/ActivityUnitTestCase.java b/test-runner/android/test/ActivityUnitTestCase.java
index dfd8fc24f1..6bd19a6223 100644
--- a/test-runner/android/test/ActivityUnitTestCase.java
+++ b/test-runner/android/test/ActivityUnitTestCase.java
@@ -1,340 +1,340 @@
/*
* Copyright (C) 2008 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 android.test;
import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.test.mock.MockApplication;
import android.view.Window;
/**
* This class provides isolated testing of a single activity. The activity under test will
* be created with minimal connection to the system infrastructure, and you can inject mocked or
* wrappered versions of many of Activity's dependencies. Most of the work is handled
* automatically here by {@link #setUp} and {@link #tearDown}.
*
* <p>If you prefer a functional test, see {@link android.test.ActivityInstrumentationTestCase}.
*
* <p>It must be noted that, as a true unit test, your Activity will not be running in the
* normal system and will not participate in the normal interactions with other Activities.
* The following methods should not be called in this configuration - most of them will throw
* exceptions:
* <ul>
* <li>{@link android.app.Activity#createPendingResult(int, Intent, int)}</li>
* <li>{@link android.app.Activity#startActivityIfNeeded(Intent, int)}</li>
* <li>{@link android.app.Activity#startActivityFromChild(Activity, Intent, int)}</li>
* <li>{@link android.app.Activity#startNextMatchingActivity(Intent)}</li>
* <li>{@link android.app.Activity#getCallingActivity()}</li>
* <li>{@link android.app.Activity#getCallingPackage()}</li>
* <li>{@link android.app.Activity#createPendingResult(int, Intent, int)}</li>
* <li>{@link android.app.Activity#getTaskId()}</li>
* <li>{@link android.app.Activity#isTaskRoot()}</li>
* <li>{@link android.app.Activity#moveTaskToBack(boolean)}</li>
* <li>{@link android.app.Activity#setPersistent(boolean)}</li>
* </ul>
*
* <p>The following methods may be called but will not do anything. For test purposes, you can use
* the methods {@link #getStartedActivityIntent()} and {@link #getStartedActivityRequest()} to
* inspect the parameters that they were called with.
* <ul>
* <li>{@link android.app.Activity#startActivity(Intent)}</li>
* <li>{@link android.app.Activity#startActivityForResult(Intent, int)}</li>
* </ul>
*
* <p>The following methods may be called but will not do anything. For test purposes, you can use
* the methods {@link #isFinishCalled()} and {@link #getFinishedActivityRequest()} to inspect the
* parameters that they were called with.
* <ul>
* <li>{@link android.app.Activity#finish()}</li>
* <li>{@link android.app.Activity#finishFromChild(Activity child)}</li>
* <li>{@link android.app.Activity#finishActivity(int requestCode)}</li>
* </ul>
*
*/
public abstract class ActivityUnitTestCase<T extends Activity>
extends ActivityTestCase {
private Class<T> mActivityClass;
private Context mActivityContext;
private Application mApplication;
private MockParent mMockParent;
private boolean mAttached = false;
private boolean mCreated = false;
public ActivityUnitTestCase(Class<T> activityClass) {
mActivityClass = activityClass;
}
@Override
public T getActivity() {
return (T) super.getActivity();
}
@Override
protected void setUp() throws Exception {
super.setUp();
// default value for target context, as a default
mActivityContext = getInstrumentation().getTargetContext();
}
/**
* Start the activity under test, in the same way as if it was started by
* {@link android.content.Context#startActivity Context.startActivity()}, providing the
* arguments it supplied. When you use this method to start the activity, it will automatically
* be stopped by {@link #tearDown}.
*
* <p>This method will call onCreate(), but if you wish to further exercise Activity life
* cycle methods, you must call them yourself from your test case.
*
* <p><i>Do not call from your setUp() method. You must call this method from each of your
* test methods.</i>
*
* @param intent The Intent as if supplied to {@link android.content.Context#startActivity}.
* @param savedInstanceState The instance state, if you are simulating this part of the life
* cycle. Typically null.
* @param lastNonConfigurationInstance This Object will be available to the
* Activity if it calls {@link android.app.Activity#getLastNonConfigurationInstance()}.
* Typically null.
* @return Returns the Activity that was created
*/
protected T startActivity(Intent intent, Bundle savedInstanceState,
Object lastNonConfigurationInstance) {
assertFalse("Activity already created", mCreated);
if (!mAttached) {
assertNotNull(mActivityClass);
setActivity(null);
T newActivity = null;
try {
IBinder token = null;
if (mApplication == null) {
setApplication(new MockApplication());
}
ComponentName cn = new ComponentName(mActivityClass.getPackage().getName(),
mActivityClass.getName());
intent.setComponent(cn);
- ActivityInfo info = null;
+ ActivityInfo info = new ActivityInfo();
CharSequence title = mActivityClass.getName();
mMockParent = new MockParent();
String id = null;
newActivity = (T) getInstrumentation().newActivity(mActivityClass, mActivityContext,
token, mApplication, intent, info, title, mMockParent, id,
lastNonConfigurationInstance);
} catch (Exception e) {
assertNotNull(newActivity);
}
assertNotNull(newActivity);
setActivity(newActivity);
mAttached = true;
}
T result = getActivity();
if (result != null) {
getInstrumentation().callActivityOnCreate(getActivity(), savedInstanceState);
mCreated = true;
}
return result;
}
@Override
protected void tearDown() throws Exception {
setActivity(null);
// Scrub out members - protects against memory leaks in the case where someone
// creates a non-static inner class (thus referencing the test case) and gives it to
// someone else to hold onto
scrubClass(ActivityInstrumentationTestCase.class);
super.tearDown();
}
/**
* Set the application for use during the test. You must call this function before calling
* {@link #startActivity}. If your test does not call this method,
* @param application The Application object that will be injected into the Activity under test.
*/
public void setApplication(Application application) {
mApplication = application;
}
/**
* If you wish to inject a Mock, Isolated, or otherwise altered context, you can do so
* here. You must call this function before calling {@link #startActivity}. If you wish to
* obtain a real Context, as a building block, use getInstrumentation().getTargetContext().
*/
public void setActivityContext(Context activityContext) {
mActivityContext = activityContext;
}
/**
* This method will return the value if your Activity under test calls
* {@link android.app.Activity#setRequestedOrientation}.
*/
public int getRequestedOrientation() {
if (mMockParent != null) {
return mMockParent.mRequestedOrientation;
}
return 0;
}
/**
* This method will return the launch intent if your Activity under test calls
* {@link android.app.Activity#startActivity(Intent)} or
* {@link android.app.Activity#startActivityForResult(Intent, int)}.
* @return The Intent provided in the start call, or null if no start call was made.
*/
public Intent getStartedActivityIntent() {
if (mMockParent != null) {
return mMockParent.mStartedActivityIntent;
}
return null;
}
/**
* This method will return the launch request code if your Activity under test calls
* {@link android.app.Activity#startActivityForResult(Intent, int)}.
* @return The request code provided in the start call, or -1 if no start call was made.
*/
public int getStartedActivityRequest() {
if (mMockParent != null) {
return mMockParent.mStartedActivityRequest;
}
return 0;
}
/**
* This method will notify you if the Activity under test called
* {@link android.app.Activity#finish()},
* {@link android.app.Activity#finishFromChild(Activity)}, or
* {@link android.app.Activity#finishActivity(int)}.
* @return Returns true if one of the listed finish methods was called.
*/
public boolean isFinishCalled() {
if (mMockParent != null) {
return mMockParent.mFinished;
}
return false;
}
/**
* This method will return the request code if the Activity under test called
* {@link android.app.Activity#finishActivity(int)}.
* @return The request code provided in the start call, or -1 if no finish call was made.
*/
public int getFinishedActivityRequest() {
if (mMockParent != null) {
return mMockParent.mFinishedActivityRequest;
}
return 0;
}
/**
* This mock Activity represents the "parent" activity. By injecting this, we allow the user
* to call a few more Activity methods, including:
* <ul>
* <li>{@link android.app.Activity#getRequestedOrientation()}</li>
* <li>{@link android.app.Activity#setRequestedOrientation(int)}</li>
* <li>{@link android.app.Activity#finish()}</li>
* <li>{@link android.app.Activity#finishActivity(int requestCode)}</li>
* <li>{@link android.app.Activity#finishFromChild(Activity child)}</li>
* </ul>
*
* TODO: Make this overrideable, and the unit test can look for calls to other methods
*/
private static class MockParent extends Activity {
public int mRequestedOrientation = 0;
public Intent mStartedActivityIntent = null;
public int mStartedActivityRequest = -1;
public boolean mFinished = false;
public int mFinishedActivityRequest = -1;
/**
* Implementing in the parent allows the user to call this function on the tested activity.
*/
@Override
public void setRequestedOrientation(int requestedOrientation) {
mRequestedOrientation = requestedOrientation;
}
/**
* Implementing in the parent allows the user to call this function on the tested activity.
*/
@Override
public int getRequestedOrientation() {
return mRequestedOrientation;
}
/**
* By returning null here, we inhibit the creation of any "container" for the window.
*/
@Override
public Window getWindow() {
return null;
}
/**
* By defining this in the parent, we allow the tested activity to call
* <ul>
* <li>{@link android.app.Activity#startActivity(Intent)}</li>
* <li>{@link android.app.Activity#startActivityForResult(Intent, int)}</li>
* </ul>
*/
@Override
public void startActivityFromChild(Activity child, Intent intent, int requestCode) {
mStartedActivityIntent = intent;
mStartedActivityRequest = requestCode;
}
/**
* By defining this in the parent, we allow the tested activity to call
* <ul>
* <li>{@link android.app.Activity#finish()}</li>
* <li>{@link android.app.Activity#finishFromChild(Activity child)}</li>
* </ul>
*/
@Override
public void finishFromChild(Activity child) {
mFinished = true;
}
/**
* By defining this in the parent, we allow the tested activity to call
* <ul>
* <li>{@link android.app.Activity#finishActivity(int requestCode)}</li>
* </ul>
*/
@Override
public void finishActivityFromChild(Activity child, int requestCode) {
mFinished = true;
mFinishedActivityRequest = requestCode;
}
}
}
| true | true | protected T startActivity(Intent intent, Bundle savedInstanceState,
Object lastNonConfigurationInstance) {
assertFalse("Activity already created", mCreated);
if (!mAttached) {
assertNotNull(mActivityClass);
setActivity(null);
T newActivity = null;
try {
IBinder token = null;
if (mApplication == null) {
setApplication(new MockApplication());
}
ComponentName cn = new ComponentName(mActivityClass.getPackage().getName(),
mActivityClass.getName());
intent.setComponent(cn);
ActivityInfo info = null;
CharSequence title = mActivityClass.getName();
mMockParent = new MockParent();
String id = null;
newActivity = (T) getInstrumentation().newActivity(mActivityClass, mActivityContext,
token, mApplication, intent, info, title, mMockParent, id,
lastNonConfigurationInstance);
} catch (Exception e) {
assertNotNull(newActivity);
}
assertNotNull(newActivity);
setActivity(newActivity);
mAttached = true;
}
T result = getActivity();
if (result != null) {
getInstrumentation().callActivityOnCreate(getActivity(), savedInstanceState);
mCreated = true;
}
return result;
}
| protected T startActivity(Intent intent, Bundle savedInstanceState,
Object lastNonConfigurationInstance) {
assertFalse("Activity already created", mCreated);
if (!mAttached) {
assertNotNull(mActivityClass);
setActivity(null);
T newActivity = null;
try {
IBinder token = null;
if (mApplication == null) {
setApplication(new MockApplication());
}
ComponentName cn = new ComponentName(mActivityClass.getPackage().getName(),
mActivityClass.getName());
intent.setComponent(cn);
ActivityInfo info = new ActivityInfo();
CharSequence title = mActivityClass.getName();
mMockParent = new MockParent();
String id = null;
newActivity = (T) getInstrumentation().newActivity(mActivityClass, mActivityContext,
token, mApplication, intent, info, title, mMockParent, id,
lastNonConfigurationInstance);
} catch (Exception e) {
assertNotNull(newActivity);
}
assertNotNull(newActivity);
setActivity(newActivity);
mAttached = true;
}
T result = getActivity();
if (result != null) {
getInstrumentation().callActivityOnCreate(getActivity(), savedInstanceState);
mCreated = true;
}
return result;
}
|
diff --git a/src/main/java/org/ccdd/redcable/RedCable.java b/src/main/java/org/ccdd/redcable/RedCable.java
index e3cc955..ed82ec3 100644
--- a/src/main/java/org/ccdd/redcable/RedCable.java
+++ b/src/main/java/org/ccdd/redcable/RedCable.java
@@ -1,54 +1,55 @@
package org.ccdd.redcable;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.ccdd.redcable.listeners.SpeakerWireListener;
import org.ccdd.redcable.materials.blocks.Blocks;
import org.ccdd.redcable.materials.items.Items;
import org.ccdd.redcable.util.Recipies;
import org.ccdd.redcable.util.ResourceManager;
public class RedCable extends JavaPlugin {
public static RedCable instance;
Blocks blocks;
Items items;
public void onEnable() {
//copy the config
this.getConfig().options().copyDefaults(true);
this.saveConfig();
//double check for spout.
if (!Bukkit.getPluginManager().isPluginEnabled("Spout")) {
Bukkit.getLogger().log(Level.WARNING, "[RedCable] Could not start: Spout not found.");
setEnabled(false);
return;
}
instance = this;
ResourceManager.copyResources();
items = new Items();
blocks = new Blocks();
Recipies.load();
this.getServer().getPluginManager().registerEvents(new SpeakerWireListener(), this);
//this.getCommand("redcable").setExecutor(new CommandHandler());
ResourceManager.resetCache();
+ Bukkit.getLogger().log(Level.INFO, "[RedCable] Enabled");
}
public void onDisable() {
Bukkit.getLogger().log(Level.INFO, "[RedCable] Disabled");
}
}
| true | true | public void onEnable() {
//copy the config
this.getConfig().options().copyDefaults(true);
this.saveConfig();
//double check for spout.
if (!Bukkit.getPluginManager().isPluginEnabled("Spout")) {
Bukkit.getLogger().log(Level.WARNING, "[RedCable] Could not start: Spout not found.");
setEnabled(false);
return;
}
instance = this;
ResourceManager.copyResources();
items = new Items();
blocks = new Blocks();
Recipies.load();
this.getServer().getPluginManager().registerEvents(new SpeakerWireListener(), this);
//this.getCommand("redcable").setExecutor(new CommandHandler());
ResourceManager.resetCache();
}
| public void onEnable() {
//copy the config
this.getConfig().options().copyDefaults(true);
this.saveConfig();
//double check for spout.
if (!Bukkit.getPluginManager().isPluginEnabled("Spout")) {
Bukkit.getLogger().log(Level.WARNING, "[RedCable] Could not start: Spout not found.");
setEnabled(false);
return;
}
instance = this;
ResourceManager.copyResources();
items = new Items();
blocks = new Blocks();
Recipies.load();
this.getServer().getPluginManager().registerEvents(new SpeakerWireListener(), this);
//this.getCommand("redcable").setExecutor(new CommandHandler());
ResourceManager.resetCache();
Bukkit.getLogger().log(Level.INFO, "[RedCable] Enabled");
}
|
diff --git a/test/src/com/rabbitmq/client/test/functional/Reject.java b/test/src/com/rabbitmq/client/test/functional/Reject.java
index c3b1b19c6..d35f64c33 100644
--- a/test/src/com/rabbitmq/client/test/functional/Reject.java
+++ b/test/src/com/rabbitmq/client/test/functional/Reject.java
@@ -1,84 +1,84 @@
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is RabbitMQ.
//
// The Initial Developers of the Original Code are LShift Ltd,
// Cohesive Financial Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created before 22-Nov-2008 00:00:00 GMT by LShift Ltd,
// Cohesive Financial Technologies LLC, or Rabbit Technologies Ltd
// are Copyright (C) 2007-2008 LShift Ltd, Cohesive Financial
// Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created by LShift Ltd are Copyright (C) 2007-2010 LShift
// Ltd. Portions created by Cohesive Financial Technologies LLC are
// Copyright (C) 2007-2010 Cohesive Financial Technologies
// LLC. Portions created by Rabbit Technologies Ltd are Copyright
// (C) 2007-2010 Rabbit Technologies Ltd.
//
// All Rights Reserved.
//
// Contributor(s): ______________________________________.
//
package com.rabbitmq.client.test.functional;
import com.rabbitmq.client.test.BrokerTestCase;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import java.io.IOException;
import java.util.Arrays;
public class Reject extends BrokerTestCase
{
protected long checkDelivery(Delivery d, byte[] msg, boolean redelivered)
{
assertNotNull(d);
assertTrue(Arrays.equals(msg, d.getBody()));
assertEquals(d.getEnvelope().isRedeliver(), redelivered);
return d.getEnvelope().getDeliveryTag();
}
public void testReject()
throws IOException, InterruptedException
{
String q = channel.queueDeclare("", false, true, false, null).getQueue();
QueueingConsumer c = new QueueingConsumer(channel);
String consumerTag = channel.basicConsume(q, false, c);
byte[] m1 = "1".getBytes();
byte[] m2 = "2".getBytes();
basicPublishVolatile(m1, q);
basicPublishVolatile(m2, q);
long tag1 = checkDelivery(c.nextDelivery(), m1, false);
long tag2 = checkDelivery(c.nextDelivery(), m2, false);
channel.basicReject(tag2, true);
long tag3 = checkDelivery(c.nextDelivery(), m2, true);
channel.basicCancel(consumerTag);
channel.basicReject(tag3, false);
assertNull(channel.basicGet(q, false));
channel.basicAck(tag1, false);
channel.basicReject(tag3, false);
try {
channel.basicQos(0); //some synchronous command
fail();
} catch (IOException ioe) {
- checkShutdownSignal(AMQP.NOT_FOUND, ioe);
+ checkShutdownSignal(AMQP.PRECONDITION_FAILED, ioe);
}
}
}
| true | true | public void testReject()
throws IOException, InterruptedException
{
String q = channel.queueDeclare("", false, true, false, null).getQueue();
QueueingConsumer c = new QueueingConsumer(channel);
String consumerTag = channel.basicConsume(q, false, c);
byte[] m1 = "1".getBytes();
byte[] m2 = "2".getBytes();
basicPublishVolatile(m1, q);
basicPublishVolatile(m2, q);
long tag1 = checkDelivery(c.nextDelivery(), m1, false);
long tag2 = checkDelivery(c.nextDelivery(), m2, false);
channel.basicReject(tag2, true);
long tag3 = checkDelivery(c.nextDelivery(), m2, true);
channel.basicCancel(consumerTag);
channel.basicReject(tag3, false);
assertNull(channel.basicGet(q, false));
channel.basicAck(tag1, false);
channel.basicReject(tag3, false);
try {
channel.basicQos(0); //some synchronous command
fail();
} catch (IOException ioe) {
checkShutdownSignal(AMQP.NOT_FOUND, ioe);
}
}
| public void testReject()
throws IOException, InterruptedException
{
String q = channel.queueDeclare("", false, true, false, null).getQueue();
QueueingConsumer c = new QueueingConsumer(channel);
String consumerTag = channel.basicConsume(q, false, c);
byte[] m1 = "1".getBytes();
byte[] m2 = "2".getBytes();
basicPublishVolatile(m1, q);
basicPublishVolatile(m2, q);
long tag1 = checkDelivery(c.nextDelivery(), m1, false);
long tag2 = checkDelivery(c.nextDelivery(), m2, false);
channel.basicReject(tag2, true);
long tag3 = checkDelivery(c.nextDelivery(), m2, true);
channel.basicCancel(consumerTag);
channel.basicReject(tag3, false);
assertNull(channel.basicGet(q, false));
channel.basicAck(tag1, false);
channel.basicReject(tag3, false);
try {
channel.basicQos(0); //some synchronous command
fail();
} catch (IOException ioe) {
checkShutdownSignal(AMQP.PRECONDITION_FAILED, ioe);
}
}
|
diff --git a/moskito-webui/java/net/anotheria/moskito/webui/MoskitoUIFilter.java b/moskito-webui/java/net/anotheria/moskito/webui/MoskitoUIFilter.java
index 37ab7d6b..f37f619b 100644
--- a/moskito-webui/java/net/anotheria/moskito/webui/MoskitoUIFilter.java
+++ b/moskito-webui/java/net/anotheria/moskito/webui/MoskitoUIFilter.java
@@ -1,80 +1,80 @@
package net.anotheria.moskito.webui;
import net.anotheria.maf.MAFFilter;
import net.anotheria.maf.action.ActionMappingsConfigurator;
import net.anotheria.moskito.webui.shared.api.MoskitoAPIInitializer;
import net.anotheria.net.util.NetUtils;
import net.anotheria.util.maven.MavenVersion;
import net.anotheria.webutils.util.VersionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.util.Arrays;
import java.util.List;
/**
* MoskitoUI Filter is the main entering point of the Moskito Web User Interface.
* @author lrosenberg
*
*/
public class MoskitoUIFilter extends MAFFilter{
/**
* Logger.
*/
private static final Logger log = LoggerFactory.getLogger(MoskitoUIFilter.class);
/**
* Path to images for html-layer image linking.
*/
private String pathToImages = "../img/";
@Override public void init(FilterConfig config) throws ServletException {
super.init(config);
- log.info("Initing MoSKito WebUI...");
+ log.info("Initializing MoSKito WebUI...");
MoskitoAPIInitializer.initialize();
try{
MavenVersion moskitoVersion = VersionUtil.getWebappLibVersion(config.getServletContext(), "moskito-webui");
MavenVersion appVersion = VersionUtil.getWebappVersion(config.getServletContext());
config.getServletContext().setAttribute("application.maven.version", appVersion == null ? "?" : appVersion);
config.getServletContext().setAttribute("moskito.maven.version", moskitoVersion == null ? "?" : moskitoVersion);
String computerName = NetUtils.getComputerName();
config.getServletContext().setAttribute("servername", computerName==null ? "Unknown" : computerName);
}catch(Exception e){
log.error("init("+config+")", e);
}
String pathToImagesParameter = config.getInitParameter("pathToImages");
if (pathToImagesParameter!=null && pathToImagesParameter.length()>0)
pathToImages = pathToImagesParameter;
config.getServletContext().setAttribute("mskPathToImages", pathToImages);
}
@Override public String getProducerId() {
return "moskitoUI";
}
@Override public String getSubsystem() {
return "monitoring";
}
@Override public String getCategory() {
return "filter";
}
@Override
protected List<ActionMappingsConfigurator> getConfigurators(){
return Arrays.asList(new ActionMappingsConfigurator[]{ new MoskitoMappingsConfigurator() });
}
@Override
protected String getDefaultActionName() {
return "mskShowAllProducers";
}
}
| true | true | @Override public void init(FilterConfig config) throws ServletException {
super.init(config);
log.info("Initing MoSKito WebUI...");
MoskitoAPIInitializer.initialize();
try{
MavenVersion moskitoVersion = VersionUtil.getWebappLibVersion(config.getServletContext(), "moskito-webui");
MavenVersion appVersion = VersionUtil.getWebappVersion(config.getServletContext());
config.getServletContext().setAttribute("application.maven.version", appVersion == null ? "?" : appVersion);
config.getServletContext().setAttribute("moskito.maven.version", moskitoVersion == null ? "?" : moskitoVersion);
String computerName = NetUtils.getComputerName();
config.getServletContext().setAttribute("servername", computerName==null ? "Unknown" : computerName);
}catch(Exception e){
log.error("init("+config+")", e);
}
String pathToImagesParameter = config.getInitParameter("pathToImages");
if (pathToImagesParameter!=null && pathToImagesParameter.length()>0)
pathToImages = pathToImagesParameter;
config.getServletContext().setAttribute("mskPathToImages", pathToImages);
}
| @Override public void init(FilterConfig config) throws ServletException {
super.init(config);
log.info("Initializing MoSKito WebUI...");
MoskitoAPIInitializer.initialize();
try{
MavenVersion moskitoVersion = VersionUtil.getWebappLibVersion(config.getServletContext(), "moskito-webui");
MavenVersion appVersion = VersionUtil.getWebappVersion(config.getServletContext());
config.getServletContext().setAttribute("application.maven.version", appVersion == null ? "?" : appVersion);
config.getServletContext().setAttribute("moskito.maven.version", moskitoVersion == null ? "?" : moskitoVersion);
String computerName = NetUtils.getComputerName();
config.getServletContext().setAttribute("servername", computerName==null ? "Unknown" : computerName);
}catch(Exception e){
log.error("init("+config+")", e);
}
String pathToImagesParameter = config.getInitParameter("pathToImages");
if (pathToImagesParameter!=null && pathToImagesParameter.length()>0)
pathToImages = pathToImagesParameter;
config.getServletContext().setAttribute("mskPathToImages", pathToImages);
}
|
diff --git a/source/com/mucommander/file/impl/smb/SMBFile.java b/source/com/mucommander/file/impl/smb/SMBFile.java
index 8741e7f0..de26f0a3 100644
--- a/source/com/mucommander/file/impl/smb/SMBFile.java
+++ b/source/com/mucommander/file/impl/smb/SMBFile.java
@@ -1,466 +1,466 @@
package com.mucommander.file.impl.smb;
import com.mucommander.Debug;
import com.mucommander.auth.AuthException;
import com.mucommander.file.*;
import com.mucommander.io.FileTransferException;
import com.mucommander.io.RandomAccessInputStream;
import jcifs.smb.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* SMBFile represents a file shared through the SMB protocol.
*
* @author Maxence Bernard
*/
public class SMBFile extends AbstractFile {
private SmbFile file;
// private String privateURL;
private AbstractFile parent;
private boolean parentValSet;
private boolean isDirectory;
private boolean isDirectoryValSet;
// private String name;
private final static String SEPARATOR = DEFAULT_SEPARATOR;
static {
// Silence jCIFS's output if not in debug mode
// To quote jCIFS's documentation : "0 - No log messages are printed -- not even crticial exceptions."
if(!Debug.ON)
System.setProperty("jcifs.util.loglevel", "0");
}
public SMBFile(FileURL fileURL) throws IOException {
this(fileURL, null);
}
private SMBFile(FileURL fileURL, SmbFile smbFile) throws IOException {
super(fileURL);
if(smbFile==null) { // Called by public constructor
while(true) {
file = new SmbFile(fileURL.toString(true));
// The following test comes at a cost, so it's only used by the public constructor, SmbFile instances
// created by this class are considered OK.
try {
// SmbFile requires a trailing slash for directories otherwise listFiles() will throw an SmbException.
// As we cannot guarantee that the path will contain a trailing slash for directories, test if the
// SmbFile is a directory and if it doesn't contain a trailing slash, create a new SmbFile.
// SmbFile.isDirectory() will throw an SmbAuthException if access to the file requires (new) credentials.
if(file.isDirectory() && !getURL().getPath().endsWith("/")) {
// Add trailing slash and loop to create a new SmbFile
fileURL.setPath(fileURL.getPath()+'/');
continue;
}
break;
}
catch(SmbException e) {
// Need credentials, throw AuthException
if(e instanceof SmbAuthException)
throw new AuthException(fileURL, e.getMessage());
}
}
}
else { // Instanciated by this class
file = smbFile;
}
// // Cache SmbFile.getName()'s return value which parses name each time it is called
// this.name = file.getName();
// if(name.endsWith("/"))
// name = name.substring(0, name.length()-1);
}
/////////////////////////////////////////
// AbstractFile methods implementation //
/////////////////////////////////////////
public long getDate() {
try {
return file.lastModified();
}
catch(SmbException e) {
return 0;
}
}
public boolean changeDate(long lastModified) {
try {
// SmbFile.setLastModified() returns "jcifs.smb.SmbAuthException: Access is denied" exceptions
// don't know if it's a bug in the library or a server limitation (tested with Samba)
file.setLastModified(lastModified);
return true;
}
catch(SmbException e) {
if(com.mucommander.Debug.ON) { com.mucommander.Debug.trace("return false "+e);}
return false;
}
}
public long getSize() {
try {
return file.length();
}
catch(SmbException e) {
return 0;
}
}
public AbstractFile getParent() {
if(!parentValSet) {
try {
FileURL parentURL = fileURL.getParent();
// If parent URL as returned by fileURL.getParent() is null and URL's host is not null,
// create an 'smb://' parent to browse network workgroups
if(parentURL==null) {
if(fileURL.getHost()!=null)
parentURL = new FileURL(FileProtocols.SMB+"://");
else
return null; // This file is already smb://
}
// this.parent = new SMBFile(parentURL, null, false);
// parentURL.setCredentials(fileURL.getCredentials());
this.parent = new SMBFile(parentURL, null);
return parent;
}
catch(IOException e) {
// this.parent and returned parent will be null
}
finally {
this.parentValSet = true;
}
}
return this.parent;
}
public void setParent(AbstractFile parent) {
this.parent = parent;
this.parentValSet = true;
}
public boolean exists() {
// Unlike java.io.File, SmbFile.exists() can throw an SmbException
try {
return file.exists();
}
catch(IOException e) {
if(e instanceof SmbAuthException)
return true;
return false;
}
}
public boolean getPermission(int access, int permission) {
if(access!= USER_ACCESS)
return false;
try {
if(permission==READ_PERMISSION)
return file.canRead();
else if(permission==WRITE_PERMISSION)
return file.canWrite();
else
return false;
}
// Unlike java.io.File, SmbFile#canRead() and SmbFile#canWrite() can throw an SmbException
catch(SmbException e) {
return false;
}
}
public boolean setPermission(int access, int permission, boolean enabled) {
if(access!= USER_ACCESS || permission!=WRITE_PERMISSION)
return false;
try {
if(enabled)
file.setReadWrite();
else
file.setReadOnly();
return true;
}
catch(SmbException e) {
return false;
}
}
public boolean canGetPermission(int access, int permission) {
return access== USER_ACCESS; // Get permission support is limited to the user access type.
}
public boolean canSetPermission(int access, int permission) {
// Set permission support is limited to the user access type, and only for the write permission flag.
return access== USER_ACCESS && permission==WRITE_PERMISSION;
}
public boolean isDirectory() {
// Cache SmbFile.isDirectory()'s return value as this method triggers network calls
// (calls exists() which checks file existence on the server) and will report
// false if connection is lost.
if(!isDirectoryValSet) {
try {
this.isDirectory = file.isDirectory();
this.isDirectoryValSet = true;
}
catch(SmbException e) {
return false;
}
}
return this.isDirectory;
}
public boolean isSymlink() {
// Symlinks are not supported with jCIFS (or in CIFS/SMB?)
return false;
}
public InputStream getInputStream() throws IOException {
// return new SmbFileInputStream(privateURL);
return new SmbFileInputStream(getURL().toString(true));
}
public RandomAccessInputStream getRandomAccessInputStream() throws IOException {
return new SMBRandomAccessInputStream(new SmbRandomAccessFile(file, "r"));
}
public OutputStream getOutputStream(boolean append) throws IOException {
// return new SmbFileOutputStream(privateURL, append);
return new SmbFileOutputStream(getURL().toString(true), append);
}
public void delete() throws IOException {
file.delete();
}
public AbstractFile[] ls() throws IOException {
try {
SmbFile smbFiles[] = file.listFiles();
if(smbFiles==null)
throw new IOException();
// Count the number of files to exclude: excluded files are those that are not file share/ not browsable
// (Printers, named pipes, comm ports)
int nbSmbFiles = smbFiles.length;
int nbSmbFilesToExclude = 0;
int smbFileType;
for(int i=0; i<nbSmbFiles; i++) {
smbFileType = smbFiles[i].getType();
if(smbFileType==SmbFile.TYPE_PRINTER || smbFileType==SmbFile.TYPE_NAMED_PIPE || smbFileType==SmbFile.TYPE_COMM)
nbSmbFilesToExclude++;
}
// Create SMBFile by using SmbFile instance and sharing parent instance among children
AbstractFile children[] = new AbstractFile[nbSmbFiles-nbSmbFilesToExclude];
AbstractFile child;
FileURL childURL;
SmbFile smbFile;
int currentIndex = 0;
// Credentials credentials = fileURL.getCredentials();
for(int i=0; i<nbSmbFiles; i++) {
smbFile = smbFiles[i];
smbFileType = smbFile.getType();
if(smbFileType==SmbFile.TYPE_PRINTER || smbFileType==SmbFile.TYPE_NAMED_PIPE || smbFileType==SmbFile.TYPE_COMM)
continue;
// Note: properties and credentials are cloned for every children's url
childURL = (FileURL)fileURL.clone();
- childURL.setPath(smbFile.getCanonicalPath());
+ childURL.setPath(smbFile.getURL().getPath());
// childURL = new FileURL(smbFile.getCanonicalPath());
// childURL.setCredentials(credentials);
child = FileFactory.wrapArchive(new SMBFile(childURL, smbFile));
child.setParent(this);
children[currentIndex++] = child;
}
return children;
}
catch(SmbAuthException e) {
throw new AuthException(fileURL, e.getMessage());
}
}
public void mkdir(String name) throws IOException {
// Unlike java.io.File.mkdir(), SmbFile does not return a boolean value
// to indicate if the folder could be created
// new SmbFile(privateURL+SEPARATOR+name).mkdir();
new SmbFile(getURL().toString(true)+SEPARATOR+name).mkdir();
}
public long getFreeSpace() {
try {
return file.getDiskFreeSpace();
}
catch(SmbException e) {
// Error occured, return -1 (not available)
return -1;
}
}
public long getTotalSpace() {
// No way to retrieve this information with jCIFS/SMB, return -1 (not available)
return -1;
}
////////////////////////
// Overridden methods //
////////////////////////
public boolean isHidden() {
try {
return file.isHidden();
}
catch(SmbException e) {
return false;
}
}
public boolean copyTo(AbstractFile destFile) throws FileTransferException {
// File can only be copied by SMB if the destination is on an SMB share (but not necessarily on the same host)
if(!destFile.getURL().getProtocol().equals(FileProtocols.SMB)) {
return super.copyTo(destFile);
}
// If file is an archive file, retrieve the enclosed file, which is likely to be an SMBFile but not necessarily
// (may be an ArchiveEntryFile)
if(destFile instanceof AbstractArchiveFile)
destFile = ((AbstractArchiveFile)destFile).getProxiedFile();
// If destination file is not an SMBFile (for instance an archive entry), SmbFile.copyTo() won't work
// so use the default copyTo() implementation instead
if(!(destFile instanceof SMBFile)) {
return super.copyTo(destFile);
}
// Reuse the destination SmbFile instance
SmbFile destSmbFile = ((SMBFile)destFile).file;
try {
// Copy the SMB file
file.copyTo(destSmbFile);
return true;
}
catch(SmbException e) {
return false;
}
}
/**
* Overrides {@link AbstractFile#moveTo(AbstractFile)} to support server-to-server move if the destination file
* uses SMB.
*/
public boolean moveTo(AbstractFile destFile) throws FileTransferException {
// File can only be moved directly if the destination if it is on an SMB share
// (but not necessarily on the same host).
// Use the default moveTo() implementation if the destination file doesn't use the same protocol (webdav/webdavs)
// or is not on the same host
if(!destFile.getURL().getProtocol().equals(FileProtocols.SMB)) {
return super.moveTo(destFile);
}
// If file is an archive file, retrieve enclosed file, which is likely to be an SMBFile but not necessarily
// (may be an ArchiveEntryFile)
if(destFile instanceof AbstractArchiveFile)
destFile = ((AbstractArchiveFile)destFile).getProxiedFile();
// If destination file is not an SMBFile (for instance an archive entry), SmbFile.renameTo() won't work,
// so use the default moveTo() implementation instead
if(!(destFile instanceof SMBFile)) {
return super.moveTo(destFile);
}
// Move file
try {
file.renameTo(((SMBFile)destFile).file);
return true;
}
catch(SmbException e) {
return false;
}
}
public boolean equals(Object f) {
if(!(f instanceof SMBFile))
return super.equals(f); // could be equal to an AbstractArchiveFile
// SmbFile's equals method is just perfect: compares canonical paths
// and IP addresses
return file.equals(((SMBFile)f).file);
}
public boolean canRunProcess() {return false;}
public com.mucommander.process.AbstractProcess runProcess(String[] tokens) throws IOException {throw new IOException();}
/**
* SMBRandomAccessInputStream extends RandomAccessInputStream to provide random access to an <code>SMBFile</code>'s
* content.
*/
public class SMBRandomAccessInputStream extends RandomAccessInputStream {
private SmbRandomAccessFile raf;
public SMBRandomAccessInputStream(SmbRandomAccessFile raf) {
this.raf = raf;
}
public int read() throws IOException {
return raf.read();
}
public int read(byte b[]) throws IOException {
return raf.read(b);
}
public int read(byte b[], int off, int len) throws IOException {
return raf.read(b, off, len);
}
public void close() throws IOException {
raf.close();
}
public long getOffset() throws IOException {
return raf.getFilePointer();
}
public long getLength() throws IOException {
return raf.length();
}
public void seek(long pos) throws IOException {
raf.seek(pos);
}
}
}
| true | true | public AbstractFile[] ls() throws IOException {
try {
SmbFile smbFiles[] = file.listFiles();
if(smbFiles==null)
throw new IOException();
// Count the number of files to exclude: excluded files are those that are not file share/ not browsable
// (Printers, named pipes, comm ports)
int nbSmbFiles = smbFiles.length;
int nbSmbFilesToExclude = 0;
int smbFileType;
for(int i=0; i<nbSmbFiles; i++) {
smbFileType = smbFiles[i].getType();
if(smbFileType==SmbFile.TYPE_PRINTER || smbFileType==SmbFile.TYPE_NAMED_PIPE || smbFileType==SmbFile.TYPE_COMM)
nbSmbFilesToExclude++;
}
// Create SMBFile by using SmbFile instance and sharing parent instance among children
AbstractFile children[] = new AbstractFile[nbSmbFiles-nbSmbFilesToExclude];
AbstractFile child;
FileURL childURL;
SmbFile smbFile;
int currentIndex = 0;
// Credentials credentials = fileURL.getCredentials();
for(int i=0; i<nbSmbFiles; i++) {
smbFile = smbFiles[i];
smbFileType = smbFile.getType();
if(smbFileType==SmbFile.TYPE_PRINTER || smbFileType==SmbFile.TYPE_NAMED_PIPE || smbFileType==SmbFile.TYPE_COMM)
continue;
// Note: properties and credentials are cloned for every children's url
childURL = (FileURL)fileURL.clone();
childURL.setPath(smbFile.getCanonicalPath());
// childURL = new FileURL(smbFile.getCanonicalPath());
// childURL.setCredentials(credentials);
child = FileFactory.wrapArchive(new SMBFile(childURL, smbFile));
child.setParent(this);
children[currentIndex++] = child;
}
return children;
}
catch(SmbAuthException e) {
throw new AuthException(fileURL, e.getMessage());
}
}
| public AbstractFile[] ls() throws IOException {
try {
SmbFile smbFiles[] = file.listFiles();
if(smbFiles==null)
throw new IOException();
// Count the number of files to exclude: excluded files are those that are not file share/ not browsable
// (Printers, named pipes, comm ports)
int nbSmbFiles = smbFiles.length;
int nbSmbFilesToExclude = 0;
int smbFileType;
for(int i=0; i<nbSmbFiles; i++) {
smbFileType = smbFiles[i].getType();
if(smbFileType==SmbFile.TYPE_PRINTER || smbFileType==SmbFile.TYPE_NAMED_PIPE || smbFileType==SmbFile.TYPE_COMM)
nbSmbFilesToExclude++;
}
// Create SMBFile by using SmbFile instance and sharing parent instance among children
AbstractFile children[] = new AbstractFile[nbSmbFiles-nbSmbFilesToExclude];
AbstractFile child;
FileURL childURL;
SmbFile smbFile;
int currentIndex = 0;
// Credentials credentials = fileURL.getCredentials();
for(int i=0; i<nbSmbFiles; i++) {
smbFile = smbFiles[i];
smbFileType = smbFile.getType();
if(smbFileType==SmbFile.TYPE_PRINTER || smbFileType==SmbFile.TYPE_NAMED_PIPE || smbFileType==SmbFile.TYPE_COMM)
continue;
// Note: properties and credentials are cloned for every children's url
childURL = (FileURL)fileURL.clone();
childURL.setPath(smbFile.getURL().getPath());
// childURL = new FileURL(smbFile.getCanonicalPath());
// childURL.setCredentials(credentials);
child = FileFactory.wrapArchive(new SMBFile(childURL, smbFile));
child.setParent(this);
children[currentIndex++] = child;
}
return children;
}
catch(SmbAuthException e) {
throw new AuthException(fileURL, e.getMessage());
}
}
|
diff --git a/paul/src/main/java/au/edu/uq/cmm/paul/grabber/DatafileMetadata.java b/paul/src/main/java/au/edu/uq/cmm/paul/grabber/DatafileMetadata.java
index 1f6ae1d..8f7001d 100644
--- a/paul/src/main/java/au/edu/uq/cmm/paul/grabber/DatafileMetadata.java
+++ b/paul/src/main/java/au/edu/uq/cmm/paul/grabber/DatafileMetadata.java
@@ -1,142 +1,142 @@
/*
* Copyright 2012, CMM, University of Queensland.
*
* This file is part of Paul.
*
* Paul 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.
*
* Paul 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 Paul. If not, see <http://www.gnu.org/licenses/>.
*/
package au.edu.uq.cmm.paul.grabber;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.annotations.GenericGenerator;
/**
* This class represents the administrative metadata for a file captured
* by the FileGrabber.
*
* @author scrawley
*/
@Entity
@Table(name = "DATAFILE_METADATA",
uniqueConstraints=@UniqueConstraint(columnNames={"capturedFilePathname"}))
public class DatafileMetadata {
private String sourceFilePathname;
private String facilityFilePathname;
private Date captureTimestamp;
private Date fileWriteTimestamp;
private String capturedFilePathname;
private String mimeType;
private Long id;
private long fileSize;
public DatafileMetadata() {
super();
}
public DatafileMetadata(
String sourceFilePathname, String facilityFilePathname,
- String capturedFilePathname, Date captureTimestamp,
- Date fileWriteTimestamp, String mimeType, long fileSize) {
+ String capturedFilePathname, Date fileWriteTimestamp,
+ Date captureTimestamp, String mimeType, long fileSize) {
super();
this.sourceFilePathname = sourceFilePathname;
this.facilityFilePathname = facilityFilePathname;
this.capturedFilePathname = capturedFilePathname;
this.captureTimestamp = captureTimestamp;
this.fileWriteTimestamp = fileWriteTimestamp;
this.mimeType = mimeType;
this.fileSize = fileSize;
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@JsonIgnore
public Long getId() {
return id;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getCaptureTimestamp() {
return captureTimestamp;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getFileWriteTimestamp() {
return fileWriteTimestamp;
}
public String getSourceFilePathname() {
return sourceFilePathname;
}
public String getCapturedFilePathname() {
return capturedFilePathname;
}
public void setSourceFilePathname(String sourceFilePathname) {
this.sourceFilePathname = sourceFilePathname;
}
public String getFacilityFilePathname() {
return facilityFilePathname;
}
public void setFacilityFilePathname(String facilityFilePathname) {
this.facilityFilePathname = facilityFilePathname;
}
public void setCaptureTimestamp(Date captureTimestamp) {
this.captureTimestamp = captureTimestamp;
}
public void setFileWriteTimestamp(Date fileWriteTimestamp) {
this.fileWriteTimestamp = fileWriteTimestamp;
}
public void setCapturedFilePathname(String capturedFilePathname) {
this.capturedFilePathname = capturedFilePathname;
}
public void setId(Long id) {
this.id = id;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
}
| true | true | public DatafileMetadata(
String sourceFilePathname, String facilityFilePathname,
String capturedFilePathname, Date captureTimestamp,
Date fileWriteTimestamp, String mimeType, long fileSize) {
super();
this.sourceFilePathname = sourceFilePathname;
this.facilityFilePathname = facilityFilePathname;
this.capturedFilePathname = capturedFilePathname;
this.captureTimestamp = captureTimestamp;
this.fileWriteTimestamp = fileWriteTimestamp;
this.mimeType = mimeType;
this.fileSize = fileSize;
}
| public DatafileMetadata(
String sourceFilePathname, String facilityFilePathname,
String capturedFilePathname, Date fileWriteTimestamp,
Date captureTimestamp, String mimeType, long fileSize) {
super();
this.sourceFilePathname = sourceFilePathname;
this.facilityFilePathname = facilityFilePathname;
this.capturedFilePathname = capturedFilePathname;
this.captureTimestamp = captureTimestamp;
this.fileWriteTimestamp = fileWriteTimestamp;
this.mimeType = mimeType;
this.fileSize = fileSize;
}
|
diff --git a/jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/JaxbAwareTranslator.java b/jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/JaxbAwareTranslator.java
index 4eb9876..a0ad8b2 100644
--- a/jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/JaxbAwareTranslator.java
+++ b/jaxrs-doclet/src/main/java/com/hypnoticocelot/jaxrs/doclet/translator/JaxbAwareTranslator.java
@@ -1,78 +1,80 @@
package com.hypnoticocelot.jaxrs.doclet.translator;
import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationHelper;
import com.hypnoticocelot.jaxrs.doclet.parser.AnnotationParser;
import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.ProgramElementDoc;
import com.sun.javadoc.Type;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Objects.firstNonNull;
public class JaxbAwareTranslator implements Translator {
private static final String JAXB_XML_ROOT_ELEMENT = "javax.xml.bind.annotation.XmlRootElement";
private static final String JAXB_XML_ELEMENT = "javax.xml.bind.annotation.XmlElement";
private static final String JAXB_XML_TRANSIENT = "javax.xml.bind.annotation.XmlTransient";
private final Translator simpleTranslator;
private final Map<String, Type> reverseIndex;
private final Map<Type, String> namedTypes;
public JaxbAwareTranslator() {
simpleTranslator = new SimpleTranslator();
reverseIndex = new HashMap<String, Type>();
namedTypes = new HashMap<Type, String>();
}
@Override
public String nameFor(Type type) {
if (AnnotationHelper.isPrimitive(type)) {
return AnnotationHelper.typeOf(type.qualifiedTypeName());
}
if (namedTypes.containsKey(type)) {
return namedTypes.get(type);
}
String name = jaxbNameFor(JAXB_XML_ROOT_ELEMENT, type.asClassDoc());
if (name != null) {
- while (reverseIndex.containsKey(name)) {
- name += '_';
+ StringBuilder nameBuilder = new StringBuilder(name);
+ while (reverseIndex.containsKey(nameBuilder.toString())) {
+ nameBuilder.append('_');
}
+ name = nameBuilder.toString();
}
name = firstNonNull(name, simpleTranslator.nameFor(type));
namedTypes.put(type, name);
reverseIndex.put(name, type);
return name;
}
@Override
public String nameFor(FieldDoc field) {
String name = jaxbNameFor(JAXB_XML_ELEMENT, field);
if (name == null) {
name = simpleTranslator.nameFor(field);
}
return name;
}
@Override
public String nameFor(MethodDoc method) {
String name = jaxbNameFor(JAXB_XML_ELEMENT, method);
if (name == null) {
name = simpleTranslator.nameFor(method);
}
return name;
}
private String jaxbNameFor(String annotation, ProgramElementDoc doc) {
AnnotationParser element = new AnnotationParser(doc);
if (element.isAnnotatedBy(JAXB_XML_TRANSIENT)) {
return null;
}
return element.getAnnotationValue(annotation, "name");
}
}
| false | true | public String nameFor(Type type) {
if (AnnotationHelper.isPrimitive(type)) {
return AnnotationHelper.typeOf(type.qualifiedTypeName());
}
if (namedTypes.containsKey(type)) {
return namedTypes.get(type);
}
String name = jaxbNameFor(JAXB_XML_ROOT_ELEMENT, type.asClassDoc());
if (name != null) {
while (reverseIndex.containsKey(name)) {
name += '_';
}
}
name = firstNonNull(name, simpleTranslator.nameFor(type));
namedTypes.put(type, name);
reverseIndex.put(name, type);
return name;
}
| public String nameFor(Type type) {
if (AnnotationHelper.isPrimitive(type)) {
return AnnotationHelper.typeOf(type.qualifiedTypeName());
}
if (namedTypes.containsKey(type)) {
return namedTypes.get(type);
}
String name = jaxbNameFor(JAXB_XML_ROOT_ELEMENT, type.asClassDoc());
if (name != null) {
StringBuilder nameBuilder = new StringBuilder(name);
while (reverseIndex.containsKey(nameBuilder.toString())) {
nameBuilder.append('_');
}
name = nameBuilder.toString();
}
name = firstNonNull(name, simpleTranslator.nameFor(type));
namedTypes.put(type, name);
reverseIndex.put(name, type);
return name;
}
|
diff --git a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/networkAdmin/UtilitiesPage.java b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/networkAdmin/UtilitiesPage.java
index 7f36b534b..c02f86f7c 100644
--- a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/networkAdmin/UtilitiesPage.java
+++ b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/networkAdmin/UtilitiesPage.java
@@ -1,1151 +1,1151 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see <http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* UtilitiesPage.java
*
* Created on Mar 18, 2008, 3:30:20 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.iq.dvn.core.web.networkAdmin;
import com.icesoft.faces.async.render.RenderManager;
import com.icesoft.faces.async.render.Renderable;
import edu.harvard.iq.dvn.core.harvest.HarvestFormatType;
import edu.harvard.iq.dvn.core.harvest.HarvestStudyServiceLocal;
import edu.harvard.iq.dvn.core.harvest.HarvesterServiceLocal;
import edu.harvard.iq.dvn.core.index.IndexServiceLocal;
import edu.harvard.iq.dvn.core.index.Indexer;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyFile;
import edu.harvard.iq.dvn.core.study.StudyFileEditBean;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.util.FileUtil;
import edu.harvard.iq.dvn.core.vdc.HarvestingDataverse;
import edu.harvard.iq.dvn.core.vdc.HarvestingDataverseServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import edu.harvard.iq.dvn.core.web.common.VDCBaseBean;
import edu.harvard.iq.dvn.core.gnrs.GNRSServiceLocal;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import com.icesoft.faces.component.inputfile.InputFile;
import com.icesoft.faces.webapp.xmlhttp.FatalRenderingException;
import com.icesoft.faces.webapp.xmlhttp.PersistentFacesState;
import com.icesoft.faces.webapp.xmlhttp.RenderingException;
import com.icesoft.faces.webapp.xmlhttp.TransientRenderingException;
import edu.harvard.iq.dvn.core.study.FileMetadata;
import edu.harvard.iq.dvn.core.study.StudyFileServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyVersion;
import edu.harvard.iq.dvn.core.util.StringUtil;
import java.util.EventObject;
import javax.faces.context.ExternalContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author gdurand
*/
public class UtilitiesPage extends VDCBaseBean implements java.io.Serializable, Renderable {
private static final Logger logger = Logger.getLogger("edu.harvard.iq.dvn.core.web.networkAdmin.UtilitiesPage");
@EJB StudyServiceLocal studyService;
@EJB StudyFileServiceLocal studyFileService;
@EJB IndexServiceLocal indexService;
@EJB HarvestStudyServiceLocal harvestStudyService;
@EJB HarvestingDataverseServiceLocal harvestingDataverseService;
@EJB HarvesterServiceLocal harvesterService;
@EJB VDCServiceLocal vdcService;
@EJB GNRSServiceLocal gnrsService;
private String selectedPanel;
private Long vdcId;
/** Creates a new instance of ImportStudyPage */
public UtilitiesPage() {
persistentFacesState = PersistentFacesState.getInstance();
// Get the session id in a container generic way
ExternalContext ext = FacesContext.getCurrentInstance().getExternalContext();
sessionId = ext.getSession(false).toString();
}
public void init() {
super.init();
vdcId = getVDCRequestBean().getCurrentVDCId();
selectedPanel = getRequestParam("selectedPanel");
}
public String getSelectedPanel() {
return selectedPanel;
}
public void setSelectedPanel(String selectedPanel) {
this.selectedPanel = selectedPanel;
}
// <editor-fold defaultstate="collapsed" desc="studyLock utilities">
public boolean isStudyLockPanelRendered() {
return "studyLock".equals(selectedPanel);
}
String studyLockStudyId;
public String getStudyLockStudyId() {
return studyLockStudyId;
}
public void setStudyLockStudyId(String studyLockStudyId) {
this.studyLockStudyId = studyLockStudyId;
}
public List getStudyLockList() {
return studyService.getStudyLocks();
}
public String removeLock_action() {
try {
studyService.removeStudyLock( new Long( studyLockStudyId) );
addMessage( "studyLockMessage", "Study lock removed (for study id = " + studyLockStudyId + ")" );
} catch (NumberFormatException nfe) {
addMessage( "studyLockMessage", "Action failed: The study id must be of type Long." );
} catch (Exception e) {
e.printStackTrace();
addMessage( "studyLockMessage", "Action failed: An unknown error occurred trying to remove lock for study id = " + studyLockStudyId );
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="index utilities">
public boolean isIndexPanelRendered() {
return "index".equals(selectedPanel);
}
String indexDVId;
String indexStudyIds;
public String getIndexDVId() {
return indexDVId;
}
public void setIndexDVId(String indexDVId) {
this.indexDVId = indexDVId;
}
public String getIndexStudyIds() {
return indexStudyIds;
}
public void setIndexStudyIds(String indexStudyIds) {
this.indexStudyIds = indexStudyIds;
}
private boolean deleteLockDisabled;
public String getIndexLocks(){
String indexLocks = "There is no index lock at this time";
deleteLockDisabled = true;
File lockFile = getLockFile();
if (lockFile != null) {
indexLocks = "There has been a lock on the index since " + (new Date(lockFile.lastModified())).toString();
deleteLockDisabled = false;
}
return indexLocks;
}
private File getLockFileFromDir(File lockFileDir) {
File lockFile=null;
if (lockFileDir.exists()) {
File[] locks = lockFileDir.listFiles(new IndexLockFileNameFilter());
if (locks.length > 0) {
lockFile = locks[0];
}
}
return lockFile;
}
private File getLockFile() {
File lockFile = null;
File lockFileDir = null;
String lockDir = System.getProperty("org.apache.lucene.lockDir");
if (lockDir != null) {
lockFileDir = new File(lockDir);
lockFile = getLockFileFromDir(lockFileDir);
} else {
lockFileDir = new File(Indexer.getInstance().getIndexDir());
lockFile = getLockFileFromDir(lockFileDir);
}
return lockFile;
}
public String indexAll_action() {
try {
File indexDir = new File( Indexer.getInstance().getIndexDir() );
if (!indexDir.exists() || indexDir.list().length == 0) {
indexService.indexAll();
addMessage( "indexMessage", "Reindexing completed." );
} else {
addMessage( "indexMessage", "Reindexing failed: The index directory must be empty before 'index all' can be run." );
}
} catch (Exception e) {
e.printStackTrace();
addMessage( "indexMessage", "Reindexing failed: An unknown error occurred trying to reindex the DVN." );
}
return null;
}
public String indexDV_action() {
try {
VDC vdc = vdcService.findById( new Long( indexDVId) );
if (vdc != null) {
List studyIDList = new ArrayList();
for (Study study : vdc.getOwnedStudies() ) {
studyIDList.add( study.getId() );
}
indexService.updateIndexList( studyIDList );
addMessage( "indexMessage", "Indexing completed (for dataverse id = " + indexDVId + ")" );
} else {
addMessage( "indexMessage", "Indexing failed: There is no dataverse with dvId = " + indexDVId );
}
} catch (NumberFormatException nfe) {
addMessage( "indexMessage", "Indexing failed: The dataverse id must be of type Long." );
} catch (Exception e) {
e.printStackTrace();
addMessage( "indexMessage", "Indexing failed: An unknown error occurred trying to index dataverse with id = " + indexDVId );
}
return null;
}
public String indexStudies_action() {
try {
Map tokenizedLists = determineStudyIds(indexStudyIds);
indexService.updateIndexList( (List) tokenizedLists.get("idList") );
addMessage( "indexMessage", "Indexing request completed." );
addStudyMessages( "indexMessage", tokenizedLists);
} catch (Exception e) {
e.printStackTrace();
addMessage( "indexMessage", "Indexing failed: An unknown error occurred trying to index the following: \"" + indexStudyIds + "\"" );
}
return null;
}
public String indexLocks_action(){
File lockFile = getLockFile();
if (lockFile.exists()){
if (lockFile.delete()){
addMessage("indexMessage", "Index lock deleted");
} else {
addMessage("indexMessage", "Index lock could not be deleted");
}
}
return null;
}
public String indexBatch_action() {
try {
indexService.indexBatch();
addMessage("indexMessage", "Indexing update completed.");
} catch (Exception e) {
e.printStackTrace();
addMessage("indexMessage", "Indexing failed: An unknown error occurred trying to update the index");
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="export utilities">
public boolean isExportPanelRendered() {
return "export".equals(selectedPanel);
}
String exportFormat;
String exportDVId;
String exportStudyIds;
public String getExportFormat() {
return exportFormat;
}
public void setExportFormat(String exportFormat) {
this.exportFormat = exportFormat == null || exportFormat.equals("") ? null : exportFormat;
}
public String getExportDVId() {
return exportDVId;
}
public void setExportDVId(String exportDVId) {
this.exportDVId = exportDVId;
}
public String getExportStudyIds() {
return exportStudyIds;
}
public void setExportStudyIds(String exportStudyIds) {
this.exportStudyIds = exportStudyIds;
}
public String exportUpdated_action() {
try {
studyService.exportUpdatedStudies();
addMessage( "exportMessage", "Export succeeded (for updated studies).");
} catch (Exception e) {
addMessage( "exportMessage", "Export failed: Exception occurred while exporting studies. See export log for details.");
}
return null;
}
public String updateHarvestStudies_action() {
try {
harvestStudyService.updateHarvestStudies();
addMessage( "exportMessage", "Update Harvest Studies succeeded.");
} catch (Exception e) {
addMessage( "exportMessage", "Export failed: An unknown exception occurred while updating harvest studies.");
}
return null;
}
public String exportAll_action() {
try {
List<Long> allStudyIds = studyService.getAllStudyIds();
studyService.exportStudies(allStudyIds, exportFormat);
addMessage( "exportMessage", "Export succeeded for all studies." );
} catch (Exception e) {
e.printStackTrace();
addMessage( "exportMessage", "Export failed: An unknown error occurred trying to export all studies." );
}
return null;
}
public String exportDV_action() {
try {
VDC vdc = vdcService.findById( new Long(exportDVId) );
if (vdc != null) {
List studyIDList = new ArrayList();
for (Study study : vdc.getOwnedStudies() ) {
studyIDList.add( study.getId() );
}
studyService.exportStudies(studyIDList, exportFormat);
addMessage( "exportMessage", "Export succeeded (for dataverse id = " + exportDVId + ")" );
} else {
addMessage( "exportMessage", "Export failed: There is no dataverse with dvId = " + exportDVId );
}
} catch (NumberFormatException nfe) {
addMessage( "exportMessage", "Export failed: The dataverse id must be of type Long.");
} catch (Exception e) {
e.printStackTrace();
addMessage( "exportMessage", "Export failed: An unknown error occurred trying to export dataverse with id = " + exportDVId );
}
return null;
}
public String exportStudies_action() {
try {
Map tokenizedLists = determineStudyIds(exportStudyIds);
studyService.exportStudies( (List) tokenizedLists.get("idList"), exportFormat );
addMessage( "exportMessage", "Export request completed." );
addStudyMessages( "exportMessage", tokenizedLists);
} catch (Exception e) {
e.printStackTrace();
addMessage( "exportMessage", "Export failed: An unknown error occurred trying to export the following: \"" + exportStudyIds + "\"" );
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="harvest utilities">
public boolean isHarvestPanelRendered() {
return "harvest".equals(selectedPanel);
}
Long harvestDVId;
String harvestIdentifier;
public Long getHarvestDVId() {
return harvestDVId;
}
public void setHarvestDVId(Long harvestDVId) {
this.harvestDVId = harvestDVId;
}
public String getHarvestIdentifier() {
return harvestIdentifier;
}
public void setHarvestIdentifier(String harvestIdentifier) {
this.harvestIdentifier = harvestIdentifier;
}
public List<SelectItem> getHarvestDVs() {
List harvestDVSelectItems = new ArrayList<SelectItem>();
Iterator iter = harvestingDataverseService.findAll().iterator();
while (iter.hasNext()) {
HarvestingDataverse hd = (HarvestingDataverse) iter.next();
harvestDVSelectItems.add( new SelectItem(hd.getId(), hd.getVdc().getName()) );
}
return harvestDVSelectItems;
}
public String harvestStudy_action() {
String link = null;
HarvestingDataverse hd = null;
try {
hd = harvestingDataverseService.find( harvestDVId );
Long studyId = harvesterService.getRecord(hd, harvestIdentifier, hd.getHarvestFormatType().getMetadataPrefix());
if (studyId != null) {
indexService.updateStudy(studyId);
// create link String
HttpServletRequest req = (HttpServletRequest) getExternalContext().getRequest();
link = req.getScheme() +"://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath()
+ "/dv/" + hd.getVdc().getAlias() + "/faces/study/StudyPage.xhtml?studyId=" + studyId;
}
addMessage( "harvestMessage", "Harvest succeeded" + (link == null ? "." : ": " + link ) );
} catch (Exception e) {
e.printStackTrace();
addMessage( "harvestMessage", "Harvest failed: An unexpected error occurred trying to get this record." );
addMessage( "harvestMessage", "Exception message: " + e.getMessage() );
addMessage( "harvestMessage", "Harvest URL: " + hd.getServerUrl() + "?verb=GetRecord&identifier=" + harvestIdentifier + "&metadataPrefix=" + hd.getHarvestFormatType().getMetadataPrefix() );
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="file utilities">
public boolean isFilePanelRendered() {
return "file".equals(selectedPanel);
}
String fileExtension;
String fileStudyIds;
public String getFileExtension() {
return fileExtension;
}
public void setFileExtension(String fileExtension) {
this.fileExtension = fileExtension;
}
public String getFileStudyIds() {
return fileStudyIds;
}
public void setFileStudyIds(String fileStudyIds) {
this.fileStudyIds = fileStudyIds;
}
public String determineFileTypeForExtension_action() {
try {
List<FileMetadata> fileMetadatas = studyFileService.getStudyFilesByExtension(fileExtension);
Map<String,Integer> fileTypeCounts = new HashMap<String,Integer>();
for ( FileMetadata fmd : fileMetadatas ) {
StudyFile sf = fmd.getStudyFile();
String newFileType = FileUtil.determineFileType( fmd );
sf.setFileType( newFileType );
studyFileService.updateStudyFile(sf);
Integer count = fileTypeCounts.get(newFileType);
if ( fileTypeCounts.containsKey(newFileType)) {
fileTypeCounts.put( newFileType, fileTypeCounts.get(newFileType) + 1 );
} else {
fileTypeCounts.put( newFileType, 1 );
}
}
addMessage( "fileMessage", "Determine File Type request completed for extension ." + fileExtension );
for (String key : fileTypeCounts.keySet()) {
addMessage( "fileMessage", fileTypeCounts.get(key) + (fileTypeCounts.get(key) == 1 ? " file" : " files") + " set to type: " + key);
}
} catch (Exception e) {
e.printStackTrace();
addMessage( "fileMessage", "Request failed: An unknown error occurred trying to process the following extension: \"" + fileExtension + "\"" );
}
return null;
}
public String determineFileTypeForStudies_action() {
try {
Map tokenizedLists = determineStudyIds(fileStudyIds);
for (Iterator<Long> iter = ((List<Long>) tokenizedLists.get("idList")).iterator(); iter.hasNext();) {
Long studyId = iter.next();
Study study = studyService.getStudy(studyId);
// determine the file type for the latest version of the study
for ( FileMetadata fmd : study.getLatestVersion().getFileMetadatas() ) {
fmd.getStudyFile().setFileType( FileUtil.determineFileType( fmd ) );
}
studyService.updateStudy(study);
}
addMessage( "fileMessage", "Determine File Type request completed." );
addStudyMessages("fileMessage", tokenizedLists);
} catch (Exception e) {
e.printStackTrace();
addMessage( "fileMessage", "Request failed: An unknown error occurred trying to process the following: \"" + fileStudyIds + "\"" );
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="import utilities">
public boolean isImportPanelRendered() {
return "import".equals(selectedPanel);
}
private Long importDVId;
private Long importFileFormat;
private String importBatchDir;
// file upload completed percent (Progress)
private int fileProgress;
// render manager for the application, uses session id for on demand
// render group.
private String sessionId;
private RenderManager renderManager;
private PersistentFacesState persistentFacesState;
public static final Log mLog = LogFactory.getLog(UtilitiesPage.class);
private InputFile inputFile;
public Long getImportDVId() {
return importDVId;
}
public void setImportDVId(Long importDVId) {
this.importDVId = importDVId;
}
public Long getImportFileFormat() {
return importFileFormat;
}
public void setImportFileFormat(Long importFileFormat) {
this.importFileFormat = importFileFormat;
}
public String getImportBatchDir() {
return importBatchDir;
}
public void setImportBatchDir(String importBatchDir) {
this.importBatchDir = importBatchDir;
}
public int getFileProgress(){
return fileProgress;
}
public void setFileProgress(int p){
fileProgress=p;
}
public InputFile getInputFile(){
return inputFile;
}
public void setInputFile(InputFile in){
inputFile = in;
}
public List<SelectItem> getImportDVs() {
List importDVsSelectItems = new ArrayList<SelectItem>();
Iterator iter = vdcService.findAllNonHarvesting().iterator();
while (iter.hasNext()) {
VDC vdc = (VDC) iter.next();
importDVsSelectItems.add( new SelectItem(vdc.getId(), vdc.getName()) );
}
return importDVsSelectItems;
}
public List<SelectItem> getImportFileFormatTypes() {
List<SelectItem> metadataFormatsSelect = new ArrayList<SelectItem>();
for (HarvestFormatType hft : harvesterService.findAllHarvestFormatTypes() ) {
metadataFormatsSelect.add(new SelectItem(hft.getId(),hft.getName()));
}
return metadataFormatsSelect;
}
public String importBatch_action() {
FileHandler logFileHandler = null;
Logger importLogger = null;
if(importBatchDir==null || importBatchDir.equals("")) return null;
try {
int importFailureCount = 0;
int fileFailureCount = 0;
List<Long> studiesToIndex = new ArrayList<Long>();
//sessionId = ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).getId();
File batchDir = new File(importBatchDir);
if (batchDir.exists() && batchDir.isDirectory()) {
// create Logger
String logTimestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss").format(new Date());
String dvAlias = vdcService.find(importDVId).getAlias();
importLogger = Logger.getLogger("edu.harvard.iq.dvn.core.web.networkAdmin.UtilitiesPage." + dvAlias + "_" + logTimestamp);
String logFileName = FileUtil.getImportFileDir() + File.separator + "batch_" + dvAlias + "_" + logTimestamp + ".log";
logFileHandler = new FileHandler(logFileName);
importLogger.addHandler(logFileHandler );
importLogger.info("BEGIN BATCH IMPORT (dvId = " + importDVId + ") from directory: " + importBatchDir);
for (int i=0; i < batchDir.listFiles().length; i++ ) {
File studyDir = batchDir.listFiles()[i];
if (studyDir.isDirectory()) { // one directory per study
importLogger.info("Found study directory: " + studyDir.getName());
File xmlFile = null;
Map<File,String> filesToUpload = new HashMap();
for (int j=0; j < studyDir.listFiles().length; j++ ) {
File file = studyDir.listFiles()[j];
if ( "study.xml".equals(file.getName()) ) {
xmlFile = file;
} else {
addFile(file, "", filesToUpload);
}
}
if (xmlFile != null) {
try {
importLogger.info("Found study.xml and " + filesToUpload.size() + " other " + (filesToUpload.size() == 1 ? "file." : "files."));
// TODO: we need to incorporate the add files step into the same transaction of the import!!!
Study study = studyService.importStudy(
xmlFile, importFileFormat, importDVId, getVDCSessionBean().getLoginBean().getUser().getId());
+ study.getLatestVersion().setVersionNote("Study imported via batch import.");
importLogger.info("Import of study.xml succeeded: study id = " + study.getId());
studiesToIndex.add(study.getId());
if ( !filesToUpload.isEmpty() ) {
List<StudyFileEditBean> fileBeans = new ArrayList();
for (File file : filesToUpload.keySet()) {
StudyFileEditBean fileBean = new StudyFileEditBean( file, studyService.generateFileSystemNameSequence(), study );
fileBean.getFileMetadata().setCategory (filesToUpload.get(file));
fileBeans.add(fileBean);
}
try {
- studyFileService.addFiles( study.getReleasedVersion(), fileBeans, getVDCSessionBean().getLoginBean().getUser() );
- studyService.updateStudy(study); // for now, must call this to persist the new files
+ studyFileService.addFiles( study.getLatestVersion(), fileBeans, getVDCSessionBean().getLoginBean().getUser() );
importLogger.info("File upload succeeded.");
} catch (Exception e) {
fileFailureCount++;
importLogger.severe("File Upload failed (dir = " + studyDir.getName() + "): exception message = " + e.getMessage());
logException (e, importLogger);
}
}
} catch (Exception e) {
importFailureCount++;
importLogger.severe("Import failed (dir = " + studyDir.getName() + "): exception message = " + e.getMessage());
logException (e, importLogger);
}
} else { // no ddi.xml found in studyDir
importLogger.warning("No study.xml file was found in study directory. Skipping... ");
}
} else {
importLogger.warning("Found non directory at top level. Skipping... (filename = " + studyDir.getName() +")");
}
}
// generate status message
String statusMessage = studiesToIndex.size() + (studiesToIndex.size() == 1 ? " study" : " studies") + " successfully imported";
statusMessage += (fileFailureCount == 0 ? "" : " (" + fileFailureCount + " of which failed file upload)");
statusMessage += (importFailureCount == 0 ? "." : "; " + importFailureCount + (importFailureCount == 1 ? " study" : " studies") + " failed import.");
importLogger.info("COMPLETED BATCH IMPORT: " + statusMessage );
// now index all studies
importLogger.info("POST BATCH IMPORT, start calls to index.");
indexService.updateIndexList(studiesToIndex);
importLogger.info("POST BATCH IMPORT, calls to index finished.");
addMessage( "importMessage", "Batch Import request completed." );
addMessage( "importMessage", statusMessage );
addMessage( "importMessage", "For more detail see log file at: " + logFileName );
} else {
addMessage( "importMessage", "Batch Import failed: " + importBatchDir + " does not exist or is not a directory." );
}
} catch (Exception e) {
e.printStackTrace();
addMessage( "importMessage", "Batch Import failed: An unexpected error occurred during processing." );
addMessage( "importMessage", "Exception message: " + e.getMessage() );
} finally {
if ( logFileHandler != null ) {
logFileHandler.close();
importLogger.removeHandler(logFileHandler);
}
// importBatchDir = "";
}
return null;
}
private void addFile(File file, String catName, Map<File,String> filesToUpload) throws Exception{
if ( file.getName()!= null && file.getName().startsWith(".")) {
// ignore hidden files (ie files that start with "."
} else if (file.isDirectory()) {
String tempCatName = StringUtil.isEmpty(catName) ? file.getName() : catName + " - " + file.getName();
for (int j=0; j < file.listFiles().length; j++ ) {
addFile( file.listFiles()[j], tempCatName, filesToUpload );
}
} else {
File tempFile = FileUtil.createTempFile( sessionId, file.getName() );
FileUtil.copyFile(file, tempFile);
filesToUpload.put(tempFile, catName);
}
}
/**
* Return the reference to the
* {@link com.icesoft.faces.webapp.xmlhttp.PersistentFacesState
* PersistentFacesState} associated with this Renderable.
* <p/>
* The typical (and recommended usage) is to get and hold a reference to the
* PersistentFacesState in the constructor of your managed bean and return
* that reference from this method.
*
* @return the PersistentFacesState associated with this Renderable
*/
public PersistentFacesState getState() {
return persistentFacesState;
}
public void setRenderManager(RenderManager renderManager) {
this.renderManager = renderManager;
renderManager.getOnDemandRenderer(sessionId).add(this);
}
/**
* Callback method that is called if any exception occurs during an attempt
* to render this Renderable.
* <p/>
* It is up to the application developer to implement appropriate policy
* when a RenderingException occurs. Different policies might be
* appropriate based on the severity of the exception. For example, if the
* exception is fatal (the session has expired), no further attempts should
* be made to render this Renderable and the application may want to remove
* the Renderable from some or all of the
* {@link com.icesoft.faces.async.render.GroupAsyncRenderer}s it
* belongs to. If it is a transient exception (like a client's connection is
* temporarily unavailable) then the application has the option of removing
* the Renderable from GroupRenderers or leaving them and allowing another
* render call to be attempted.
*
* @param renderingException The exception that occurred when attempting to
* render this Renderable.
*/
public void renderingException(RenderingException renderingException) {
if (mLog.isTraceEnabled() &&
renderingException instanceof TransientRenderingException) {
mLog.trace("InputFileController Transient Rendering excpetion:", renderingException);
} else if (renderingException instanceof FatalRenderingException) {
if (mLog.isTraceEnabled()) {
mLog.trace("InputFileController Fatal rendering exception: ", renderingException);
}
renderManager.getOnDemandRenderer(sessionId).remove(this);
renderManager.getOnDemandRenderer(sessionId).dispose();
}
}
/**
* Dispose callback called due to a view closing or session
* invalidation/timeout
*/
public void dispose() throws Exception {
if (mLog.isTraceEnabled()) {
mLog.trace("OutputProgressController dispose OnDemandRenderer for session: " + sessionId);
}
renderManager.getOnDemandRenderer(sessionId).remove(this);
renderManager.getOnDemandRenderer(sessionId).dispose();
}
/**
* <p>This method is bound to the inputFile component and is executed
* multiple times during the file upload process. Every call allows
* the user to finds out what percentage of the file has been uploaded.
* This progress information can then be used with a progressBar component
* for user feedback on the file upload progress. </p>
*
* @param event holds a InputFile object in its source which can be probed
* for the file upload percentage complete.
*/
public void fileUploadProgress(EventObject event) {
InputFile ifile = (InputFile) event.getSource();
fileProgress = ifile.getFileInfo().getPercent();
getImportFileFormat();
getImportDVId();
// System.out.println("sessid "+ sessionId);
//getImportFileFormat()getImportFileFormat() System.out.println("render "+ renderManager.getOnDemandRenderer(sessionId).toString());
if (persistentFacesState !=null) {
renderManager.getOnDemandRenderer(sessionId).requestRender();}
}
public String importSingleFile_action(){
if(inputFile==null) return null;
File originalFile = inputFile.getFile();
try {
Study study = studyService.importStudy(
originalFile,getImportFileFormat(), getImportDVId(), getVDCSessionBean().getLoginBean().getUser().getId());
indexService.updateStudy(study.getId());
// create result message
HttpServletRequest req = (HttpServletRequest) getExternalContext().getRequest();
String studyURL = req.getScheme() +"://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath()
+ "/dv/" + study.getOwner().getAlias() + "/faces/study/StudyPage.xhtml?globalId=" + study.getGlobalId();
addMessage( "importMessage", "Import succeeded." );
addMessage( "importMessage", "Study URL: " + studyURL );
}catch(Exception e) {
e.printStackTrace();
addMessage( "harvestMessage", "Import failed: An unexpected error occurred trying to import this study." );
addMessage( "harvestMessage", "Exception message: " + e.getMessage() );
}
return null;
}
public String uploadFile() {
inputFile =getInputFile();
String str="";
if (inputFile.getStatus() != InputFile.SAVED){
str = "File " + inputFile.getFileInfo().getFileName()+ " has not been saved. \n"+
"Status: "+ inputFile.getStatus();
logger.info(str);
addMessage("importMessage",str);
if(inputFile.getStatus() != InputFile.INVALID)
return null;
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="delete utilities">
public boolean isDeletePanelRendered() {
return "delete".equals(selectedPanel);
}
String deleteStudyIds;
public String getDeleteStudyIds() {
return deleteStudyIds;
}
public void setDeleteStudyIds(String deleteStudyIds) {
this.deleteStudyIds = deleteStudyIds;
}
public String deleteStudies_action() {
try {
Map tokenizedLists = determineStudyIds(deleteStudyIds);
studyService.deleteStudyList( (List) tokenizedLists.get("idList") );
addMessage( "deleteMessage", "Delete request completed." );
addStudyMessages( "deleteMessage", tokenizedLists);
} catch (Exception e) {
e.printStackTrace();
addMessage( "deleteMessage", "Delete failed: An unknown error occurred trying to delete the following: \"" + deleteStudyIds + "\"" );
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="handle utilities">
public boolean isHandlePanelRendered() {
return "handle".equals(selectedPanel);
}
public String handleRegisterAll_action() {
try {
gnrsService.registerAll();
addMessage( "handleMessage", "Handle registration request completed." );
} catch (Exception e) {
e.printStackTrace();
addMessage( "handleMessage", "Handle registration failed: An unknown error occurred trying to index the following: \"" + indexStudyIds + "\"" );
}
return null;
}
public String handleFixAll_action() {
try {
gnrsService.fixAll();
addMessage( "handleMessage", "Handle re-registration request completed." );
} catch (Exception e) {
e.printStackTrace();
addMessage( "handleMessage", "Handle registration failed: An unknown error occurred trying to index the following: \"" + indexStudyIds + "\"" );
}
return null;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="study utilities">
public boolean isStudyPanelRendered() {
return "study".equals(selectedPanel);
}
String createStudyDraftIds;
public String getCreateStudyDraftIds() {
return createStudyDraftIds;
}
public void setCreateStudyDraftIds(String createStudyDraftIds) {
this.createStudyDraftIds = createStudyDraftIds;
}
public String createStudyDrafts_action() {
try {
Map tokenizedLists = determineStudyIds(createStudyDraftIds);
List ignoredList = new ArrayList();
for (Iterator it = ((List) tokenizedLists.get("idList")).iterator(); it.hasNext();) {
Long studyId = (Long) it.next();
Study study = studyService.getStudy(studyId);
Long currentVersionNumber = study.getLatestVersion().getVersionNumber();
StudyVersion editVersion = study.getEditVersion();
if ( currentVersionNumber.equals(editVersion.getVersionNumber()) ){
// working copy already exists
it.remove();
ignoredList.add(studyId);
} else {
// save new version
studyService.saveStudyVersion(editVersion, getVDCSessionBean().getLoginBean().getUser().getId());
studyService.updateStudyVersion(editVersion);
}
}
tokenizedLists.put("ignoredList", ignoredList );
tokenizedLists.put("ignoredReason", "working verison already exists" );
addMessage( "studyMessage", "Create Study Draft request completed." );
addStudyMessages( "studyMessage", tokenizedLists);
} catch (Exception e) {
e.printStackTrace();
addMessage( "studyMessage", "Create Drafts failed: An unknown error occurred trying to delete the following: \"" + deleteStudyIds + "\"" );
}
return null;
}
// </editor-fold>
// ****************************
// Common methods
// ****************************
private void addMessage(String component, String message) {
FacesMessage facesMsg = new FacesMessage(message);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(component, facesMsg);
}
private void addStudyMessages (String component, Map tokenizedLists) {
if ( tokenizedLists.get("idList") != null && !((List) tokenizedLists.get("idList")).isEmpty() ) {
addMessage( component, "The following studies were successfully processed: " + tokenizedLists.get("idList") );
}
if ( tokenizedLists.get("ignoredList") != null && !((List) tokenizedLists.get("ignoredList")).isEmpty() ) {
addMessage( component, "The following studies were ignored ("
+ ((String) tokenizedLists.get("ignoredReason")) + "): " + tokenizedLists.get("ignoredList") );
}
if ( tokenizedLists.get("invalidStudyIdList") != null && !((List) tokenizedLists.get("invalidStudyIdList")).isEmpty() ) {
addMessage( component, "The following study ids were invalid: " + tokenizedLists.get("invalidStudyIdList") );
}
if ( tokenizedLists.get("failedTokenList") != null && !((List) tokenizedLists.get("failedTokenList")).isEmpty() ) {
addMessage( component, "The following tokens could not be interpreted: " + tokenizedLists.get("failedTokenList") );
}
}
private Map determineIds(String ids) {
List<Long> idList = new ArrayList();
List<String> failedTokenList = new ArrayList();
StringTokenizer st = new StringTokenizer(ids, ",; \t\n\r\f");
while (st.hasMoreTokens()) {
String token = st.nextToken();
try {
idList.add( new Long(token) );
} catch (NumberFormatException nfe) {
if ( token.indexOf("-") == -1 ) {
failedTokenList.add(token);
} else {
try {
Long startId = new Long( token.substring( 0, token.indexOf("-") ) );
Long endId = new Long( token.substring( token.indexOf("-") + 1 ) );
for (long i = startId.longValue(); i <= endId.longValue(); i++) {
idList.add( new Long(i) );
}
} catch (NumberFormatException nfe2) {
failedTokenList.add( token );
}
}
}
}
Map returnMap = new HashMap();
returnMap.put("idList", idList);
returnMap.put("failedTokenList", failedTokenList);
return returnMap;
}
private Map determineStudyIds(String studyIds) {
Map tokenizedLists = determineIds(studyIds);
List invalidStudyIdList = new ArrayList();
for (Iterator<Long> iter = ((List<Long>) tokenizedLists.get("idList")).iterator(); iter.hasNext();) {
Long id = iter.next();
try {
studyService.getStudy(id);
} catch (EJBException e) {
if (e.getCause() instanceof IllegalArgumentException) {
invalidStudyIdList.add(id);
iter.remove();
} else {
throw e;
}
}
}
tokenizedLists.put("invalidStudyIdList", invalidStudyIdList);
return tokenizedLists;
}
// duplicate from harvester
private void logException(Throwable e, Logger logger) {
boolean cause = false;
String fullMessage = "";
do {
String message = e.getClass().getName() + " " + e.getMessage();
if (cause) {
message = "\nCaused By Exception.................... " + e.getClass().getName() + " " + e.getMessage();
}
StackTraceElement[] ste = e.getStackTrace();
message += "\nStackTrace: \n";
for (int m = 0; m < ste.length; m++) {
message += ste[m].toString() + "\n";
}
fullMessage += message;
cause = true;
} while ((e = e.getCause()) != null);
logger.severe(fullMessage);
}
public boolean isDeleteLockDisabled() {
return deleteLockDisabled;
}
public void setDeleteLockDisabled(boolean deleteLockDisabled) {
this.deleteLockDisabled = deleteLockDisabled;
}
}
| false | true | public String importBatch_action() {
FileHandler logFileHandler = null;
Logger importLogger = null;
if(importBatchDir==null || importBatchDir.equals("")) return null;
try {
int importFailureCount = 0;
int fileFailureCount = 0;
List<Long> studiesToIndex = new ArrayList<Long>();
//sessionId = ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).getId();
File batchDir = new File(importBatchDir);
if (batchDir.exists() && batchDir.isDirectory()) {
// create Logger
String logTimestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss").format(new Date());
String dvAlias = vdcService.find(importDVId).getAlias();
importLogger = Logger.getLogger("edu.harvard.iq.dvn.core.web.networkAdmin.UtilitiesPage." + dvAlias + "_" + logTimestamp);
String logFileName = FileUtil.getImportFileDir() + File.separator + "batch_" + dvAlias + "_" + logTimestamp + ".log";
logFileHandler = new FileHandler(logFileName);
importLogger.addHandler(logFileHandler );
importLogger.info("BEGIN BATCH IMPORT (dvId = " + importDVId + ") from directory: " + importBatchDir);
for (int i=0; i < batchDir.listFiles().length; i++ ) {
File studyDir = batchDir.listFiles()[i];
if (studyDir.isDirectory()) { // one directory per study
importLogger.info("Found study directory: " + studyDir.getName());
File xmlFile = null;
Map<File,String> filesToUpload = new HashMap();
for (int j=0; j < studyDir.listFiles().length; j++ ) {
File file = studyDir.listFiles()[j];
if ( "study.xml".equals(file.getName()) ) {
xmlFile = file;
} else {
addFile(file, "", filesToUpload);
}
}
if (xmlFile != null) {
try {
importLogger.info("Found study.xml and " + filesToUpload.size() + " other " + (filesToUpload.size() == 1 ? "file." : "files."));
// TODO: we need to incorporate the add files step into the same transaction of the import!!!
Study study = studyService.importStudy(
xmlFile, importFileFormat, importDVId, getVDCSessionBean().getLoginBean().getUser().getId());
importLogger.info("Import of study.xml succeeded: study id = " + study.getId());
studiesToIndex.add(study.getId());
if ( !filesToUpload.isEmpty() ) {
List<StudyFileEditBean> fileBeans = new ArrayList();
for (File file : filesToUpload.keySet()) {
StudyFileEditBean fileBean = new StudyFileEditBean( file, studyService.generateFileSystemNameSequence(), study );
fileBean.getFileMetadata().setCategory (filesToUpload.get(file));
fileBeans.add(fileBean);
}
try {
studyFileService.addFiles( study.getReleasedVersion(), fileBeans, getVDCSessionBean().getLoginBean().getUser() );
studyService.updateStudy(study); // for now, must call this to persist the new files
importLogger.info("File upload succeeded.");
} catch (Exception e) {
fileFailureCount++;
importLogger.severe("File Upload failed (dir = " + studyDir.getName() + "): exception message = " + e.getMessage());
logException (e, importLogger);
}
}
} catch (Exception e) {
importFailureCount++;
importLogger.severe("Import failed (dir = " + studyDir.getName() + "): exception message = " + e.getMessage());
logException (e, importLogger);
}
} else { // no ddi.xml found in studyDir
importLogger.warning("No study.xml file was found in study directory. Skipping... ");
}
} else {
importLogger.warning("Found non directory at top level. Skipping... (filename = " + studyDir.getName() +")");
}
}
// generate status message
String statusMessage = studiesToIndex.size() + (studiesToIndex.size() == 1 ? " study" : " studies") + " successfully imported";
statusMessage += (fileFailureCount == 0 ? "" : " (" + fileFailureCount + " of which failed file upload)");
statusMessage += (importFailureCount == 0 ? "." : "; " + importFailureCount + (importFailureCount == 1 ? " study" : " studies") + " failed import.");
importLogger.info("COMPLETED BATCH IMPORT: " + statusMessage );
// now index all studies
importLogger.info("POST BATCH IMPORT, start calls to index.");
indexService.updateIndexList(studiesToIndex);
importLogger.info("POST BATCH IMPORT, calls to index finished.");
addMessage( "importMessage", "Batch Import request completed." );
addMessage( "importMessage", statusMessage );
addMessage( "importMessage", "For more detail see log file at: " + logFileName );
} else {
addMessage( "importMessage", "Batch Import failed: " + importBatchDir + " does not exist or is not a directory." );
}
} catch (Exception e) {
e.printStackTrace();
addMessage( "importMessage", "Batch Import failed: An unexpected error occurred during processing." );
addMessage( "importMessage", "Exception message: " + e.getMessage() );
} finally {
if ( logFileHandler != null ) {
logFileHandler.close();
importLogger.removeHandler(logFileHandler);
}
// importBatchDir = "";
}
return null;
}
| public String importBatch_action() {
FileHandler logFileHandler = null;
Logger importLogger = null;
if(importBatchDir==null || importBatchDir.equals("")) return null;
try {
int importFailureCount = 0;
int fileFailureCount = 0;
List<Long> studiesToIndex = new ArrayList<Long>();
//sessionId = ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).getId();
File batchDir = new File(importBatchDir);
if (batchDir.exists() && batchDir.isDirectory()) {
// create Logger
String logTimestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss").format(new Date());
String dvAlias = vdcService.find(importDVId).getAlias();
importLogger = Logger.getLogger("edu.harvard.iq.dvn.core.web.networkAdmin.UtilitiesPage." + dvAlias + "_" + logTimestamp);
String logFileName = FileUtil.getImportFileDir() + File.separator + "batch_" + dvAlias + "_" + logTimestamp + ".log";
logFileHandler = new FileHandler(logFileName);
importLogger.addHandler(logFileHandler );
importLogger.info("BEGIN BATCH IMPORT (dvId = " + importDVId + ") from directory: " + importBatchDir);
for (int i=0; i < batchDir.listFiles().length; i++ ) {
File studyDir = batchDir.listFiles()[i];
if (studyDir.isDirectory()) { // one directory per study
importLogger.info("Found study directory: " + studyDir.getName());
File xmlFile = null;
Map<File,String> filesToUpload = new HashMap();
for (int j=0; j < studyDir.listFiles().length; j++ ) {
File file = studyDir.listFiles()[j];
if ( "study.xml".equals(file.getName()) ) {
xmlFile = file;
} else {
addFile(file, "", filesToUpload);
}
}
if (xmlFile != null) {
try {
importLogger.info("Found study.xml and " + filesToUpload.size() + " other " + (filesToUpload.size() == 1 ? "file." : "files."));
// TODO: we need to incorporate the add files step into the same transaction of the import!!!
Study study = studyService.importStudy(
xmlFile, importFileFormat, importDVId, getVDCSessionBean().getLoginBean().getUser().getId());
study.getLatestVersion().setVersionNote("Study imported via batch import.");
importLogger.info("Import of study.xml succeeded: study id = " + study.getId());
studiesToIndex.add(study.getId());
if ( !filesToUpload.isEmpty() ) {
List<StudyFileEditBean> fileBeans = new ArrayList();
for (File file : filesToUpload.keySet()) {
StudyFileEditBean fileBean = new StudyFileEditBean( file, studyService.generateFileSystemNameSequence(), study );
fileBean.getFileMetadata().setCategory (filesToUpload.get(file));
fileBeans.add(fileBean);
}
try {
studyFileService.addFiles( study.getLatestVersion(), fileBeans, getVDCSessionBean().getLoginBean().getUser() );
importLogger.info("File upload succeeded.");
} catch (Exception e) {
fileFailureCount++;
importLogger.severe("File Upload failed (dir = " + studyDir.getName() + "): exception message = " + e.getMessage());
logException (e, importLogger);
}
}
} catch (Exception e) {
importFailureCount++;
importLogger.severe("Import failed (dir = " + studyDir.getName() + "): exception message = " + e.getMessage());
logException (e, importLogger);
}
} else { // no ddi.xml found in studyDir
importLogger.warning("No study.xml file was found in study directory. Skipping... ");
}
} else {
importLogger.warning("Found non directory at top level. Skipping... (filename = " + studyDir.getName() +")");
}
}
// generate status message
String statusMessage = studiesToIndex.size() + (studiesToIndex.size() == 1 ? " study" : " studies") + " successfully imported";
statusMessage += (fileFailureCount == 0 ? "" : " (" + fileFailureCount + " of which failed file upload)");
statusMessage += (importFailureCount == 0 ? "." : "; " + importFailureCount + (importFailureCount == 1 ? " study" : " studies") + " failed import.");
importLogger.info("COMPLETED BATCH IMPORT: " + statusMessage );
// now index all studies
importLogger.info("POST BATCH IMPORT, start calls to index.");
indexService.updateIndexList(studiesToIndex);
importLogger.info("POST BATCH IMPORT, calls to index finished.");
addMessage( "importMessage", "Batch Import request completed." );
addMessage( "importMessage", statusMessage );
addMessage( "importMessage", "For more detail see log file at: " + logFileName );
} else {
addMessage( "importMessage", "Batch Import failed: " + importBatchDir + " does not exist or is not a directory." );
}
} catch (Exception e) {
e.printStackTrace();
addMessage( "importMessage", "Batch Import failed: An unexpected error occurred during processing." );
addMessage( "importMessage", "Exception message: " + e.getMessage() );
} finally {
if ( logFileHandler != null ) {
logFileHandler.close();
importLogger.removeHandler(logFileHandler);
}
// importBatchDir = "";
}
return null;
}
|
diff --git a/src/DistGrep/ConnectionHandler.java b/src/DistGrep/ConnectionHandler.java
index 88de458..3f94d56 100644
--- a/src/DistGrep/ConnectionHandler.java
+++ b/src/DistGrep/ConnectionHandler.java
@@ -1,225 +1,228 @@
package DistGrep;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.Enumeration;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created with IntelliJ IDEA.
* User: kyle
* Date: 9/14/13
* Time: 8:58 PM
* To change this template use File | Settings | File Templates.
*/
public class ConnectionHandler implements Runnable {
private LinkedBlockingQueue<Socket> connectionQueue;
private String searchPath;
private boolean shouldRun = true;
private Config conf;
public ConnectionHandler(LinkedBlockingQueue<Socket> connectionQueue, Config conf) {
this.connectionQueue = connectionQueue;
this.conf = conf;
this.searchPath = conf.valueFor("searchPath");
}
public void kill() {
this.shouldRun = false;
}
public void run() {
System.out.println("[" + this.getClass().toString() + "]: Waiting to handle accepted connections: Started");
while(shouldRun) {
// Poll the connection queue for an accepted connection.
Socket clientSocket = null;
InetAddress clientAddress = null;
try {
clientSocket = connectionQueue.poll(1, TimeUnit.MINUTES);
}
catch (InterruptedException e) {
break;
}
//If we timed out or our thread was interrupted, continue.
if(clientSocket == null)
continue;
clientAddress = clientSocket.getInetAddress();
System.out.println("[" + this.getClass().toString() + "]: Got connection from: " + clientAddress);
String clientMessage;
//Attempt to get the message from the client.
try {
clientMessage = readStringFromConnection(clientSocket);
//clientSocket.close();
}
catch (IOException e) {
System.err.println("Failed to get message from client. " + e);
+ try {
+ clientSocket.close();
+ } catch (IOException ex) {}
continue;
}
System.out.println("[" + this.getClass().toString() + "]: Got message from: " + clientAddress);
String[] parsedMessage;
try {
parsedMessage = parseMessage(clientMessage);
}
catch (IllegalStateException e) {
continue;
}
String header = parsedMessage[0];
String body = parsedMessage[1];
//If a request was sent to this machine, it will execute a grep and sends the results back to the initiator
// if(header.equalsIgnoreCase("searchrequest")) {
System.out.println("[" + this.getClass().toString() + "]: Running search for: " + clientAddress);
CommandExecutor grepExecutor = null;
try {
grepExecutor = Search.runSearch(searchPath, body);
}
catch (IOException e) {
System.err.println("Failed to generate search results. " + e);
}
catch (InterruptedException e) {
break;
}
try {
System.out.println("[" + this.getClass().toString() + "]: Delivering results to: " + clientAddress);
deliverResults(clientSocket, grepExecutor);
clientSocket.close();
}
catch (SocketException e) {
System.err.println("[" + this.getClass().toString() + "]: Failed to enumerate network devices. " + e);
continue;
}
catch (IOException e) {
System.err.println("[" + this.getClass().toString() + "]: Failed to deliver results to client. " + e);
continue;
}
/*
} else if(header.equalsIgnoreCase("searchresult")) {
body = body.replace("<br>", "\n");
System.out.println("Search results from " + clientAddress + ":\n----------\n" + body);
}
*/
}
System.out.println("[" + this.getClass().toString() + "] is dying.");
}
//Reads a string message from a client.
private String readStringFromConnection(Socket clientSocket) throws IOException {
String clientMessage = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
char[] buffer = new char[3000];
int numberOfChars = bufferedReader.read(buffer, 0, 3000);
clientMessage = new String(buffer, 0, numberOfChars);
return clientMessage;
}
// Parse the received XML-message and extract header and body information
// Returns a string array of size 2. The first member is the header,
// The second is the body.
private String[] parseMessage(String clientMessage) throws NullPointerException, IllegalStateException {
String header = null;
String body = null;
clientMessage = clientMessage.replace("\n", "<br>");
final Pattern headerpattern = Pattern.compile("<header>(.+?)</header>");
final Matcher headermatcher = headerpattern.matcher(clientMessage);
headermatcher.find();
header = headermatcher.group(1);
final Pattern bodypattern = Pattern.compile("<body>(.+?)</body>");
final Matcher bodymatcher = bodypattern.matcher(clientMessage);
bodymatcher.find();
body = bodymatcher.group(1);
String[] parsedMessage = new String[2];
parsedMessage[0] = header;
parsedMessage[1] = body;
return parsedMessage;
}
private void deliverResults(Socket clientSocket, CommandExecutor grepExecutor) throws SocketException, IOException {
OutputStream clientOutputStream = clientSocket.getOutputStream();
BufferedReader processOutput = grepExecutor.getProcessReader();
String line;
while(!grepExecutor.processIsTerminated()) {
line = processOutput.readLine();
if(line != null)
clientOutputStream.write((line + "\n").getBytes());
}
while((line = processOutput.readLine()) != null) {
clientOutputStream.write((line + "\n").getBytes());
}
/*
while ((line = b.readLine()) != null) {
text += line + "\n";
System.out.println(text.length());
System.out.println(p.exitValue());
p.
}
clientSocket.getOutputStream().write(searchResults.getBytes());
/*
if(isLocalInetAddress(clientSocket)) {
System.out.println("Search results from localhost:\n"+searchResults+"---\n");
} else {
Connection backcon = new Connection(conf);
String[] receiver = new String[1];
receiver[0] = clientSocket.toString().substring(1);
backcon.sendMessage(searchResults, "searchresult", receiver);
}
*/
}
//Check, if an address is local.
private boolean isLocalInetAddress(InetAddress addr) throws SocketException {
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
while(n.hasMoreElements())
{
NetworkInterface e =(NetworkInterface) n.nextElement();
Enumeration ee = e.getInetAddresses();
while(ee.hasMoreElements())
{
InetAddress i= (InetAddress) ee.nextElement();
if(addr.toString().substring(1).equalsIgnoreCase(i.getHostAddress().toString())) {
return true;
}
}
}
return false;
}
}
| true | true | public void run() {
System.out.println("[" + this.getClass().toString() + "]: Waiting to handle accepted connections: Started");
while(shouldRun) {
// Poll the connection queue for an accepted connection.
Socket clientSocket = null;
InetAddress clientAddress = null;
try {
clientSocket = connectionQueue.poll(1, TimeUnit.MINUTES);
}
catch (InterruptedException e) {
break;
}
//If we timed out or our thread was interrupted, continue.
if(clientSocket == null)
continue;
clientAddress = clientSocket.getInetAddress();
System.out.println("[" + this.getClass().toString() + "]: Got connection from: " + clientAddress);
String clientMessage;
//Attempt to get the message from the client.
try {
clientMessage = readStringFromConnection(clientSocket);
//clientSocket.close();
}
catch (IOException e) {
System.err.println("Failed to get message from client. " + e);
continue;
}
System.out.println("[" + this.getClass().toString() + "]: Got message from: " + clientAddress);
String[] parsedMessage;
try {
parsedMessage = parseMessage(clientMessage);
}
catch (IllegalStateException e) {
continue;
}
String header = parsedMessage[0];
String body = parsedMessage[1];
//If a request was sent to this machine, it will execute a grep and sends the results back to the initiator
// if(header.equalsIgnoreCase("searchrequest")) {
System.out.println("[" + this.getClass().toString() + "]: Running search for: " + clientAddress);
CommandExecutor grepExecutor = null;
try {
grepExecutor = Search.runSearch(searchPath, body);
}
catch (IOException e) {
System.err.println("Failed to generate search results. " + e);
}
catch (InterruptedException e) {
break;
}
try {
System.out.println("[" + this.getClass().toString() + "]: Delivering results to: " + clientAddress);
deliverResults(clientSocket, grepExecutor);
clientSocket.close();
}
catch (SocketException e) {
System.err.println("[" + this.getClass().toString() + "]: Failed to enumerate network devices. " + e);
continue;
}
catch (IOException e) {
System.err.println("[" + this.getClass().toString() + "]: Failed to deliver results to client. " + e);
continue;
}
/*
} else if(header.equalsIgnoreCase("searchresult")) {
body = body.replace("<br>", "\n");
System.out.println("Search results from " + clientAddress + ":\n----------\n" + body);
}
*/
}
| public void run() {
System.out.println("[" + this.getClass().toString() + "]: Waiting to handle accepted connections: Started");
while(shouldRun) {
// Poll the connection queue for an accepted connection.
Socket clientSocket = null;
InetAddress clientAddress = null;
try {
clientSocket = connectionQueue.poll(1, TimeUnit.MINUTES);
}
catch (InterruptedException e) {
break;
}
//If we timed out or our thread was interrupted, continue.
if(clientSocket == null)
continue;
clientAddress = clientSocket.getInetAddress();
System.out.println("[" + this.getClass().toString() + "]: Got connection from: " + clientAddress);
String clientMessage;
//Attempt to get the message from the client.
try {
clientMessage = readStringFromConnection(clientSocket);
//clientSocket.close();
}
catch (IOException e) {
System.err.println("Failed to get message from client. " + e);
try {
clientSocket.close();
} catch (IOException ex) {}
continue;
}
System.out.println("[" + this.getClass().toString() + "]: Got message from: " + clientAddress);
String[] parsedMessage;
try {
parsedMessage = parseMessage(clientMessage);
}
catch (IllegalStateException e) {
continue;
}
String header = parsedMessage[0];
String body = parsedMessage[1];
//If a request was sent to this machine, it will execute a grep and sends the results back to the initiator
// if(header.equalsIgnoreCase("searchrequest")) {
System.out.println("[" + this.getClass().toString() + "]: Running search for: " + clientAddress);
CommandExecutor grepExecutor = null;
try {
grepExecutor = Search.runSearch(searchPath, body);
}
catch (IOException e) {
System.err.println("Failed to generate search results. " + e);
}
catch (InterruptedException e) {
break;
}
try {
System.out.println("[" + this.getClass().toString() + "]: Delivering results to: " + clientAddress);
deliverResults(clientSocket, grepExecutor);
clientSocket.close();
}
catch (SocketException e) {
System.err.println("[" + this.getClass().toString() + "]: Failed to enumerate network devices. " + e);
continue;
}
catch (IOException e) {
System.err.println("[" + this.getClass().toString() + "]: Failed to deliver results to client. " + e);
continue;
}
/*
} else if(header.equalsIgnoreCase("searchresult")) {
body = body.replace("<br>", "\n");
System.out.println("Search results from " + clientAddress + ":\n----------\n" + body);
}
*/
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/funlib/LastEdge.java b/src/de/uni_koblenz/jgralab/greql2/funlib/LastEdge.java
index ea9d7118f..a4b6b63eb 100644
--- a/src/de/uni_koblenz/jgralab/greql2/funlib/LastEdge.java
+++ b/src/de/uni_koblenz/jgralab/greql2/funlib/LastEdge.java
@@ -1,123 +1,123 @@
/*
* JGraLab - The Java Graph Laboratory
*
* Copyright (C) 2006-2011 Institute for Software Technology
* University of Koblenz-Landau, Germany
* [email protected]
*
* For bug reports, documentation and further information, visit
*
* http://jgralab.uni-koblenz.de
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with Eclipse (or a modified version of that program or an Eclipse
* plugin), containing parts covered by the terms of the Eclipse Public
* License (EPL), the licensors of this Program grant you additional
* permission to convey the resulting work. Corresponding Source for a
* non-source form of such a combination shall include the source code for
* the parts of JGraLab used as well as that of the covered work.
*/
package de.uni_koblenz.jgralab.greql2.funlib;
import java.util.ArrayList;
import de.uni_koblenz.jgralab.AttributedElement;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.graphmarker.AbstractGraphMarker;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.WrongFunctionParameterException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueImpl;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueType;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueTypeCollection;
/**
* Returns the last edge (of a type matching the given TypeCollection) in the
* graph
*
* <dl>
* <dt><b>GReQL-signature</b></dt>
* <dd><code>EDGE lastEdge()</code></dd>
* <dd><code>EDGE lastEdge(tc: TYPECOLLECTION)</code></dd>
* </dd>
* <dd> </dd>
* </dl>
* <dl>
* <dt></dt>
* <dd>
* <dd>the last edge (of a type matching tc) in Eseq
* </dl>
* </dd> </dl>
*
* @see LastVertex, FirstEdge
* @author [email protected]
*
*/
public class LastEdge extends Greql2Function {
{
JValueType[][] x = { { JValueType.EDGE },
{ JValueType.TYPECOLLECTION, JValueType.EDGE } };
signatures = x;
description = "Returns the last edge (optional restricted by TypeCollection) in the graph.";
Category[] c = { Category.GRAPH };
categories = c;
}
@Override
public JValue evaluate(Graph graph,
AbstractGraphMarker<AttributedElement> subgraph, JValue[] arguments)
throws EvaluateException {
switch (checkArguments(arguments)) {
case 0:
return new JValueImpl(graph.getLastEdge());
case 1:
Edge current = graph.getLastEdge();
- JValueTypeCollection tc = arguments[2].toJValueTypeCollection();
+ JValueTypeCollection tc = arguments[0].toJValueTypeCollection();
while (current != null) {
if (tc.acceptsType(current.getAttributedElementClass())) {
return new JValueImpl(current);
}
current = current.getPrevEdge();
}
return new JValueImpl((Edge) null);
default:
throw new WrongFunctionParameterException(this, arguments);
}
}
@Override
public long getEstimatedCosts(ArrayList<Long> inElements) {
return 1000;
}
@Override
public double getSelectivity() {
return 0.2;
}
@Override
public long getEstimatedCardinality(int inElements) {
return 100;
}
}
| true | true | public JValue evaluate(Graph graph,
AbstractGraphMarker<AttributedElement> subgraph, JValue[] arguments)
throws EvaluateException {
switch (checkArguments(arguments)) {
case 0:
return new JValueImpl(graph.getLastEdge());
case 1:
Edge current = graph.getLastEdge();
JValueTypeCollection tc = arguments[2].toJValueTypeCollection();
while (current != null) {
if (tc.acceptsType(current.getAttributedElementClass())) {
return new JValueImpl(current);
}
current = current.getPrevEdge();
}
return new JValueImpl((Edge) null);
default:
throw new WrongFunctionParameterException(this, arguments);
}
}
| public JValue evaluate(Graph graph,
AbstractGraphMarker<AttributedElement> subgraph, JValue[] arguments)
throws EvaluateException {
switch (checkArguments(arguments)) {
case 0:
return new JValueImpl(graph.getLastEdge());
case 1:
Edge current = graph.getLastEdge();
JValueTypeCollection tc = arguments[0].toJValueTypeCollection();
while (current != null) {
if (tc.acceptsType(current.getAttributedElementClass())) {
return new JValueImpl(current);
}
current = current.getPrevEdge();
}
return new JValueImpl((Edge) null);
default:
throw new WrongFunctionParameterException(this, arguments);
}
}
|
diff --git a/src/org/nutz/mvc/upload/FastUploading.java b/src/org/nutz/mvc/upload/FastUploading.java
index 6686d6070..67f95f720 100644
--- a/src/org/nutz/mvc/upload/FastUploading.java
+++ b/src/org/nutz/mvc/upload/FastUploading.java
@@ -1,195 +1,196 @@
package org.nutz.mvc.upload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import org.nutz.filepool.FilePool;
import org.nutz.http.Http;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.nutz.lang.Strings;
import org.nutz.lang.stream.StreamBuffer;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.upload.util.BufferRing;
import org.nutz.mvc.upload.util.MarkMode;
import org.nutz.mvc.upload.util.RemountBytes;
/**
* 采用成块写入的方式,这个逻辑比 SimpleUploading 大约快了 1 倍
*
* @author zozoh([email protected])
*/
public class FastUploading implements Uploading {
private static Log log = Logs.getLog(FastUploading.class);
/**
* 缓冲环的节点宽度,推荐 8192
*/
private int bufferSize;
public FastUploading(int bufferSize) {
this.bufferSize = bufferSize;
}
public Map<String, Object> parse(HttpServletRequest req, String charset, FilePool tmps)
throws UploadException {
if (log.isDebugEnabled())
log.debug("FastUpload : " + Mvcs.getRequestPath(req));
/*
* 创建进度对象
*/
UploadInfo info = Uploads.createInfo(req);
if (log.isDebugEnabled())
log.debug("info created");
/*
* 创建参数表
*/
NutMap params = Uploads.createParamsMap(req);
if (log.isDebugEnabled())
log.debugf("Params map created - %d params", params.size());
/*
* 解析边界
*/
String firstBoundary = "--" + Http.multipart.getBoundary(req.getContentType());
RemountBytes firstBoundaryBytes = RemountBytes.create(firstBoundary);
String itemEndl = "\r\n--" + Http.multipart.getBoundary(req.getContentType());
RemountBytes itemEndlBytes = RemountBytes.create(itemEndl);
RemountBytes nameEndlBytes = RemountBytes.create("\r\n\r\n");
if (log.isDebugEnabled())
log.debug("boundary: " + itemEndl);
/*
* 准备缓冲环,并跳过开始标记
*/
MarkMode mm;
BufferRing br;
try {
ServletInputStream ins = req.getInputStream();
// 构建 3 个环节点的缓冲环
br = new BufferRing(ins, 3, bufferSize);
// 初始加载
info.current = br.load();
// 跳过开始的标记
mm = br.mark(firstBoundaryBytes);
// 这是不可能的,应该立即退出
if (mm != MarkMode.FOUND) {
if (log.isWarnEnabled())
log.warnf("Fail to find the firstBoundary (%s) in stream, quit!", firstBoundary);
return params;
}
br.skipMark();
if (log.isDebugEnabled())
log.debug("skip first boundary");
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
/**
* ========================================================<br>
* 进入循环
*/
if (log.isDebugEnabled())
log.debug("Reading...");
try {
FieldMeta meta;
do {
info.current = br.load();
// 标记项目头
mm = br.mark(nameEndlBytes);
String s = br.dumpAsString(charset);
// 肯定碰到了 "--\r\n", 这标志着整个流结束了
if ("--".equals(s) || MarkMode.STREAM_END == mm) {
break;
}
// 找到头的结束标志
else if (MarkMode.FOUND == mm) {
meta = new FieldMeta(s);
}
// 这是不可能的,抛错
else {
throw new UploadInvalidFormatException("Fail to found nameEnd!");
}
// 作为文件读取
if (meta.isFile()) {
// 上传的是一个空文件
if (Strings.isBlank(meta.getFileLocalPath())) {
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.skipMark();
} while (mm == MarkMode.NOT_FOUND);
}
// 保存临时文件
else {
File tmp = tmps.createFile(meta.getFileExtension());
OutputStream ops = null;
try {
ops = new BufferedOutputStream( new FileOutputStream(tmp),
bufferSize * 2);
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.dump(ops);
} while (mm == MarkMode.NOT_FOUND);
}
finally {
Streams.safeClose(ops);
}
params.add(meta.getName(), new TempFile(meta, tmp));
}
}
// 作为提交值读取
else {
- StreamBuffer sb = new StreamBuffer();
+ // StreamBuffer sb = new StreamBuffer();
+ StringBuilder sb = new StringBuilder();
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
- br.dump(sb.getBuffer());
+ sb.append(br.dumpAsString(charset));
} while (mm == MarkMode.NOT_FOUND);
- params.add(meta.getName(), sb.toString(charset));
+ params.add(meta.getName(), sb.toString());
}
} while (mm != MarkMode.STREAM_END);
}
// 处理异常
catch (Exception e) {
throw Lang.wrapThrow(e, UploadException.class);
}
// 安全关闭输入流
finally {
br.close();
}
if (log.isDebugEnabled())
log.debugf("...Done %dbyted readed", br.readed());
/**
* 全部结束<br>
* ========================================================
*/
return params;
}
private static void assertStreamNotEnd(MarkMode mm) throws UploadInvalidFormatException {
if (mm == MarkMode.STREAM_END)
throw new UploadInvalidFormatException("Should not end stream");
}
}
| false | true | public Map<String, Object> parse(HttpServletRequest req, String charset, FilePool tmps)
throws UploadException {
if (log.isDebugEnabled())
log.debug("FastUpload : " + Mvcs.getRequestPath(req));
/*
* 创建进度对象
*/
UploadInfo info = Uploads.createInfo(req);
if (log.isDebugEnabled())
log.debug("info created");
/*
* 创建参数表
*/
NutMap params = Uploads.createParamsMap(req);
if (log.isDebugEnabled())
log.debugf("Params map created - %d params", params.size());
/*
* 解析边界
*/
String firstBoundary = "--" + Http.multipart.getBoundary(req.getContentType());
RemountBytes firstBoundaryBytes = RemountBytes.create(firstBoundary);
String itemEndl = "\r\n--" + Http.multipart.getBoundary(req.getContentType());
RemountBytes itemEndlBytes = RemountBytes.create(itemEndl);
RemountBytes nameEndlBytes = RemountBytes.create("\r\n\r\n");
if (log.isDebugEnabled())
log.debug("boundary: " + itemEndl);
/*
* 准备缓冲环,并跳过开始标记
*/
MarkMode mm;
BufferRing br;
try {
ServletInputStream ins = req.getInputStream();
// 构建 3 个环节点的缓冲环
br = new BufferRing(ins, 3, bufferSize);
// 初始加载
info.current = br.load();
// 跳过开始的标记
mm = br.mark(firstBoundaryBytes);
// 这是不可能的,应该立即退出
if (mm != MarkMode.FOUND) {
if (log.isWarnEnabled())
log.warnf("Fail to find the firstBoundary (%s) in stream, quit!", firstBoundary);
return params;
}
br.skipMark();
if (log.isDebugEnabled())
log.debug("skip first boundary");
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
/**
* ========================================================<br>
* 进入循环
*/
if (log.isDebugEnabled())
log.debug("Reading...");
try {
FieldMeta meta;
do {
info.current = br.load();
// 标记项目头
mm = br.mark(nameEndlBytes);
String s = br.dumpAsString(charset);
// 肯定碰到了 "--\r\n", 这标志着整个流结束了
if ("--".equals(s) || MarkMode.STREAM_END == mm) {
break;
}
// 找到头的结束标志
else if (MarkMode.FOUND == mm) {
meta = new FieldMeta(s);
}
// 这是不可能的,抛错
else {
throw new UploadInvalidFormatException("Fail to found nameEnd!");
}
// 作为文件读取
if (meta.isFile()) {
// 上传的是一个空文件
if (Strings.isBlank(meta.getFileLocalPath())) {
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.skipMark();
} while (mm == MarkMode.NOT_FOUND);
}
// 保存临时文件
else {
File tmp = tmps.createFile(meta.getFileExtension());
OutputStream ops = null;
try {
ops = new BufferedOutputStream( new FileOutputStream(tmp),
bufferSize * 2);
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.dump(ops);
} while (mm == MarkMode.NOT_FOUND);
}
finally {
Streams.safeClose(ops);
}
params.add(meta.getName(), new TempFile(meta, tmp));
}
}
// 作为提交值读取
else {
StreamBuffer sb = new StreamBuffer();
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.dump(sb.getBuffer());
} while (mm == MarkMode.NOT_FOUND);
params.add(meta.getName(), sb.toString(charset));
}
} while (mm != MarkMode.STREAM_END);
}
// 处理异常
catch (Exception e) {
throw Lang.wrapThrow(e, UploadException.class);
}
// 安全关闭输入流
finally {
br.close();
}
if (log.isDebugEnabled())
log.debugf("...Done %dbyted readed", br.readed());
/**
* 全部结束<br>
* ========================================================
*/
return params;
}
| public Map<String, Object> parse(HttpServletRequest req, String charset, FilePool tmps)
throws UploadException {
if (log.isDebugEnabled())
log.debug("FastUpload : " + Mvcs.getRequestPath(req));
/*
* 创建进度对象
*/
UploadInfo info = Uploads.createInfo(req);
if (log.isDebugEnabled())
log.debug("info created");
/*
* 创建参数表
*/
NutMap params = Uploads.createParamsMap(req);
if (log.isDebugEnabled())
log.debugf("Params map created - %d params", params.size());
/*
* 解析边界
*/
String firstBoundary = "--" + Http.multipart.getBoundary(req.getContentType());
RemountBytes firstBoundaryBytes = RemountBytes.create(firstBoundary);
String itemEndl = "\r\n--" + Http.multipart.getBoundary(req.getContentType());
RemountBytes itemEndlBytes = RemountBytes.create(itemEndl);
RemountBytes nameEndlBytes = RemountBytes.create("\r\n\r\n");
if (log.isDebugEnabled())
log.debug("boundary: " + itemEndl);
/*
* 准备缓冲环,并跳过开始标记
*/
MarkMode mm;
BufferRing br;
try {
ServletInputStream ins = req.getInputStream();
// 构建 3 个环节点的缓冲环
br = new BufferRing(ins, 3, bufferSize);
// 初始加载
info.current = br.load();
// 跳过开始的标记
mm = br.mark(firstBoundaryBytes);
// 这是不可能的,应该立即退出
if (mm != MarkMode.FOUND) {
if (log.isWarnEnabled())
log.warnf("Fail to find the firstBoundary (%s) in stream, quit!", firstBoundary);
return params;
}
br.skipMark();
if (log.isDebugEnabled())
log.debug("skip first boundary");
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
/**
* ========================================================<br>
* 进入循环
*/
if (log.isDebugEnabled())
log.debug("Reading...");
try {
FieldMeta meta;
do {
info.current = br.load();
// 标记项目头
mm = br.mark(nameEndlBytes);
String s = br.dumpAsString(charset);
// 肯定碰到了 "--\r\n", 这标志着整个流结束了
if ("--".equals(s) || MarkMode.STREAM_END == mm) {
break;
}
// 找到头的结束标志
else if (MarkMode.FOUND == mm) {
meta = new FieldMeta(s);
}
// 这是不可能的,抛错
else {
throw new UploadInvalidFormatException("Fail to found nameEnd!");
}
// 作为文件读取
if (meta.isFile()) {
// 上传的是一个空文件
if (Strings.isBlank(meta.getFileLocalPath())) {
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.skipMark();
} while (mm == MarkMode.NOT_FOUND);
}
// 保存临时文件
else {
File tmp = tmps.createFile(meta.getFileExtension());
OutputStream ops = null;
try {
ops = new BufferedOutputStream( new FileOutputStream(tmp),
bufferSize * 2);
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
br.dump(ops);
} while (mm == MarkMode.NOT_FOUND);
}
finally {
Streams.safeClose(ops);
}
params.add(meta.getName(), new TempFile(meta, tmp));
}
}
// 作为提交值读取
else {
// StreamBuffer sb = new StreamBuffer();
StringBuilder sb = new StringBuilder();
do {
info.current = br.load();
mm = br.mark(itemEndlBytes);
assertStreamNotEnd(mm);
sb.append(br.dumpAsString(charset));
} while (mm == MarkMode.NOT_FOUND);
params.add(meta.getName(), sb.toString());
}
} while (mm != MarkMode.STREAM_END);
}
// 处理异常
catch (Exception e) {
throw Lang.wrapThrow(e, UploadException.class);
}
// 安全关闭输入流
finally {
br.close();
}
if (log.isDebugEnabled())
log.debugf("...Done %dbyted readed", br.readed());
/**
* 全部结束<br>
* ========================================================
*/
return params;
}
|
diff --git a/src/pt/webdetails/cda/exporter/AbstractExporter.java b/src/pt/webdetails/cda/exporter/AbstractExporter.java
index aaf941cb..df978787 100644
--- a/src/pt/webdetails/cda/exporter/AbstractExporter.java
+++ b/src/pt/webdetails/cda/exporter/AbstractExporter.java
@@ -1,55 +1,55 @@
package pt.webdetails.cda.exporter;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;
import javax.swing.table.TableModel;
/**
* Created by IntelliJ IDEA.
* User: pedro
* Date: Feb 5, 2010
* Time: 5:06:31 PM
*/
public abstract class AbstractExporter implements Exporter
{
public abstract void export(final OutputStream out, final TableModel tableModel) throws ExporterException;
public abstract String getMimeType();
protected String getColType(final Class<?> columnClass) throws ExporterException
{
if (columnClass.equals(String.class))
{
return "String";
}
- else if (columnClass.equals(Integer.class))
+ else if (columnClass.equals(Integer.class) || columnClass.equals(Short.class))
{
return "Integer";
}
else if (columnClass.equals(Number.class) || columnClass.equals(Long.class) || columnClass.equals(Double.class) || columnClass.equals(Float.class) )
{
return "Numeric";
}
else if (columnClass.equals(Date.class) || columnClass.equals(java.sql.Date.class) || columnClass.equals(Timestamp.class) )
{
return "Date";
}
else if (columnClass.equals(Object.class) )
{
// todo: Quick and dirty hack, as the formula never knows what type is returned.
return "String";
}
else{
throw new ExporterException("Unknown class: " + columnClass.toString(), null);
}
}
}
| true | true | protected String getColType(final Class<?> columnClass) throws ExporterException
{
if (columnClass.equals(String.class))
{
return "String";
}
else if (columnClass.equals(Integer.class))
{
return "Integer";
}
else if (columnClass.equals(Number.class) || columnClass.equals(Long.class) || columnClass.equals(Double.class) || columnClass.equals(Float.class) )
{
return "Numeric";
}
else if (columnClass.equals(Date.class) || columnClass.equals(java.sql.Date.class) || columnClass.equals(Timestamp.class) )
{
return "Date";
}
else if (columnClass.equals(Object.class) )
{
// todo: Quick and dirty hack, as the formula never knows what type is returned.
return "String";
}
else{
throw new ExporterException("Unknown class: " + columnClass.toString(), null);
}
}
| protected String getColType(final Class<?> columnClass) throws ExporterException
{
if (columnClass.equals(String.class))
{
return "String";
}
else if (columnClass.equals(Integer.class) || columnClass.equals(Short.class))
{
return "Integer";
}
else if (columnClass.equals(Number.class) || columnClass.equals(Long.class) || columnClass.equals(Double.class) || columnClass.equals(Float.class) )
{
return "Numeric";
}
else if (columnClass.equals(Date.class) || columnClass.equals(java.sql.Date.class) || columnClass.equals(Timestamp.class) )
{
return "Date";
}
else if (columnClass.equals(Object.class) )
{
// todo: Quick and dirty hack, as the formula never knows what type is returned.
return "String";
}
else{
throw new ExporterException("Unknown class: " + columnClass.toString(), null);
}
}
|
diff --git a/src/main/java/ru/urbancamper/audiobookmarker/text/LongestSubsequenceFinder.java b/src/main/java/ru/urbancamper/audiobookmarker/text/LongestSubsequenceFinder.java
index add3ae6..999d6b6 100644
--- a/src/main/java/ru/urbancamper/audiobookmarker/text/LongestSubsequenceFinder.java
+++ b/src/main/java/ru/urbancamper/audiobookmarker/text/LongestSubsequenceFinder.java
@@ -1,126 +1,126 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ru.urbancamper.audiobookmarker.text;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author pozpl
*/
public class LongestSubsequenceFinder {
private static final Integer WORDS_INTERVAL_THRESHHOLD = 3;
private TreeMap<Integer, Integer> findLogestSubsequence(Integer[] fullArray,
Integer[] subArray) {
int[][] lengths = new int[fullArray.length + 1][subArray.length + 1];
int[] fullArrayIndexesOfSameWords = new int[subArray.length + 1];
// row 0 and column 0 are initialized to 0 already
for (int i = 0; i < fullArray.length; i++) {
for (int j = 0; j < subArray.length; j++) {
if (fullArray[i] == subArray[j] &&
- this.isWodsBelongToInterval(fullArrayIndexesOfSameWords, i, j)) {
+ this.isWodsBelongToInterval(fullArrayIndexesOfSameWords, j, i)) {
lengths[i + 1][j + 1] = lengths[i][j] + 1;
fullArrayIndexesOfSameWords[j] = i;
} else {
lengths[i + 1][j + 1] =
Math.max(lengths[i + 1][j], lengths[i][j + 1]);
}
}
}
// read the substring out from the matrix
// StringBuffer sb = new StringBuffer();
TreeMap<Integer, Integer> resultBuffer = new TreeMap<Integer, Integer>();
for (int x = fullArray.length, y = subArray.length;
x != 0 && y != 0;) {
if (lengths[x][y] == lengths[x - 1][y]) {
x--;
} else if (lengths[x][y] == lengths[x][y - 1]) {
y--;
} else {
assert fullArray[x - 1] == subArray[y - 1];
// sb.append(a.get(x - 1));
resultBuffer.put(x-1, y-1);
x--;
y--;
}
}
return resultBuffer;
}
/**
* function to decide if words is close enough to be in same sequence
* @param longestSequenceWordsOffsets array of word offsets tat matched
* @param fullArrayIndex
* @param subArrayIndex
* @return decigion if words is close enough
*/
private Boolean isWodsBelongToInterval(int[] longestSequenceWordsOffsets, int fullArrayIndex, int subArrayIndex){
if(subArrayIndex == 0){
return true;
}
Integer subArrayWordsCounter = 0;
for(Integer wordsLengthsIndex = subArrayIndex -1; wordsLengthsIndex >= 0; wordsLengthsIndex--){
int subArrayWordOffset = longestSequenceWordsOffsets[wordsLengthsIndex];
int wordsDistance = fullArrayIndex - subArrayWordOffset;
if(wordsDistance > 0 && wordsDistance - subArrayWordsCounter < WORDS_INTERVAL_THRESHHOLD){
return true;
}
}
return false;
}
public TreeMap<Integer, Integer> getLongestSubsequenceWithMinDistance(
Integer[] fullArray,
Integer[] subArray){
TreeMap<Integer, Integer> longestSubsequence = this.findLogestSubsequence(fullArray, subArray);
Integer previousFullTextIndex = 0;
Integer previousFullTextElement = -1;
ArrayList<Integer> fullTextBuffer = new ArrayList<Integer>();
ArrayList<Integer> subTextBuffer = new ArrayList<Integer>();
Integer entriesCounter = 0;
for(Map.Entry<Integer, Integer> fullTextToRecTextMapEntry: longestSubsequence.entrySet()){
Integer fullTextWordIndex = fullTextToRecTextMapEntry.getKey();
Integer subTextWordIndex = fullTextToRecTextMapEntry.getValue();
fullTextBuffer.add(fullTextWordIndex);
subTextBuffer.add(subTextWordIndex);
Integer currentFullTextElement = fullArray[fullTextWordIndex];
for(Integer spanCounter = previousFullTextIndex + 1; spanCounter < fullTextWordIndex; spanCounter++){
Integer elementlToCheck = fullArray[spanCounter];
if(elementlToCheck == previousFullTextElement){
fullTextBuffer.set(previousFullTextIndex, spanCounter);
}
}
previousFullTextElement = currentFullTextElement;
previousFullTextIndex = entriesCounter;
entriesCounter++;
}
return this.getFullTextSubTextTreeMapFromLists(fullTextBuffer, subTextBuffer);
}
private TreeMap<Integer, Integer> getFullTextSubTextTreeMapFromLists(ArrayList<Integer> fullTextBuffer,
ArrayList<Integer> subTextBuffer){
TreeMap<Integer, Integer> resultBuffer = new TreeMap<Integer, Integer>();
for(Integer elementCounter = 0; elementCounter < fullTextBuffer.size(); elementCounter++){
resultBuffer.put(fullTextBuffer.get(elementCounter), subTextBuffer.get(elementCounter));
}
return resultBuffer;
}
}
| true | true | private TreeMap<Integer, Integer> findLogestSubsequence(Integer[] fullArray,
Integer[] subArray) {
int[][] lengths = new int[fullArray.length + 1][subArray.length + 1];
int[] fullArrayIndexesOfSameWords = new int[subArray.length + 1];
// row 0 and column 0 are initialized to 0 already
for (int i = 0; i < fullArray.length; i++) {
for (int j = 0; j < subArray.length; j++) {
if (fullArray[i] == subArray[j] &&
this.isWodsBelongToInterval(fullArrayIndexesOfSameWords, i, j)) {
lengths[i + 1][j + 1] = lengths[i][j] + 1;
fullArrayIndexesOfSameWords[j] = i;
} else {
lengths[i + 1][j + 1] =
Math.max(lengths[i + 1][j], lengths[i][j + 1]);
}
}
}
// read the substring out from the matrix
// StringBuffer sb = new StringBuffer();
TreeMap<Integer, Integer> resultBuffer = new TreeMap<Integer, Integer>();
for (int x = fullArray.length, y = subArray.length;
x != 0 && y != 0;) {
if (lengths[x][y] == lengths[x - 1][y]) {
x--;
} else if (lengths[x][y] == lengths[x][y - 1]) {
y--;
} else {
assert fullArray[x - 1] == subArray[y - 1];
// sb.append(a.get(x - 1));
resultBuffer.put(x-1, y-1);
x--;
y--;
}
}
return resultBuffer;
}
| private TreeMap<Integer, Integer> findLogestSubsequence(Integer[] fullArray,
Integer[] subArray) {
int[][] lengths = new int[fullArray.length + 1][subArray.length + 1];
int[] fullArrayIndexesOfSameWords = new int[subArray.length + 1];
// row 0 and column 0 are initialized to 0 already
for (int i = 0; i < fullArray.length; i++) {
for (int j = 0; j < subArray.length; j++) {
if (fullArray[i] == subArray[j] &&
this.isWodsBelongToInterval(fullArrayIndexesOfSameWords, j, i)) {
lengths[i + 1][j + 1] = lengths[i][j] + 1;
fullArrayIndexesOfSameWords[j] = i;
} else {
lengths[i + 1][j + 1] =
Math.max(lengths[i + 1][j], lengths[i][j + 1]);
}
}
}
// read the substring out from the matrix
// StringBuffer sb = new StringBuffer();
TreeMap<Integer, Integer> resultBuffer = new TreeMap<Integer, Integer>();
for (int x = fullArray.length, y = subArray.length;
x != 0 && y != 0;) {
if (lengths[x][y] == lengths[x - 1][y]) {
x--;
} else if (lengths[x][y] == lengths[x][y - 1]) {
y--;
} else {
assert fullArray[x - 1] == subArray[y - 1];
// sb.append(a.get(x - 1));
resultBuffer.put(x-1, y-1);
x--;
y--;
}
}
return resultBuffer;
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/UpdateStockPane.java b/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/UpdateStockPane.java
index ac73bcb5..440b367b 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/UpdateStockPane.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/stock/panes/UpdateStockPane.java
@@ -1,178 +1,178 @@
package devopsdistilled.operp.client.stock.panes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
import javax.inject.Inject;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import devopsdistilled.operp.client.abstracts.SubTaskPane;
import devopsdistilled.operp.client.exceptions.EntityValidationException;
import devopsdistilled.operp.client.items.controllers.ItemController;
import devopsdistilled.operp.client.items.models.observers.ItemModelObserver;
import devopsdistilled.operp.client.stock.controllers.WarehouseController;
import devopsdistilled.operp.client.stock.models.observers.WarehouseModelObserver;
import devopsdistilled.operp.client.stock.panes.controllers.UpdateStockPaneController;
import devopsdistilled.operp.client.stock.panes.models.observers.UpdateStockPaneModelObserver;
import devopsdistilled.operp.server.data.entity.items.Item;
import devopsdistilled.operp.server.data.entity.stock.Warehouse;
public class UpdateStockPane extends SubTaskPane implements
UpdateStockPaneModelObserver, ItemModelObserver, WarehouseModelObserver {
@Inject
private UpdateStockPaneController controller;
@Inject
private WarehouseController warehouseController;
@Inject
private ItemController itemController;
private final JPanel pane;
private final JTextField quantityField;
private final JComboBox<Item> comboItems;
private final JComboBox<Warehouse> comboWarehouses;
public UpdateStockPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[]25[grow]", "[][][][][]"));
JLabel lblItemName = new JLabel("Item Name");
pane.add(lblItemName, "cell 0 0,alignx trailing");
comboItems = new JComboBox<Item>();
comboItems.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
controller.getModel().setItem((Item) e.getItem());
}
});
- comboItems.setSelectedItem(controller.getModel().getItem());
+ comboItems.setSelectedItem(null);
pane.add(comboItems, "flowx,split 2,cell 1 0,growx");
JButton btnNewItem = new JButton("New Item");
btnNewItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
itemController.create();
}
});
pane.add(btnNewItem, "cell 1 0");
JLabel lblWarehouseName = new JLabel("Warehouse Name");
pane.add(lblWarehouseName, "cell 0 1,alignx trailing");
comboWarehouses = new JComboBox<Warehouse>();
comboWarehouses.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
controller.getModel().setWarehouse((Warehouse) e.getItem());
}
});
- comboWarehouses.setSelectedItem(controller.getModel().getWarehouse());
+ comboWarehouses.setSelectedItem(null);
pane.add(comboWarehouses, "flowx,split 2,cell 1 1,growx");
JButton btnNewWarehouse = new JButton("New Warehouse");
btnNewWarehouse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
warehouseController.create();
}
});
pane.add(btnNewWarehouse, "cell 1 1");
JLabel lblQuantity = new JLabel("Quantity");
pane.add(lblQuantity, "cell 0 2,alignx trailing");
quantityField = new JTextField();
quantityField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Long quantity = Long.parseLong(quantityField.getText()
.trim());
controller.getModel().setQuantity(quantity);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(getPane(),
"Quantity field must be numeric value");
}
}
});
pane.add(quantityField, "cell 1 2,growx");
quantityField.setColumns(15);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
}
});
pane.add(btnCancel, "flowx,split 3,cell 1 4");
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
controller.validate();
controller.save();
getDialog().dispose();
} catch (EntityValidationException e1) {
JOptionPane.showMessageDialog(getPane(), e1.getMessage());
}
}
});
pane.add(btnUpdate, "cell 1 4");
}
@Override
public JComponent getPane() {
return pane;
}
@Override
public void updateItems(List<Item> items) {
Item prevSelected = (Item) comboItems.getSelectedItem();
comboItems.removeAllItems();
for (Item item : items) {
comboItems.addItem(item);
if (prevSelected != null)
if (prevSelected.compareTo(item) == 0)
comboItems.setSelectedItem(item);
}
}
@Override
public void updateWarehouses(List<Warehouse> warehouses) {
Warehouse prevSelected = (Warehouse) comboWarehouses.getSelectedItem();
comboWarehouses.removeAllItems();
for (Warehouse warehouse : warehouses) {
comboWarehouses.addItem(warehouse);
if (prevSelected != null)
if (prevSelected.compareTo(warehouse) == 0)
comboWarehouses.setSelectedItem(warehouse);
}
}
}
| false | true | public UpdateStockPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[]25[grow]", "[][][][][]"));
JLabel lblItemName = new JLabel("Item Name");
pane.add(lblItemName, "cell 0 0,alignx trailing");
comboItems = new JComboBox<Item>();
comboItems.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
controller.getModel().setItem((Item) e.getItem());
}
});
comboItems.setSelectedItem(controller.getModel().getItem());
pane.add(comboItems, "flowx,split 2,cell 1 0,growx");
JButton btnNewItem = new JButton("New Item");
btnNewItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
itemController.create();
}
});
pane.add(btnNewItem, "cell 1 0");
JLabel lblWarehouseName = new JLabel("Warehouse Name");
pane.add(lblWarehouseName, "cell 0 1,alignx trailing");
comboWarehouses = new JComboBox<Warehouse>();
comboWarehouses.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
controller.getModel().setWarehouse((Warehouse) e.getItem());
}
});
comboWarehouses.setSelectedItem(controller.getModel().getWarehouse());
pane.add(comboWarehouses, "flowx,split 2,cell 1 1,growx");
JButton btnNewWarehouse = new JButton("New Warehouse");
btnNewWarehouse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
warehouseController.create();
}
});
pane.add(btnNewWarehouse, "cell 1 1");
JLabel lblQuantity = new JLabel("Quantity");
pane.add(lblQuantity, "cell 0 2,alignx trailing");
quantityField = new JTextField();
quantityField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Long quantity = Long.parseLong(quantityField.getText()
.trim());
controller.getModel().setQuantity(quantity);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(getPane(),
"Quantity field must be numeric value");
}
}
});
pane.add(quantityField, "cell 1 2,growx");
quantityField.setColumns(15);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
}
});
pane.add(btnCancel, "flowx,split 3,cell 1 4");
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
controller.validate();
controller.save();
getDialog().dispose();
} catch (EntityValidationException e1) {
JOptionPane.showMessageDialog(getPane(), e1.getMessage());
}
}
});
pane.add(btnUpdate, "cell 1 4");
}
| public UpdateStockPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[]25[grow]", "[][][][][]"));
JLabel lblItemName = new JLabel("Item Name");
pane.add(lblItemName, "cell 0 0,alignx trailing");
comboItems = new JComboBox<Item>();
comboItems.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
controller.getModel().setItem((Item) e.getItem());
}
});
comboItems.setSelectedItem(null);
pane.add(comboItems, "flowx,split 2,cell 1 0,growx");
JButton btnNewItem = new JButton("New Item");
btnNewItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
itemController.create();
}
});
pane.add(btnNewItem, "cell 1 0");
JLabel lblWarehouseName = new JLabel("Warehouse Name");
pane.add(lblWarehouseName, "cell 0 1,alignx trailing");
comboWarehouses = new JComboBox<Warehouse>();
comboWarehouses.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
controller.getModel().setWarehouse((Warehouse) e.getItem());
}
});
comboWarehouses.setSelectedItem(null);
pane.add(comboWarehouses, "flowx,split 2,cell 1 1,growx");
JButton btnNewWarehouse = new JButton("New Warehouse");
btnNewWarehouse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
warehouseController.create();
}
});
pane.add(btnNewWarehouse, "cell 1 1");
JLabel lblQuantity = new JLabel("Quantity");
pane.add(lblQuantity, "cell 0 2,alignx trailing");
quantityField = new JTextField();
quantityField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Long quantity = Long.parseLong(quantityField.getText()
.trim());
controller.getModel().setQuantity(quantity);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(getPane(),
"Quantity field must be numeric value");
}
}
});
pane.add(quantityField, "cell 1 2,growx");
quantityField.setColumns(15);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getDialog().dispose();
}
});
pane.add(btnCancel, "flowx,split 3,cell 1 4");
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
controller.validate();
controller.save();
getDialog().dispose();
} catch (EntityValidationException e1) {
JOptionPane.showMessageDialog(getPane(), e1.getMessage());
}
}
});
pane.add(btnUpdate, "cell 1 4");
}
|
diff --git a/src/main/java/org/apache/flume/sink/hbase/SimpleAsyncHbaseEventSerializer.java b/src/main/java/org/apache/flume/sink/hbase/SimpleAsyncHbaseEventSerializer.java
index 03676c5..9d955be 100644
--- a/src/main/java/org/apache/flume/sink/hbase/SimpleAsyncHbaseEventSerializer.java
+++ b/src/main/java/org/apache/flume/sink/hbase/SimpleAsyncHbaseEventSerializer.java
@@ -1,168 +1,168 @@
/*
* 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.flume.sink.hbase;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.FlumeException;
import org.hbase.async.AtomicIncrementRequest;
import org.hbase.async.PutRequest;
import org.apache.flume.conf.ComponentConfiguration;
import org.apache.flume.sink.hbase.SimpleHbaseEventSerializer.KeyType;
import com.google.common.base.Charsets;
/**
* A simple serializer to be used with the AsyncHBaseSink
* that returns puts from an event, by writing the event
* body into it. The headers are discarded. It also updates a row in hbase
* which acts as an event counter.
*
* Takes optional parameters:<p>
* <tt>rowPrefix:</tt> The prefix to be used. Default: <i>default</i><p>
* <tt>incrementRow</tt> The row to increment. Default: <i>incRow</i><p>
* <tt>suffix:</tt> <i>uuid/random/timestamp.</i>Default: <i>uuid</i><p>
*
* Mandatory parameters: <p>
* <tt>cf:</tt>Column family.<p>
* Components that have no defaults and will not be used if absent:
* <tt>payloadColumn:</tt> Which column to put payload in. If it is not present,
* event data will not be written.<p>
* <tt>incrementColumn:</tt> Which column to increment. If this is absent, it
* means no column is incremented.
*/
public class SimpleAsyncHbaseEventSerializer implements AsyncHbaseEventSerializer {
private byte[] table;
private byte[] cf;
private byte[] payload;
private byte[] payloadColumn;
private byte[] incrementColumn;
private String rowPrefix;
private byte[] incrementRow;
private KeyType keyType;
// 20130521, leoricklin
private Event hbevent;
@Override
public void initialize(byte[] table, byte[] cf) {
this.table = table;
this.cf = cf;
}
@Override
public List<PutRequest> getActions() {
List<PutRequest> actions = new ArrayList<PutRequest>();
if(payloadColumn != null){
byte[] rowKey;
String srchost = (hbevent.getHeaders().containsKey("host"))?(hbevent.getHeaders().get("host")):("");
- rowPrefix = rowPrefix + srchost + "-";
+ String rowPrefixHost = rowPrefix + srchost + "-";
try {
switch (keyType) {
case TS:
- rowKey = SimpleRowKeyGenerator.getTimestampKey(rowPrefix);
+ rowKey = SimpleRowKeyGenerator.getTimestampKey(rowPrefixHost);
break;
case TSNANO:
- rowKey = SimpleRowKeyGenerator.getNanoTimestampKey(rowPrefix);
+ rowKey = SimpleRowKeyGenerator.getNanoTimestampKey(rowPrefixHost);
break;
case RANDOM:
- rowKey = SimpleRowKeyGenerator.getRandomKey(rowPrefix);
+ rowKey = SimpleRowKeyGenerator.getRandomKey(rowPrefixHost);
break;
default:
- rowKey = SimpleRowKeyGenerator.getUUIDKey(rowPrefix);
+ rowKey = SimpleRowKeyGenerator.getUUIDKey(rowPrefixHost);
break;
}
PutRequest putRequest;
// Event Headers
for (Map.Entry<String, String> entry : hbevent.getHeaders().entrySet()) {
if (entry.getKey() != null) {
putRequest = new PutRequest(table, rowKey, cf, entry.getKey().getBytes(), entry.getValue().getBytes());
actions.add(putRequest);
}
}
// Event Body
putRequest = new PutRequest(table, rowKey, cf, payloadColumn, payload);
actions.add(putRequest);
} catch (Exception e){
throw new FlumeException("Could not get row key!", e);
}
}
return actions;
}
public List<AtomicIncrementRequest> getIncrements(){
List<AtomicIncrementRequest> actions = new
ArrayList<AtomicIncrementRequest>();
if(incrementColumn != null) {
AtomicIncrementRequest inc = new AtomicIncrementRequest(table,
incrementRow, cf, incrementColumn);
actions.add(inc);
}
return actions;
}
@Override
public void cleanUp() {
// TODO Auto-generated method stub
}
@Override
public void configure(Context context) {
String pCol = context.getString("payloadColumn");
String iCol = context.getString("incrementColumn");
rowPrefix = context.getString("rowPrefix", "default");
String suffix = context.getString("suffix", "uuid");
if(pCol != null && !pCol.isEmpty()) {
if(suffix.equals("timestamp")){
keyType = KeyType.TS;
} else if (suffix.equals("random")) {
keyType = KeyType.RANDOM;
} else if(suffix.equals("nano")){
keyType = KeyType.TSNANO;
} else {
keyType = KeyType.UUID;
}
payloadColumn = pCol.getBytes(Charsets.UTF_8);
}
if(iCol != null && !iCol.isEmpty()) {
incrementColumn = iCol.getBytes(Charsets.UTF_8);
}
incrementRow =
context.getString("incrementRow", "incRow").getBytes(Charsets.UTF_8);
}
@Override
public void setEvent(Event event) {
this.hbevent = event;
this.payload = event.getBody();
}
public byte[] getPayload() {
return this.payload;
}
@Override
public void configure(ComponentConfiguration conf) {
// TODO Auto-generated method stub
}
}
| false | true | public List<PutRequest> getActions() {
List<PutRequest> actions = new ArrayList<PutRequest>();
if(payloadColumn != null){
byte[] rowKey;
String srchost = (hbevent.getHeaders().containsKey("host"))?(hbevent.getHeaders().get("host")):("");
rowPrefix = rowPrefix + srchost + "-";
try {
switch (keyType) {
case TS:
rowKey = SimpleRowKeyGenerator.getTimestampKey(rowPrefix);
break;
case TSNANO:
rowKey = SimpleRowKeyGenerator.getNanoTimestampKey(rowPrefix);
break;
case RANDOM:
rowKey = SimpleRowKeyGenerator.getRandomKey(rowPrefix);
break;
default:
rowKey = SimpleRowKeyGenerator.getUUIDKey(rowPrefix);
break;
}
PutRequest putRequest;
// Event Headers
for (Map.Entry<String, String> entry : hbevent.getHeaders().entrySet()) {
if (entry.getKey() != null) {
putRequest = new PutRequest(table, rowKey, cf, entry.getKey().getBytes(), entry.getValue().getBytes());
actions.add(putRequest);
}
}
// Event Body
putRequest = new PutRequest(table, rowKey, cf, payloadColumn, payload);
actions.add(putRequest);
} catch (Exception e){
throw new FlumeException("Could not get row key!", e);
}
}
return actions;
}
| public List<PutRequest> getActions() {
List<PutRequest> actions = new ArrayList<PutRequest>();
if(payloadColumn != null){
byte[] rowKey;
String srchost = (hbevent.getHeaders().containsKey("host"))?(hbevent.getHeaders().get("host")):("");
String rowPrefixHost = rowPrefix + srchost + "-";
try {
switch (keyType) {
case TS:
rowKey = SimpleRowKeyGenerator.getTimestampKey(rowPrefixHost);
break;
case TSNANO:
rowKey = SimpleRowKeyGenerator.getNanoTimestampKey(rowPrefixHost);
break;
case RANDOM:
rowKey = SimpleRowKeyGenerator.getRandomKey(rowPrefixHost);
break;
default:
rowKey = SimpleRowKeyGenerator.getUUIDKey(rowPrefixHost);
break;
}
PutRequest putRequest;
// Event Headers
for (Map.Entry<String, String> entry : hbevent.getHeaders().entrySet()) {
if (entry.getKey() != null) {
putRequest = new PutRequest(table, rowKey, cf, entry.getKey().getBytes(), entry.getValue().getBytes());
actions.add(putRequest);
}
}
// Event Body
putRequest = new PutRequest(table, rowKey, cf, payloadColumn, payload);
actions.add(putRequest);
} catch (Exception e){
throw new FlumeException("Could not get row key!", e);
}
}
return actions;
}
|
diff --git a/frost-wot/source/frost/util/gui/treetable/MessageTreeTable.java b/frost-wot/source/frost/util/gui/treetable/MessageTreeTable.java
index 4814d12c..0a2fb2bd 100644
--- a/frost-wot/source/frost/util/gui/treetable/MessageTreeTable.java
+++ b/frost-wot/source/frost/util/gui/treetable/MessageTreeTable.java
@@ -1,926 +1,926 @@
/*
* Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/
package frost.util.gui.treetable;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import frost.*;
import frost.gui.objects.*;
/**
* This example shows how to create a simple JTreeTable component,
* by using a JTree as a renderer (and editor) for the cells in a
* particular column in the JTable.
*
* @version 1.2 10/27/98
*
* @author Philip Milne
* @author Scott Violet
*/
public class MessageTreeTable extends JTable {
/** A subclass of JTree. */
protected TreeTableCellRenderer tree;
private CellRenderer cellRenderer = new CellRenderer();
public MessageTreeTable(TreeTableModel treeTableModel) {
super();
// Creates the tree. It will be used as a renderer and editor.
tree = new TreeTableCellRenderer(treeTableModel);
// Installs a tableModel representing the visible rows in the tree.
super.setModel(new TreeTableModelAdapter(treeTableModel, tree));
// // set initial column sizes
// int[] widths = { 40, 30, 10, 20 };
// for (int i = 0; i < widths.length; i++) {
// getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
// }
// Forces the JTable and JTree to share their row selection models.
ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper();
tree.setSelectionModel(selectionWrapper);
setSelectionModel(selectionWrapper.getListSelectionModel());
// tree.setRootVisible(false);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
// Installs the tree editor renderer and editor.
setDefaultRenderer(TreeTableModel.class, tree);
setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
// install cell renderer
setDefaultRenderer(String.class, cellRenderer);
// No grid.
setShowGrid(false);
// No intercell spacing
setIntercellSpacing(new Dimension(0, 0));
// And update the height of the trees row to match that of the table.
if (tree.getRowHeight() < 1) {
// Metal looks better like this.
setRowHeight(20);
}
}
public void setNewRootNode(TreeNode t) {
((DefaultTreeModel)tree.getModel()).setRoot(t);
}
// If expand is true, expands all nodes in the tree.
// Otherwise, collapses all nodes in the tree.
public void expandAll(final boolean expand) {
final TreeNode root = (TreeNode)tree.getModel().getRoot();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Traverse tree from root
expandAll(new TreePath(root), expand);
}
});
}
private void expandAll(TreePath parent, boolean expand) {
// Traverse children
TreeNode node = (TreeNode)parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration e=node.children(); e.hasMoreElements(); ) {
TreeNode n = (TreeNode)e.nextElement();
TreePath path = parent.pathByAddingChild(n);
expandAll(path, expand);
}
}
// Expansion or collapse must be done bottom-up
if (expand) {
if( !tree.isExpanded(parent) ) {
tree.expandPath(parent);
}
} else {
if( !tree.isCollapsed(parent) ) {
tree.collapsePath(parent);
}
}
}
public void expandNode(final DefaultMutableTreeNode n) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
expandAll(new TreePath(n.getPath()), true);
}
});
}
/**
* Overridden to message super and forward the method to the tree.
* Since the tree is not actually in the component hierarchy it will
* never receive this unless we forward it in this manner.
*/
public void updateUI() {
super.updateUI();
if(tree != null) {
tree.updateUI();
// Do this so that the editor is referencing the current renderer
// from the tree. The renderer can potentially change each time
// laf changes.
// setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
}
// Use the tree's default foreground and background colors in the
// table.
LookAndFeel.installColorsAndFont(this, "Tree.background",
"Tree.foreground", "Tree.font");
}
/**
* Workaround for BasicTableUI anomaly. Make sure the UI never tries to
* resize the editor. The UI currently uses different techniques to
* paint the renderers and editors; overriding setBounds() below
* is not the right thing to do for an editor. Returning -1 for the
* editing row in this case, ensures the editor is never painted.
*/
public int getEditingRow() {
return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 :
editingRow;
}
/**
* Returns the actual row that is editing as <code>getEditingRow</code>
* will always return -1.
*/
private int realEditingRow() {
return editingRow;
}
/**
* This is overridden to invoke super's implementation, and then,
* if the receiver is editing a Tree column, the editor's bounds is
* reset. The reason we have to do this is because JTable doesn't
* think the table is being edited, as <code>getEditingRow</code> returns
* -1, and therefore doesn't automatically resize the editor for us.
*/
public void sizeColumnsToFit(int resizingColumn) {
super.sizeColumnsToFit(resizingColumn);
if (getEditingColumn() != -1 && getColumnClass(editingColumn) ==
TreeTableModel.class) {
Rectangle cellRect = getCellRect(realEditingRow(),
getEditingColumn(), false);
Component component = getEditorComponent();
component.setBounds(cellRect);
component.validate();
}
}
/**
* Overridden to pass the new rowHeight to the tree.
*/
public void setRowHeight(int rowHeight) {
super.setRowHeight(rowHeight);
if (tree != null && tree.getRowHeight() != rowHeight) {
tree.setRowHeight(getRowHeight());
}
}
/**
* Returns the tree that is being shared between the model.
*/
public JTree getTree() {
return tree;
}
public int getRowForNode(DefaultMutableTreeNode n) {
if(n.isRoot()) {
return 0;
}
TreePath tp = new TreePath(n.getPath());
return tree.getRowForPath(tp);
}
/**
* Overridden to invoke repaint for the particular location if
* the column contains the tree. This is done as the tree editor does
* not fill the bounds of the cell, we need the renderer to paint
* the tree in the background, and then draw the editor over it.
*/
public boolean editCellAt(int row, int column, EventObject e){
boolean retValue = super.editCellAt(row, column, e);
if (retValue && getColumnClass(column) == TreeTableModel.class) {
repaint(getCellRect(row, column, false));
}
return retValue;
}
/**
* A TreeCellRenderer that displays a JTree.
*/
public class TreeTableCellRenderer extends JTree implements TableCellRenderer {
/** Last table/tree row asked to renderer. */
protected int visibleRow;
/** Border to draw around the tree, if this is non-null, it will be painted. */
protected Border highlightBorder;
private Font boldFont = null;
private Font normalFont = null;
private boolean isDeleted = false;
public TreeTableCellRenderer(TreeModel model) {
super(model);
Font baseFont = MessageTreeTable.this.getFont();
normalFont = baseFont.deriveFont(Font.PLAIN);
boldFont = baseFont.deriveFont(Font.BOLD);
}
/**
* updateUI is overridden to set the colors of the Tree's renderer
* to match that of the table.
*/
public void updateUI() {
super.updateUI();
// Make the tree's cell renderer use the table's cell selection
// colors.
TreeCellRenderer tcr = getCellRenderer();
if (tcr instanceof DefaultTreeCellRenderer) {
DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr);
// For 1.1 uncomment this, 1.2 has a bug that will cause an
// exception to be thrown if the border selection color is null.
// dtcr.setBorderSelectionColor(null);
dtcr.setTextSelectionColor(UIManager.getColor("Table.selectionForeground"));
dtcr.setBackgroundSelectionColor(UIManager.getColor("Table.selectionBackground"));
}
}
public void setDeleted(boolean value) {
isDeleted = value;
}
/**
* Sets the row height of the tree, and forwards the row height to
* the table.
*/
public void setRowHeight(int rowHeight) {
if (rowHeight > 0) {
super.setRowHeight(rowHeight);
if (MessageTreeTable.this != null &&
MessageTreeTable.this.getRowHeight() != rowHeight) {
MessageTreeTable.this.setRowHeight(getRowHeight());
}
}
}
/**
* This is overridden to set the height to match that of the JTable.
*/
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, 0, w, MessageTreeTable.this.getHeight());
}
/**
* Sublcassed to translate the graphics such that the last visible
* row will be drawn at 0,0.
*/
public void paint(Graphics g) {
g.translate(0, -visibleRow * getRowHeight());
super.paint(g);
// Draw the Table border if we have focus.
if (highlightBorder != null) {
highlightBorder.paintBorder(this, g, 0, visibleRow *
getRowHeight(), getWidth(),
getRowHeight());
}
if(isDeleted) {
// FIXME: does not work!
Dimension size = getSize();
g.drawLine(0, size.height / 2, size.width, size.height / 2);
}
}
/**
* TreeCellRenderer method. Overridden to update the visible row.
*/
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
Color background;
Color foreground;
setAlignmentY(CENTER_ALIGNMENT);
// TODO: rework, dup code
TreeTableModelAdapter model = (TreeTableModelAdapter)MessageTreeTable.this.getModel();
Object o = model.getRow(row);
if( !(o instanceof FrostMessageObject) ) {
setFont(normalFont);
setForeground(Color.BLACK);
return this;
}
FrostMessageObject msg = (FrostMessageObject)model.getRow(row);
// FROM
// first set font, bold for new msg or normal
if (msg.isNew()) {
setFont(boldFont);
} else {
setFont(normalFont);
}
// now set color
if( msg.getRecipientName() != null && msg.getRecipientName().length() > 0) {
foreground = Color.RED;
} else if (msg.containsAttachments()) {
foreground = Color.BLUE;
} else {
foreground = Color.BLACK;
}
if (!isSelected) {
// IBM lineprinter paper
if ((row & 0x0001) == 0) {
background = Color.WHITE;
} else {
background = new java.awt.Color(238,238,238);
}
} else {
background = table.getSelectionBackground();
// foreground = table.getSelectionForeground();
}
setDeleted(msg.isDeleted());
// orig code
highlightBorder = null;
if (hasFocus) {
// highlightBorder = UIManager.getBorder("Table.focusCellHighlightBorder");
}
visibleRow = row;
setBackground(background);
TreeCellRenderer tcr = getCellRenderer();
if (tcr instanceof DefaultTreeCellRenderer) {
DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr);
if (isSelected) {
dtcr.setTextSelectionColor(foreground);
dtcr.setBackgroundSelectionColor(background);
}
else {
dtcr.setTextNonSelectionColor(foreground);
dtcr.setBackgroundNonSelectionColor(background);
}
}
return this;
}
}
/**
* An editor that can be used to edit the tree column. This extends
* DefaultCellEditor and uses a JTextField (actually, TreeTableTextField)
* to perform the actual editing.
* <p>To support editing of the tree column we can not make the tree
* editable. The reason this doesn't work is that you can not use
* the same component for editing and renderering. The table may have
* the need to paint cells, while a cell is being edited. If the same
* component were used for the rendering and editing the component would
* be moved around, and the contents would change. When editing, this
* is undesirable, the contents of the text field must stay the same,
* including the caret blinking, and selections persisting. For this
* reason the editing is done via a TableCellEditor.
* <p>Another interesting thing to be aware of is how tree positions
* its render and editor. The render/editor is responsible for drawing the
* icon indicating the type of node (leaf, branch...). The tree is
* responsible for drawing any other indicators, perhaps an additional
* +/- sign, or lines connecting the various nodes. So, the renderer
* is positioned based on depth. On the other hand, table always makes
* its editor fill the contents of the cell. To get the allusion
* that the table cell editor is part of the tree, we don't want the
* table cell editor to fill the cell bounds. We want it to be placed
* in the same manner as tree places it editor, and have table message
* the tree to paint any decorations the tree wants. Then, we would
* only have to worry about the editing part. The approach taken
* here is to determine where tree would place the editor, and to override
* the <code>reshape</code> method in the JTextField component to
* nudge the textfield to the location tree would place it. Since
* JTreeTable will paint the tree behind the editor everything should
* just work. So, that is what we are doing here. Determining of
* the icon position will only work if the TreeCellRenderer is
* an instance of DefaultTreeCellRenderer. If you need custom
* TreeCellRenderers, that don't descend from DefaultTreeCellRenderer,
* and you want to support editing in JTreeTable, you will have
* to do something similiar.
*/
// public class TreeTableCellEditor extends DefaultCellEditor {
// public TreeTableCellEditor() {
// super(new TreeTableTextField());
// }
//
// /**
// * Overridden to determine an offset that tree would place the
// * editor at. The offset is determined from the
// * <code>getRowBounds</code> JTree method, and additionally
// * from the icon DefaultTreeCellRenderer will use.
// * <p>The offset is then set on the TreeTableTextField component
// * created in the constructor, and returned.
// */
// public Component getTableCellEditorComponent(JTable table,
// Object value,
// boolean isSelected,
// int r, int c) {
// Component component = super.getTableCellEditorComponent
// (table, value, isSelected, r, c);
// JTree t = getTree();
// boolean rv = t.isRootVisible();
// int offsetRow = rv ? r : r - 1;
// Rectangle bounds = t.getRowBounds(offsetRow);
// int offset = bounds.x;
// TreeCellRenderer tcr = t.getCellRenderer();
// if (tcr instanceof DefaultTreeCellRenderer) {
// Object node = t.getPathForRow(offsetRow).
// getLastPathComponent();
// Icon icon;
// if (t.getModel().isLeaf(node))
// icon = ((DefaultTreeCellRenderer)tcr).getLeafIcon();
// else if (tree.isExpanded(offsetRow))
// icon = ((DefaultTreeCellRenderer)tcr).getOpenIcon();
// else
// icon = ((DefaultTreeCellRenderer)tcr).getClosedIcon();
// if (icon != null) {
// offset += ((DefaultTreeCellRenderer)tcr).getIconTextGap() +
// icon.getIconWidth();
// }
// }
// ((TreeTableTextField)getComponent()).offset = offset;
// return component;
// }
//
// /**
// * This is overridden to forward the event to the tree. This will
// * return true if the click count >= 3, or the event is null.
// */
// public boolean isCellEditable(EventObject e) {
// if (e instanceof MouseEvent) {
// MouseEvent me = (MouseEvent)e;
// // If the modifiers are not 0 (or the left mouse button),
// // tree may try and toggle the selection, and table
// // will then try and toggle, resulting in the
// // selection remaining the same. To avoid this, we
// // only dispatch when the modifiers are 0 (or the left mouse
// // button).
// if (me.getModifiers() == 0 ||
// me.getModifiers() == InputEvent.BUTTON1_MASK) {
// for (int counter = getColumnCount() - 1; counter >= 0;
// counter--) {
// if (getColumnClass(counter) == TreeTableModel.class) {
// MouseEvent newME = new MouseEvent
// (JTreeTable.this.tree, me.getID(),
// me.getWhen(), me.getModifiers(),
// me.getX() - getCellRect(0, counter, true).x,
// me.getY(), me.getClickCount(),
// me.isPopupTrigger());
// JTreeTable.this.tree.dispatchEvent(newME);
// break;
// }
// }
// }
// if (me.getClickCount() >= 3) {
// return true;
// }
// return false;
// }
// if (e == null) {
// return true;
// }
// return false;
// }
// }
/**
* ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel
* to listen for changes in the ListSelectionModel it maintains. Once
* a change in the ListSelectionModel happens, the paths are updated
* in the DefaultTreeSelectionModel.
*/
class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel {
/** Set to true when we are updating the ListSelectionModel. */
protected boolean updatingListSelectionModel;
public ListToTreeSelectionModelWrapper() {
super();
getListSelectionModel().addListSelectionListener(createListSelectionListener());
}
/**
* Returns the list selection model. ListToTreeSelectionModelWrapper
* listens for changes to this model and updates the selected paths
* accordingly.
*/
ListSelectionModel getListSelectionModel() {
return listSelectionModel;
}
/**
* This is overridden to set <code>updatingListSelectionModel</code>
* and message super. This is the only place DefaultTreeSelectionModel
* alters the ListSelectionModel.
*/
public void resetRowSelection() {
if(!updatingListSelectionModel) {
updatingListSelectionModel = true;
try {
// super.resetRowSelection();
}
finally {
updatingListSelectionModel = false;
}
}
// Notice how we don't message super if
// updatingListSelectionModel is true. If
// updatingListSelectionModel is true, it implies the
// ListSelectionModel has already been updated and the
// paths are the only thing that needs to be updated.
}
/**
* Creates and returns an instance of ListSelectionHandler.
*/
protected ListSelectionListener createListSelectionListener() {
return new ListSelectionHandler();
}
/**
* If <code>updatingListSelectionModel</code> is false, this will
* reset the selected paths from the selected rows in the list
* selection model.
*/
protected void updateSelectedPathsFromSelectedRows() {
if(!updatingListSelectionModel) {
updatingListSelectionModel = true;
try {
// This is way expensive, ListSelectionModel needs an enumerator for iterating
int min = listSelectionModel.getMinSelectionIndex();
int max = listSelectionModel.getMaxSelectionIndex();
clearSelection();
if(min != -1 && max != -1) {
for(int counter = min; counter <= max; counter++) {
if(listSelectionModel.isSelectedIndex(counter)) {
TreePath selPath = tree.getPathForRow(counter);
if(selPath != null) {
addSelectionPath(selPath);
}
}
}
}
}
finally {
updatingListSelectionModel = false;
}
}
}
/**
* Class responsible for calling updateSelectedPathsFromSelectedRows
* when the selection of the list changse.
*/
class ListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
updateSelectedPathsFromSelectedRows();
}
}
}
/**
* This renderer renders rows in different colors.
* New messages gets a bold look, messages with attachments a blue color.
* Encrypted messages get a red color, no matter if they have attachments.
*/
private class CellRenderer extends DefaultTableCellRenderer
{
private Font boldFont = null;
private Font normalFont = null;
private boolean isDeleted = false;
private final Color col_good = new Color(0x00, 0x80, 0x00);
private final Color col_check = new Color(0xFF, 0xCC, 0x00);
private final Color col_observe = new Color(0x00, 0xD0, 0x00);
private final Color col_bad = new Color(0xFF, 0x00, 0x00);
public CellRenderer() {
Font baseFont = MessageTreeTable.this.getFont();
normalFont = baseFont.deriveFont(Font.PLAIN);
boldFont = baseFont.deriveFont(Font.BOLD);
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
if(isDeleted) {
Dimension size = getSize();
g.drawLine(0, size.height / 2, size.width, size.height / 2);
}
}
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, /*hasFocus*/ false, row, column);
if (!isSelected) {
// IBM lineprinter paper
if ((row & 0x0001) == 0) {
setBackground(Color.WHITE);
} else {
setBackground(new java.awt.Color(238,238,238));
}
} else {
setBackground(table.getSelectionBackground());
}
setAlignmentY(CENTER_ALIGNMENT);
TreeTableModelAdapter model = (TreeTableModelAdapter) getModel();
Object o = model.getRow(row);
if( !(o instanceof FrostMessageObject) ) {
setFont(normalFont);
setForeground(Color.BLACK);
return this;
}
FrostMessageObject msg = (FrostMessageObject) model.getRow(row);
// get the original model column index (maybe columns were reordered by user)
TableColumn tableColumn = getColumnModel().getColumn(column);
column = tableColumn.getModelIndex();
// do nice things for FROM and SIG column
- if( column == 1 ) {
+ if( column == 3 ) {
// FROM
// first set font, bold for new msg or normal
if (msg.isNew()) {
setFont(boldFont);
} else {
setFont(normalFont);
}
// now set color
if (!isSelected) {
if( msg.getRecipientName() != null && msg.getRecipientName().length() > 0) {
setForeground(Color.RED);
} else if (msg.containsAttachments()) {
setForeground(Color.BLUE);
} else {
setForeground(Color.BLACK);
}
}
- } else if( column == 2 ) {
+ } else if( column == 4 ) {
// SIG
// state == good/bad/check/observe -> bold and coloured
if( msg.isMessageStatusGOOD() ) {
setFont(boldFont);
setForeground(col_good);
} else if( msg.isMessageStatusCHECK() ) {
setFont(boldFont);
setForeground(col_check);
} else if( msg.isMessageStatusOBSERVE() ) {
setFont(boldFont);
setForeground(col_observe);
} else if( msg.isMessageStatusBAD() ) {
setFont(boldFont);
setForeground(col_bad);
} else {
setFont(normalFont);
if (!isSelected) {
setForeground(Color.BLACK);
}
}
} else {
setFont(normalFont);
if (!isSelected) {
setForeground(Color.BLACK);
}
}
setDeleted(msg.isDeleted());
return this;
}
/* (non-Javadoc)
* @see java.awt.Component#setFont(java.awt.Font)
*/
public void setFont(Font font) {
super.setFont(font);
normalFont = font.deriveFont(Font.PLAIN);
boldFont = font.deriveFont(Font.BOLD);
}
public void setDeleted(boolean value) {
isDeleted = value;
}
}
public class TreeTableCellEditor extends DefaultCellEditor {
public TreeTableCellEditor() {
super(new JTextField());
}
/**
* Overridden to determine an offset that tree would place the
* editor at. The offset is determined from the
* <code>getRowBounds</code> JTree method, and additionally
* from the icon DefaultTreeCellRenderer will use.
* <p>The offset is then set on the TreeTableTextField component
* created in the constructor, and returned.
*/
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int r, int c) {
Component component = super.getTableCellEditorComponent(table, value, isSelected, r, c);
JTree t = getTree();
boolean rv = t.isRootVisible();
int offsetRow = rv ? r : r - 1;
Rectangle bounds = t.getRowBounds(offsetRow);
int offset = bounds.x;
TreeCellRenderer tcr = t.getCellRenderer();
if (tcr instanceof DefaultTreeCellRenderer) {
Object node = t.getPathForRow(offsetRow).
getLastPathComponent();
Icon icon;
if (t.getModel().isLeaf(node))
icon = ((DefaultTreeCellRenderer)tcr).getLeafIcon();
else if (tree.isExpanded(offsetRow))
icon = ((DefaultTreeCellRenderer)tcr).getOpenIcon();
else
icon = ((DefaultTreeCellRenderer)tcr).getClosedIcon();
if (icon != null) {
offset += ((DefaultTreeCellRenderer)tcr).getIconTextGap() +
icon.getIconWidth();
}
}
// ((TreeTableTextField)getComponent()).offset = offset;
return component;
}
/**
* This is overridden to forward the event to the tree. This will
* return true if the click count >= 3, or the event is null.
*/
public boolean isCellEditable(EventObject e) {
if (e instanceof MouseEvent) {
MouseEvent me = (MouseEvent)e;
// If the modifiers are not 0 (or the left mouse button),
// tree may try and toggle the selection, and table
// will then try and toggle, resulting in the
// selection remaining the same. To avoid this, we
// only dispatch when the modifiers are 0 (or the left mouse
// button).
if (me.getModifiers() == 0 || me.getModifiers() == InputEvent.BUTTON1_MASK) {
for (int counter = getColumnCount() - 1; counter >= 0; counter--) {
if (getColumnClass(counter) == TreeTableModel.class) {
MouseEvent newME = new MouseEvent
(MessageTreeTable.this.tree, me.getID(),
me.getWhen(), me.getModifiers(),
me.getX() - getCellRect(0, counter, true).x,
me.getY(), me.getClickCount(),
me.isPopupTrigger());
MessageTreeTable.this.tree.dispatchEvent(newME);
break;
}
}
}
// if (me.getClickCount() >= 3) {
// return true;
// }
return false;
}
// if (e == null) {
// return true;
// }
return false;
}
}
/**
* Save the current column positions and column sizes for restore on next startup.
*
* @param frostSettings
*/
public void saveLayout(SettingsClass frostSettings) {
TableColumnModel tcm = getColumnModel();
for(int columnIndexInTable=0; columnIndexInTable < tcm.getColumnCount(); columnIndexInTable++) {
TableColumn tc = tcm.getColumn(columnIndexInTable);
int columnIndexInModel = tc.getModelIndex();
// save the current index in table for column with the fix index in model
frostSettings.setValue("messagetreetable.tableindex.modelcolumn."+columnIndexInModel, columnIndexInTable);
// save the current width of the column
int columnWidth = tc.getWidth();
frostSettings.setValue("messagetreetable.columnwidth.modelcolumn."+columnIndexInModel, columnWidth);
}
}
/**
* Load the saved column positions and column sizes.
*
* @param frostSettings
*/
public void loadLayout(SettingsClass frostSettings) {
TableColumnModel tcm = getColumnModel();
// load the saved tableindex for each column in model, and its saved width
int[] tableToModelIndex = new int[tcm.getColumnCount()];
int[] columnWidths = new int[tcm.getColumnCount()];
for(int x=0; x < tableToModelIndex.length; x++) {
String indexKey = "messagetreetable.tableindex.modelcolumn."+x;
if( frostSettings.getObjectValue(indexKey) == null ) {
return; // column not found, abort
}
// build array of table to model associations
int tableIndex = frostSettings.getIntValue(indexKey);
if( tableIndex < 0 || tableIndex >= tableToModelIndex.length ) {
return; // invalid table index value
}
tableToModelIndex[tableIndex] = x;
String widthKey = "messagetreetable.columnwidth.modelcolumn."+x;
if( frostSettings.getObjectValue(widthKey) == null ) {
return; // column not found, abort
}
// build array of table to model associations
int columnWidth = frostSettings.getIntValue(widthKey);
if( columnWidth <= 0 ) {
return; // invalid column width
}
columnWidths[x] = columnWidth;
}
// columns are currently added in model order, remove them all and save in an array
// while on it, set the loaded width of each column
TableColumn[] tcms = new TableColumn[tcm.getColumnCount()];
for(int x=tcms.length-1; x >= 0; x--) {
tcms[x] = tcm.getColumn(x);
tcm.removeColumn(tcms[x]);
tcms[x].setPreferredWidth(columnWidths[x]);
}
// add the columns in order loaded from settings
for(int x=0; x < tableToModelIndex.length; x++) {
tcm.addColumn(tcms[tableToModelIndex[x]]);
}
}
}
| false | true | public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, /*hasFocus*/ false, row, column);
if (!isSelected) {
// IBM lineprinter paper
if ((row & 0x0001) == 0) {
setBackground(Color.WHITE);
} else {
setBackground(new java.awt.Color(238,238,238));
}
} else {
setBackground(table.getSelectionBackground());
}
setAlignmentY(CENTER_ALIGNMENT);
TreeTableModelAdapter model = (TreeTableModelAdapter) getModel();
Object o = model.getRow(row);
if( !(o instanceof FrostMessageObject) ) {
setFont(normalFont);
setForeground(Color.BLACK);
return this;
}
FrostMessageObject msg = (FrostMessageObject) model.getRow(row);
// get the original model column index (maybe columns were reordered by user)
TableColumn tableColumn = getColumnModel().getColumn(column);
column = tableColumn.getModelIndex();
// do nice things for FROM and SIG column
if( column == 1 ) {
// FROM
// first set font, bold for new msg or normal
if (msg.isNew()) {
setFont(boldFont);
} else {
setFont(normalFont);
}
// now set color
if (!isSelected) {
if( msg.getRecipientName() != null && msg.getRecipientName().length() > 0) {
setForeground(Color.RED);
} else if (msg.containsAttachments()) {
setForeground(Color.BLUE);
} else {
setForeground(Color.BLACK);
}
}
} else if( column == 2 ) {
// SIG
// state == good/bad/check/observe -> bold and coloured
if( msg.isMessageStatusGOOD() ) {
setFont(boldFont);
setForeground(col_good);
} else if( msg.isMessageStatusCHECK() ) {
setFont(boldFont);
setForeground(col_check);
} else if( msg.isMessageStatusOBSERVE() ) {
setFont(boldFont);
setForeground(col_observe);
} else if( msg.isMessageStatusBAD() ) {
setFont(boldFont);
setForeground(col_bad);
} else {
setFont(normalFont);
if (!isSelected) {
setForeground(Color.BLACK);
}
}
} else {
setFont(normalFont);
if (!isSelected) {
setForeground(Color.BLACK);
}
}
setDeleted(msg.isDeleted());
return this;
}
| public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, /*hasFocus*/ false, row, column);
if (!isSelected) {
// IBM lineprinter paper
if ((row & 0x0001) == 0) {
setBackground(Color.WHITE);
} else {
setBackground(new java.awt.Color(238,238,238));
}
} else {
setBackground(table.getSelectionBackground());
}
setAlignmentY(CENTER_ALIGNMENT);
TreeTableModelAdapter model = (TreeTableModelAdapter) getModel();
Object o = model.getRow(row);
if( !(o instanceof FrostMessageObject) ) {
setFont(normalFont);
setForeground(Color.BLACK);
return this;
}
FrostMessageObject msg = (FrostMessageObject) model.getRow(row);
// get the original model column index (maybe columns were reordered by user)
TableColumn tableColumn = getColumnModel().getColumn(column);
column = tableColumn.getModelIndex();
// do nice things for FROM and SIG column
if( column == 3 ) {
// FROM
// first set font, bold for new msg or normal
if (msg.isNew()) {
setFont(boldFont);
} else {
setFont(normalFont);
}
// now set color
if (!isSelected) {
if( msg.getRecipientName() != null && msg.getRecipientName().length() > 0) {
setForeground(Color.RED);
} else if (msg.containsAttachments()) {
setForeground(Color.BLUE);
} else {
setForeground(Color.BLACK);
}
}
} else if( column == 4 ) {
// SIG
// state == good/bad/check/observe -> bold and coloured
if( msg.isMessageStatusGOOD() ) {
setFont(boldFont);
setForeground(col_good);
} else if( msg.isMessageStatusCHECK() ) {
setFont(boldFont);
setForeground(col_check);
} else if( msg.isMessageStatusOBSERVE() ) {
setFont(boldFont);
setForeground(col_observe);
} else if( msg.isMessageStatusBAD() ) {
setFont(boldFont);
setForeground(col_bad);
} else {
setFont(normalFont);
if (!isSelected) {
setForeground(Color.BLACK);
}
}
} else {
setFont(normalFont);
if (!isSelected) {
setForeground(Color.BLACK);
}
}
setDeleted(msg.isDeleted());
return this;
}
|
diff --git a/src/Main/ServerThread.java b/src/Main/ServerThread.java
index c0c5ec7..00e344f 100644
--- a/src/Main/ServerThread.java
+++ b/src/Main/ServerThread.java
@@ -1,401 +1,408 @@
package Main;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
/**
* Provides threads for the server so multiple clients can be handled by a
* single server
*
* @author Cole Christie
*
*/
public class ServerThread extends Thread {
private Logging mylog;
private Socket socket;
private Networking network;
private Auth subject;
private int UID;
private Crypto crypt;
private Object JobLock;
private JobManagement JobQueue;
private boolean ServerMode;
/**
* CONSTRUCTOR for Server Worker Thread
*/
public ServerThread(Auth passedSubject, Logging passedLog, Socket passedSocket, int passedUID, Object passedLock,
JobManagement passedJobQueue, boolean PassedMode) {
subject = passedSubject;
mylog = passedLog;
socket = passedSocket;
UID = passedUID;
JobLock = passedLock;
JobQueue = passedJobQueue;
ServerMode = PassedMode;
network = new Networking(mylog);
}
/**
* CONSTRUCTOR for Server Management Thread
*/
public ServerThread(Logging passedLog, Object passedLock, JobManagement passedJobQueue) {
mylog = passedLog;
JobLock = passedLock;
JobQueue = passedJobQueue;
}
/**
* Runs the Job loading framework based upon the execution request passed to
* it (string argument).
*
* @param type
* @return
*/
public void JobLoader(String type) {
synchronized (JobLock) {
if (type.compareToIgnoreCase("sw") == 0) {
JobQueue.SampleWindows();
mylog.out("INFO", "Loaded 10 sample jobs (Windows).");
} else if (type.compareToIgnoreCase("sl") == 0) {
JobQueue.SampleLinux();
mylog.out("INFO", "Loaded 10 sample jobs (Linux/UNIX).");
} else if (type.compareToIgnoreCase("sa") == 0) {
JobQueue.Sample();
mylog.out("INFO", "Loaded 10 sample jobs (Any OS).");
} else if (type.compareToIgnoreCase("cuq") == 0) {
JobQueue.ClearUnsentQueue();
mylog.out("INFO", "Unassigned job queue reset.");
} else if (type.compareToIgnoreCase("caq") == 0) {
JobQueue.ClearSentQueue();
mylog.out("INFO", "Assigned job queue reset.");
} else if (type.compareToIgnoreCase("list") == 0) {
mylog.out("INFO", "[" + JobQueue.UnassignedCount() + "] unassigned jobs are left in the queue");
mylog.out("INFO", "[" + JobQueue.AssignedCount() + "] jobs are in progress");
}
// TODO add "load" option
}
}
/**
* Runs the Job loading framework based upon the execution request passed to
* it (string argument). Returns the count (int) of the number of jobs that
* were loaded.
*
* @param type
* @return
*/
public void JobLoader(String type, String filename) {
int QtyJobsLoaded = 0;
synchronized (JobLock) {
if (type.compareToIgnoreCase("load") == 0) {
try {
QtyJobsLoaded = JobQueue.Load(filename);
} catch (IOException e) {
mylog.out("ERROR", "Failed to load jobs from file [" + filename + "]");
}
mylog.out("INFO", "Loaded [" + QtyJobsLoaded + "] jobs.");
}
}
}
/**
* Assigns a job to the client in the system and returns a string that has
* the requested jobs instructions
*
* @param clientID
* @return
*/
public String AssignJob(String clientID, String OS, int ClientSecurityLevel) {
String job = "";
synchronized (JobLock) {
job = JobQueue.Assign(clientID, OS, ClientSecurityLevel);
}
return job;
}
/**
* Server thread Enables multi-client support
*/
public void run() {
// TODO Refactor so this can be used for both the SERVER and the DROPOFF
// UID is just an iterator from the server side
// It has no bearing on anything besides the raw question
// "How many have connected to this single runtime?"
mylog.out("INFO", "Establishing session with client number [" + UID + "]");
// Load and save the cleints IP and port for future UUID creation
SocketAddress theirAddress = socket.getRemoteSocketAddress();
String ClientIP = theirAddress.toString();
ClientIP = ClientIP.replace("/", "");
// Bind I/O to the socket
network.BringUp(socket);
// Prep
String fromClient = null;
+ boolean NoSend = false;
// Activate crypto
crypt = new Crypto(mylog, subject.GetPSK(), "Client");
byte[] fetched = network.ReceiveByte();
String dec = crypt.decrypt(fetched);
String craftReturn = dec + "<S>";
mylog.out("INFO", "Validating encryption with handshake.");
byte[] returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
// Main Loop
while (!socket.isClosed()) {
// Collect data sent over the network
fetched = network.ReceiveByte();
if (fetched == null) {
mylog.out("WARN", "Client disconnected abruptly");
break;
}
// Decrypt sent data
fromClient = crypt.decrypt(fetched);
// Pre-calculate meta data from passed arguments
// (for job distribution)
String ClientName = ClientIP;
boolean ClientMetaSet = false;
String ClientOS = "";
int ClientSecurityLevel = 0;
if (fromClient == null) {
mylog.out("WARN", "Client disconnected abruptly");
break;
}
// If this is a SERVER
if (ServerMode) {
// Preliminary scanning and data input manipulation
if (fromClient.toLowerCase().contains("job")) {
String[] CHOP = fromClient.split(":");
// Add the random number passed to us to the servers UID of
// this client session to create a reasonable UUID
if (CHOP.length == 4) {
// Extract meta data
if (!ClientMetaSet) {
// Only set this once
ClientName = ClientName + CHOP[1];
ClientOS = CHOP[2];
ClientSecurityLevel = Integer.parseInt(CHOP[3]);
ClientMetaSet = true;
}
// Assign a job to the client
mylog.out("INFO", "Client [" + ClientName + "] with security level [" + ClientSecurityLevel
+ "] reuested a job for [" + ClientOS + "]");
synchronized (JobLock) {
+ NoSend = true; // Do not send a secondary response
String work = JobQueue.Assign(ClientName, ClientOS, ClientSecurityLevel);
returnData = crypt.encrypt(work);
network.Send(returnData);
if (work.length() > 0) {
mylog.out("INFO", "JobOut:[" + work + "]");
mylog.out("INFO", "[" + JobQueue.UnassignedCount()
+ "] unassigned jobs are left in the queue");
mylog.out("INFO", "[" + JobQueue.AssignedCount() + "] jobs are in progress");
} else {
mylog.out("WARN", "There are no jobs for [" + ClientOS + "] with Security Level ["
+ ClientSecurityLevel + "]");
}
}
} else {
// The client failed to send all of the meta data we
// need, so abort the job request
fromClient = "";
mylog.out("INFO", "Job request failed. Missing meta data in request.");
}
} else if (fromClient.toLowerCase().contains("workdone")) {
if (ClientMetaSet) {
synchronized (JobLock) {
+ NoSend = true; // Do not send a secondary response
String work = JobQueue.Signoff(ClientName);
if (work.equalsIgnoreCase("Failed")) {
// The job was not able to be acknowledged
mylog.out("WARN", "Client [" + ClientName
+ "] job complete was NOT acknowledged (no was job assigned previously).");
} else {
mylog.out("INFO", "Client [" + ClientName + "] job was acknowledged.");
}
work = "Acknowledged";
returnData = crypt.encrypt(work);
network.Send(returnData);
}
} else {
mylog.out("ERROR",
"Client is requesting to acknowledge job completion before being assigned a job");
}
}
} else {
// If this is a Drop Off point
}
// Common actions below (Server AND Drop Off point)
- if (fromClient.compareToIgnoreCase("quit") == 0) {
+ if (NoSend) {
+ // We do not send anything this time as the transmission to the
+ // client was already handled above
+ NoSend = false;
+ } else if (fromClient.compareToIgnoreCase("quit") == 0) {
mylog.out("INFO", "Client disconnected gracefully");
break;
} else if (fromClient.compareToIgnoreCase("<REKEY>") == 0) {
SendACK(); // Send ACK
String prime = null;
String base = null;
// Grab 1st value (should be handshake for PRIME)
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PRIME>") == 0) {
prime = fromNetwork();
SendACK(); // Send ACK
} else {
mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive PRIME).");
}
// Grab 2nd value (should be handshake for BASE)
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<BASE>") == 0) {
base = fromNetwork();
SendACK(); // Send ACK
} else {
mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive BASE).");
}
// Use received values to start DH
DH myDH = new DH(mylog, prime, 16, base, 16);
// Send rekeying ack
returnData = crypt.encrypt("<REKEY-STARTING>");
network.Send(returnData);
RecieveACK(); // Wait for ACK
// Perform phase1
myDH.DHPhase1();
// Receive client public key
byte[] clientPubKey = null;
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PUBLICKEY>") == 0) {
clientPubKey = fromNetworkByte();
SendACK(); // Send ACK
returnData = crypt.encrypt("<PubKey-GOOD>");
network.Send(returnData);
RecieveACK(); // Wait for ACK
} else {
mylog.out("ERROR", "Failed to receieve client public key.");
}
// Send server public key to client
network.Send(crypt.encrypt("<PUBLICKEY>"));
RecieveACK(); // Wait for ACK
network.Send(crypt.encrypt(myDH.GetPublicKeyBF()));
RecieveACK(); // Wait for ACK
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PubKey-GOOD>") != 0) {
mylog.out("ERROR", "Client has failed to acknowledge server public key!");
}
// Use server DH public key to generate shared secret
myDH.DHPhase2(myDH.CraftPublicKey(clientPubKey), "Client");
// Final verification
// System.out.println("Shared Secret (Hex): " +
// myDH.GetSharedSecret(10));
crypt.ReKey(myDH.GetSharedSecret(10), "Client");
} else if (fromClient.length() == 0) {
// Send back empty data
craftReturn = "";
returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
} else {
// Anything else, respond with error text
mylog.out("INFO", "Not a supported request [" + fromClient + "]");
craftReturn = "Not a supported request [" + fromClient + "]";
returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
}
try {
// Have the thread sleep for 1 second to lower CPU load
Thread.sleep(1000);
} catch (InterruptedException e) {
mylog.out("ERROR", "Failed to have the thread sleep.");
e.printStackTrace();
}
}
// Tear down bound I/O
network.BringDown();
// Close this socket
try {
socket.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close SOCKET within SERVER THREAD");
}
}
/**
* Reads a string from the network
*
* @return
*/
private String fromNetwork() {
String decryptedValue = null;
byte[] initialValue = network.ReceiveByte();
if (initialValue == null) {
mylog.out("WARN", "Client disconnected abruptly");
}
decryptedValue = crypt.decrypt(initialValue);
if (decryptedValue == null) {
mylog.out("WARN", "Client disconnected abruptly");
} else if (decryptedValue.compareToIgnoreCase("quit") == 0) {
mylog.out("WARN", "Client disconnected abruptly");
}
return decryptedValue;
}
/**
* Read bytes from the network
*
* @return
*/
private byte[] fromNetworkByte() {
byte[] decryptedValue = null;
byte[] initialValue = network.ReceiveByte();
if (initialValue == null) {
mylog.out("WARN", "Client disconnected abruptly");
}
decryptedValue = crypt.decryptByte(initialValue);
if (decryptedValue == null) {
mylog.out("WARN", "Client disconnected abruptly");
}
return decryptedValue;
}
/**
* Provides message synchronization
*/
private void SendACK() {
network.Send(crypt.encrypt("<ACK>"));
if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) {
mylog.out("ERROR", "Partner failed to ACK");
}
}
/**
* Provides message synchronization
*/
private void RecieveACK() {
if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) {
mylog.out("ERROR", "Partner failed to ACK");
}
network.Send(crypt.encrypt("<ACK>"));
}
}
| false | true | public void run() {
// TODO Refactor so this can be used for both the SERVER and the DROPOFF
// UID is just an iterator from the server side
// It has no bearing on anything besides the raw question
// "How many have connected to this single runtime?"
mylog.out("INFO", "Establishing session with client number [" + UID + "]");
// Load and save the cleints IP and port for future UUID creation
SocketAddress theirAddress = socket.getRemoteSocketAddress();
String ClientIP = theirAddress.toString();
ClientIP = ClientIP.replace("/", "");
// Bind I/O to the socket
network.BringUp(socket);
// Prep
String fromClient = null;
// Activate crypto
crypt = new Crypto(mylog, subject.GetPSK(), "Client");
byte[] fetched = network.ReceiveByte();
String dec = crypt.decrypt(fetched);
String craftReturn = dec + "<S>";
mylog.out("INFO", "Validating encryption with handshake.");
byte[] returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
// Main Loop
while (!socket.isClosed()) {
// Collect data sent over the network
fetched = network.ReceiveByte();
if (fetched == null) {
mylog.out("WARN", "Client disconnected abruptly");
break;
}
// Decrypt sent data
fromClient = crypt.decrypt(fetched);
// Pre-calculate meta data from passed arguments
// (for job distribution)
String ClientName = ClientIP;
boolean ClientMetaSet = false;
String ClientOS = "";
int ClientSecurityLevel = 0;
if (fromClient == null) {
mylog.out("WARN", "Client disconnected abruptly");
break;
}
// If this is a SERVER
if (ServerMode) {
// Preliminary scanning and data input manipulation
if (fromClient.toLowerCase().contains("job")) {
String[] CHOP = fromClient.split(":");
// Add the random number passed to us to the servers UID of
// this client session to create a reasonable UUID
if (CHOP.length == 4) {
// Extract meta data
if (!ClientMetaSet) {
// Only set this once
ClientName = ClientName + CHOP[1];
ClientOS = CHOP[2];
ClientSecurityLevel = Integer.parseInt(CHOP[3]);
ClientMetaSet = true;
}
// Assign a job to the client
mylog.out("INFO", "Client [" + ClientName + "] with security level [" + ClientSecurityLevel
+ "] reuested a job for [" + ClientOS + "]");
synchronized (JobLock) {
String work = JobQueue.Assign(ClientName, ClientOS, ClientSecurityLevel);
returnData = crypt.encrypt(work);
network.Send(returnData);
if (work.length() > 0) {
mylog.out("INFO", "JobOut:[" + work + "]");
mylog.out("INFO", "[" + JobQueue.UnassignedCount()
+ "] unassigned jobs are left in the queue");
mylog.out("INFO", "[" + JobQueue.AssignedCount() + "] jobs are in progress");
} else {
mylog.out("WARN", "There are no jobs for [" + ClientOS + "] with Security Level ["
+ ClientSecurityLevel + "]");
}
}
} else {
// The client failed to send all of the meta data we
// need, so abort the job request
fromClient = "";
mylog.out("INFO", "Job request failed. Missing meta data in request.");
}
} else if (fromClient.toLowerCase().contains("workdone")) {
if (ClientMetaSet) {
synchronized (JobLock) {
String work = JobQueue.Signoff(ClientName);
if (work.equalsIgnoreCase("Failed")) {
// The job was not able to be acknowledged
mylog.out("WARN", "Client [" + ClientName
+ "] job complete was NOT acknowledged (no was job assigned previously).");
} else {
mylog.out("INFO", "Client [" + ClientName + "] job was acknowledged.");
}
work = "Acknowledged";
returnData = crypt.encrypt(work);
network.Send(returnData);
}
} else {
mylog.out("ERROR",
"Client is requesting to acknowledge job completion before being assigned a job");
}
}
} else {
// If this is a Drop Off point
}
// Common actions below (Server AND Drop Off point)
if (fromClient.compareToIgnoreCase("quit") == 0) {
mylog.out("INFO", "Client disconnected gracefully");
break;
} else if (fromClient.compareToIgnoreCase("<REKEY>") == 0) {
SendACK(); // Send ACK
String prime = null;
String base = null;
// Grab 1st value (should be handshake for PRIME)
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PRIME>") == 0) {
prime = fromNetwork();
SendACK(); // Send ACK
} else {
mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive PRIME).");
}
// Grab 2nd value (should be handshake for BASE)
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<BASE>") == 0) {
base = fromNetwork();
SendACK(); // Send ACK
} else {
mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive BASE).");
}
// Use received values to start DH
DH myDH = new DH(mylog, prime, 16, base, 16);
// Send rekeying ack
returnData = crypt.encrypt("<REKEY-STARTING>");
network.Send(returnData);
RecieveACK(); // Wait for ACK
// Perform phase1
myDH.DHPhase1();
// Receive client public key
byte[] clientPubKey = null;
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PUBLICKEY>") == 0) {
clientPubKey = fromNetworkByte();
SendACK(); // Send ACK
returnData = crypt.encrypt("<PubKey-GOOD>");
network.Send(returnData);
RecieveACK(); // Wait for ACK
} else {
mylog.out("ERROR", "Failed to receieve client public key.");
}
// Send server public key to client
network.Send(crypt.encrypt("<PUBLICKEY>"));
RecieveACK(); // Wait for ACK
network.Send(crypt.encrypt(myDH.GetPublicKeyBF()));
RecieveACK(); // Wait for ACK
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PubKey-GOOD>") != 0) {
mylog.out("ERROR", "Client has failed to acknowledge server public key!");
}
// Use server DH public key to generate shared secret
myDH.DHPhase2(myDH.CraftPublicKey(clientPubKey), "Client");
// Final verification
// System.out.println("Shared Secret (Hex): " +
// myDH.GetSharedSecret(10));
crypt.ReKey(myDH.GetSharedSecret(10), "Client");
} else if (fromClient.length() == 0) {
// Send back empty data
craftReturn = "";
returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
} else {
// Anything else, respond with error text
mylog.out("INFO", "Not a supported request [" + fromClient + "]");
craftReturn = "Not a supported request [" + fromClient + "]";
returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
}
try {
// Have the thread sleep for 1 second to lower CPU load
Thread.sleep(1000);
} catch (InterruptedException e) {
mylog.out("ERROR", "Failed to have the thread sleep.");
e.printStackTrace();
}
}
// Tear down bound I/O
network.BringDown();
// Close this socket
try {
socket.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close SOCKET within SERVER THREAD");
}
}
| public void run() {
// TODO Refactor so this can be used for both the SERVER and the DROPOFF
// UID is just an iterator from the server side
// It has no bearing on anything besides the raw question
// "How many have connected to this single runtime?"
mylog.out("INFO", "Establishing session with client number [" + UID + "]");
// Load and save the cleints IP and port for future UUID creation
SocketAddress theirAddress = socket.getRemoteSocketAddress();
String ClientIP = theirAddress.toString();
ClientIP = ClientIP.replace("/", "");
// Bind I/O to the socket
network.BringUp(socket);
// Prep
String fromClient = null;
boolean NoSend = false;
// Activate crypto
crypt = new Crypto(mylog, subject.GetPSK(), "Client");
byte[] fetched = network.ReceiveByte();
String dec = crypt.decrypt(fetched);
String craftReturn = dec + "<S>";
mylog.out("INFO", "Validating encryption with handshake.");
byte[] returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
// Main Loop
while (!socket.isClosed()) {
// Collect data sent over the network
fetched = network.ReceiveByte();
if (fetched == null) {
mylog.out("WARN", "Client disconnected abruptly");
break;
}
// Decrypt sent data
fromClient = crypt.decrypt(fetched);
// Pre-calculate meta data from passed arguments
// (for job distribution)
String ClientName = ClientIP;
boolean ClientMetaSet = false;
String ClientOS = "";
int ClientSecurityLevel = 0;
if (fromClient == null) {
mylog.out("WARN", "Client disconnected abruptly");
break;
}
// If this is a SERVER
if (ServerMode) {
// Preliminary scanning and data input manipulation
if (fromClient.toLowerCase().contains("job")) {
String[] CHOP = fromClient.split(":");
// Add the random number passed to us to the servers UID of
// this client session to create a reasonable UUID
if (CHOP.length == 4) {
// Extract meta data
if (!ClientMetaSet) {
// Only set this once
ClientName = ClientName + CHOP[1];
ClientOS = CHOP[2];
ClientSecurityLevel = Integer.parseInt(CHOP[3]);
ClientMetaSet = true;
}
// Assign a job to the client
mylog.out("INFO", "Client [" + ClientName + "] with security level [" + ClientSecurityLevel
+ "] reuested a job for [" + ClientOS + "]");
synchronized (JobLock) {
NoSend = true; // Do not send a secondary response
String work = JobQueue.Assign(ClientName, ClientOS, ClientSecurityLevel);
returnData = crypt.encrypt(work);
network.Send(returnData);
if (work.length() > 0) {
mylog.out("INFO", "JobOut:[" + work + "]");
mylog.out("INFO", "[" + JobQueue.UnassignedCount()
+ "] unassigned jobs are left in the queue");
mylog.out("INFO", "[" + JobQueue.AssignedCount() + "] jobs are in progress");
} else {
mylog.out("WARN", "There are no jobs for [" + ClientOS + "] with Security Level ["
+ ClientSecurityLevel + "]");
}
}
} else {
// The client failed to send all of the meta data we
// need, so abort the job request
fromClient = "";
mylog.out("INFO", "Job request failed. Missing meta data in request.");
}
} else if (fromClient.toLowerCase().contains("workdone")) {
if (ClientMetaSet) {
synchronized (JobLock) {
NoSend = true; // Do not send a secondary response
String work = JobQueue.Signoff(ClientName);
if (work.equalsIgnoreCase("Failed")) {
// The job was not able to be acknowledged
mylog.out("WARN", "Client [" + ClientName
+ "] job complete was NOT acknowledged (no was job assigned previously).");
} else {
mylog.out("INFO", "Client [" + ClientName + "] job was acknowledged.");
}
work = "Acknowledged";
returnData = crypt.encrypt(work);
network.Send(returnData);
}
} else {
mylog.out("ERROR",
"Client is requesting to acknowledge job completion before being assigned a job");
}
}
} else {
// If this is a Drop Off point
}
// Common actions below (Server AND Drop Off point)
if (NoSend) {
// We do not send anything this time as the transmission to the
// client was already handled above
NoSend = false;
} else if (fromClient.compareToIgnoreCase("quit") == 0) {
mylog.out("INFO", "Client disconnected gracefully");
break;
} else if (fromClient.compareToIgnoreCase("<REKEY>") == 0) {
SendACK(); // Send ACK
String prime = null;
String base = null;
// Grab 1st value (should be handshake for PRIME)
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PRIME>") == 0) {
prime = fromNetwork();
SendACK(); // Send ACK
} else {
mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive PRIME).");
}
// Grab 2nd value (should be handshake for BASE)
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<BASE>") == 0) {
base = fromNetwork();
SendACK(); // Send ACK
} else {
mylog.out("ERROR", "Failed proper DH handshake over the network (failed to receive BASE).");
}
// Use received values to start DH
DH myDH = new DH(mylog, prime, 16, base, 16);
// Send rekeying ack
returnData = crypt.encrypt("<REKEY-STARTING>");
network.Send(returnData);
RecieveACK(); // Wait for ACK
// Perform phase1
myDH.DHPhase1();
// Receive client public key
byte[] clientPubKey = null;
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PUBLICKEY>") == 0) {
clientPubKey = fromNetworkByte();
SendACK(); // Send ACK
returnData = crypt.encrypt("<PubKey-GOOD>");
network.Send(returnData);
RecieveACK(); // Wait for ACK
} else {
mylog.out("ERROR", "Failed to receieve client public key.");
}
// Send server public key to client
network.Send(crypt.encrypt("<PUBLICKEY>"));
RecieveACK(); // Wait for ACK
network.Send(crypt.encrypt(myDH.GetPublicKeyBF()));
RecieveACK(); // Wait for ACK
fromClient = fromNetwork();
SendACK(); // Send ACK
if (fromClient.compareToIgnoreCase("<PubKey-GOOD>") != 0) {
mylog.out("ERROR", "Client has failed to acknowledge server public key!");
}
// Use server DH public key to generate shared secret
myDH.DHPhase2(myDH.CraftPublicKey(clientPubKey), "Client");
// Final verification
// System.out.println("Shared Secret (Hex): " +
// myDH.GetSharedSecret(10));
crypt.ReKey(myDH.GetSharedSecret(10), "Client");
} else if (fromClient.length() == 0) {
// Send back empty data
craftReturn = "";
returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
} else {
// Anything else, respond with error text
mylog.out("INFO", "Not a supported request [" + fromClient + "]");
craftReturn = "Not a supported request [" + fromClient + "]";
returnData = crypt.encrypt(craftReturn);
network.Send(returnData);
}
try {
// Have the thread sleep for 1 second to lower CPU load
Thread.sleep(1000);
} catch (InterruptedException e) {
mylog.out("ERROR", "Failed to have the thread sleep.");
e.printStackTrace();
}
}
// Tear down bound I/O
network.BringDown();
// Close this socket
try {
socket.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close SOCKET within SERVER THREAD");
}
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/hmpp/transformations/PrepareHMPPAnnotations.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/hmpp/transformations/PrepareHMPPAnnotations.java
index e3cc093f7..1156512fc 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/hmpp/transformations/PrepareHMPPAnnotations.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/hmpp/transformations/PrepareHMPPAnnotations.java
@@ -1,123 +1,125 @@
/*
* Copyright (c) 2010-2011, IRISA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IRISA 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 net.sf.orcc.backends.c.hmpp.transformations;
import java.util.Arrays;
import java.util.List;
import net.sf.orcc.ir.BlockWhile;
import net.sf.orcc.ir.ExprList;
import net.sf.orcc.ir.ExprVar;
import net.sf.orcc.ir.IrFactory;
import net.sf.orcc.ir.util.AbstractIrVisitor;
import net.sf.orcc.util.Attribute;
/**
* This class add a list of variables to attributes on while blocks annotated
* with hmppcg "gridify" pragma. These reference to variables is used later (see
* SetHMPPAnnotations) to update attribute params and ensure parameters will be
* consistent with variables in code, even if they have been modified by another
* transformation.
*
* @author Jérôme Gorin
*
*/
public class PrepareHMPPAnnotations extends AbstractIrVisitor<Void> {
/**
* This visitor search in a model element for a given variable name. When it
* ends, it can return a reference to the corresponding Var object.
*
* @author Jérôme Gorin
*
*/
private class ExprVarGetter extends AbstractIrVisitor<Void> {
private ExprVar result;
private String varName;
public ExprVarGetter() {
// Visit also expressions
super(true);
}
public void setVariableName(String varName) {
this.varName = varName;
}
@Override
public Void caseExprVar(ExprVar expr) {
if (expr.getUse().getVariable().getName().compareTo(varName) == 0) {
result = expr;
}
return null;
}
public ExprVar getResult() {
return result;
}
}
@Override
public Void caseBlockWhile(BlockWhile blockWhile) {
super.caseBlockWhile(blockWhile);
Attribute attribute = blockWhile.getAttribute("gridify");
ExprVarGetter exprVarGetter = new ExprVarGetter();
if (attribute != null && attribute.hasAttribute("params")) {
List<String> varNames = Arrays.asList(attribute
.getAttribute("params").getStringValue().split(","));
for (String varName : varNames) {
exprVarGetter.setVariableName(varName);
exprVarGetter.doSwitch(blockWhile);
if (exprVarGetter.getResult() != null) {
if (attribute.getAttribute("params").getContainedValue() == null) {
attribute.getAttribute("params").setContainedValue(
IrFactory.eINSTANCE.createExprList());
}
ExprList variablesList = (ExprList) attribute.getAttribute(
"params").getContainedValue();
- variablesList.getValue().add(exprVarGetter.getResult());
+ variablesList.getValue().add(
+ IrFactory.eINSTANCE.createExprVar(exprVarGetter
+ .getResult().getUse().getVariable()));
}
}
}
return null;
}
}
| true | true | public Void caseBlockWhile(BlockWhile blockWhile) {
super.caseBlockWhile(blockWhile);
Attribute attribute = blockWhile.getAttribute("gridify");
ExprVarGetter exprVarGetter = new ExprVarGetter();
if (attribute != null && attribute.hasAttribute("params")) {
List<String> varNames = Arrays.asList(attribute
.getAttribute("params").getStringValue().split(","));
for (String varName : varNames) {
exprVarGetter.setVariableName(varName);
exprVarGetter.doSwitch(blockWhile);
if (exprVarGetter.getResult() != null) {
if (attribute.getAttribute("params").getContainedValue() == null) {
attribute.getAttribute("params").setContainedValue(
IrFactory.eINSTANCE.createExprList());
}
ExprList variablesList = (ExprList) attribute.getAttribute(
"params").getContainedValue();
variablesList.getValue().add(exprVarGetter.getResult());
}
}
}
return null;
}
| public Void caseBlockWhile(BlockWhile blockWhile) {
super.caseBlockWhile(blockWhile);
Attribute attribute = blockWhile.getAttribute("gridify");
ExprVarGetter exprVarGetter = new ExprVarGetter();
if (attribute != null && attribute.hasAttribute("params")) {
List<String> varNames = Arrays.asList(attribute
.getAttribute("params").getStringValue().split(","));
for (String varName : varNames) {
exprVarGetter.setVariableName(varName);
exprVarGetter.doSwitch(blockWhile);
if (exprVarGetter.getResult() != null) {
if (attribute.getAttribute("params").getContainedValue() == null) {
attribute.getAttribute("params").setContainedValue(
IrFactory.eINSTANCE.createExprList());
}
ExprList variablesList = (ExprList) attribute.getAttribute(
"params").getContainedValue();
variablesList.getValue().add(
IrFactory.eINSTANCE.createExprVar(exprVarGetter
.getResult().getUse().getVariable()));
}
}
}
return null;
}
|
diff --git a/Cluster/PowerMaster/src/NodeJS/Statistics/AsyncStats.java b/Cluster/PowerMaster/src/NodeJS/Statistics/AsyncStats.java
index 2a295c4..5cd1655 100644
--- a/Cluster/PowerMaster/src/NodeJS/Statistics/AsyncStats.java
+++ b/Cluster/PowerMaster/src/NodeJS/Statistics/AsyncStats.java
@@ -1,147 +1,148 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package NodeJS.Statistics;
import Module.Aplication;
import Module.DataBase.Database;
import Module.WebHTTP.SolverCreator;
import genetics.GenericSolver;
import genetics.Individual;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import powermaster.GeneticEvents;
import powermaster.PowerMaster;
import powermaster.SaveStatus;
import powermaster.SolverThread;
import utils.ComparatorIndividual;
import utils.PopulationUtils;
/**
*
* @author Joao
*/
public class AsyncStats extends Thread {
AtomicInteger numThreads;
int period;
int aux;
int idClient;
int idProblem;
volatile boolean Stop;
private SolverThread[] arrayThread;
public AsyncStats(int period, int idClient, int idProblem, JSONObject input) throws InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, JSONException {
this.period = period - 1;
this.aux = period;
this.idClient = idClient;
this.idProblem = idProblem;
this.setName("AsyncThread");
this.Stop = false;
numThreads = new AtomicInteger(PowerMaster.NUM_THREADS);
arrayThread = new SolverThread[PowerMaster.NUM_THREADS];
for (int i = 0; i < arrayThread.length; i++) {
GenericSolver solver = SolverCreator.CreateSolver(input);
solver.SetEvents(new GeneticEvents(PowerMaster.INTERVAL_PART, idClient, idProblem));
arrayThread[i] = new SolverThread(solver, numThreads);
arrayThread[i].setName("" + i);
arrayThread[i].start();
}
//this.start();
}
public synchronized void Stop() throws FileNotFoundException, IOException {
SaveStatus save = new SaveStatus(idClient + "_" + idProblem);
for (int i = 0; i < arrayThread.length; i++) {
save.AddPopulation(arrayThread[i].Stop());
}
Stop = true;
FileOutputStream fos = new FileOutputStream("Pops/" + idClient + "_" + idProblem);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(save);
oos.close();
//clients.remove(save);
}
public void getAllUniqueIndividuals(double fitness){
TreeSet result = new TreeSet(new ComparatorIndividual());
for (int i = 0; i < arrayThread.length; i++) {
//Entra uma collection
result.addAll( arrayThread[i].getUniqueIndividuals(fitness));
}
for (Object ind : result) {
System.out.println("\n\n"+ind.toString()+"\n\n");
}
}
/**
* Método para percorrer todas as threads e procurar o maior double
*/
public double getBestIndividual(){
double maxFitness=0,aux=0;
for (int i = 0; i < arrayThread.length; i++) {
if((aux=PopulationUtils.getBestFitness(arrayThread[i].getPopulation()))>maxFitness){
maxFitness=aux;
}
}
return maxFitness;
}
@Override
public void run() {
//Database db = new Database("power", "_p55!gv{7MJ]}dIpPk7n1*0-,hq(PD", "127.0.0.1");
Database db = new Database("power", "_p55!gv{7MJ]}dIpPk7n1*0-,hq(PD", "code.dei.estt.ipt.pt", "powercomputing");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(AsyncStats.class.getName()).log(Level.SEVERE, null, ex);
}
while (!Stop) {
try {
int result_count = db.ExecuteCountQuery(period, idClient, idProblem);
int numThread = numThreads.get();
// System.out.println("Async| Period: " + period + " Threads working: " + numThread + " Result count: " + result_count + " Cliente: " + idClient + " Problema: " + idProblem);
if (result_count == 0 && numThread == 0) {
Aplication.nodeJS.Emit("end", this.period, this.idClient, this.idProblem);
System.out.println("Async Stop");
break;
}
if (result_count >= numThread) {
+ getAllUniqueIndividuals(getBestIndividual());
//System.out.println("Fechado"+Aplication.db.Connection.isClosed());
boolean temp = db.ExecuteMedia(period, idClient, idProblem,this);
//System.out.println("Async Insertion| Iteration:" + period);
Aplication.nodeJS.Emit("run", this.period, this.idClient, this.idProblem);
period = period + aux;
}
Thread.sleep(750);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error - Sync Class " + e);
}
}
}
}
| true | true | public void run() {
//Database db = new Database("power", "_p55!gv{7MJ]}dIpPk7n1*0-,hq(PD", "127.0.0.1");
Database db = new Database("power", "_p55!gv{7MJ]}dIpPk7n1*0-,hq(PD", "code.dei.estt.ipt.pt", "powercomputing");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(AsyncStats.class.getName()).log(Level.SEVERE, null, ex);
}
while (!Stop) {
try {
int result_count = db.ExecuteCountQuery(period, idClient, idProblem);
int numThread = numThreads.get();
// System.out.println("Async| Period: " + period + " Threads working: " + numThread + " Result count: " + result_count + " Cliente: " + idClient + " Problema: " + idProblem);
if (result_count == 0 && numThread == 0) {
Aplication.nodeJS.Emit("end", this.period, this.idClient, this.idProblem);
System.out.println("Async Stop");
break;
}
if (result_count >= numThread) {
//System.out.println("Fechado"+Aplication.db.Connection.isClosed());
boolean temp = db.ExecuteMedia(period, idClient, idProblem,this);
//System.out.println("Async Insertion| Iteration:" + period);
Aplication.nodeJS.Emit("run", this.period, this.idClient, this.idProblem);
period = period + aux;
}
Thread.sleep(750);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error - Sync Class " + e);
}
}
}
| public void run() {
//Database db = new Database("power", "_p55!gv{7MJ]}dIpPk7n1*0-,hq(PD", "127.0.0.1");
Database db = new Database("power", "_p55!gv{7MJ]}dIpPk7n1*0-,hq(PD", "code.dei.estt.ipt.pt", "powercomputing");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(AsyncStats.class.getName()).log(Level.SEVERE, null, ex);
}
while (!Stop) {
try {
int result_count = db.ExecuteCountQuery(period, idClient, idProblem);
int numThread = numThreads.get();
// System.out.println("Async| Period: " + period + " Threads working: " + numThread + " Result count: " + result_count + " Cliente: " + idClient + " Problema: " + idProblem);
if (result_count == 0 && numThread == 0) {
Aplication.nodeJS.Emit("end", this.period, this.idClient, this.idProblem);
System.out.println("Async Stop");
break;
}
if (result_count >= numThread) {
getAllUniqueIndividuals(getBestIndividual());
//System.out.println("Fechado"+Aplication.db.Connection.isClosed());
boolean temp = db.ExecuteMedia(period, idClient, idProblem,this);
//System.out.println("Async Insertion| Iteration:" + period);
Aplication.nodeJS.Emit("run", this.period, this.idClient, this.idProblem);
period = period + aux;
}
Thread.sleep(750);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error - Sync Class " + e);
}
}
}
|
diff --git a/core/src/main/java/org/jclouds/http/commands/callables/xml/ParseSax.java b/core/src/main/java/org/jclouds/http/commands/callables/xml/ParseSax.java
index 8e70f69b9..281d4be06 100644
--- a/core/src/main/java/org/jclouds/http/commands/callables/xml/ParseSax.java
+++ b/core/src/main/java/org/jclouds/http/commands/callables/xml/ParseSax.java
@@ -1,123 +1,125 @@
/**
*
* Copyright (C) 2009 Global Cloud Specialists, Inc. <[email protected]>
*
* ====================================================================
* 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.jclouds.http.commands.callables.xml;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.jclouds.http.HttpException;
import org.jclouds.http.HttpFutureCommand;
import org.jclouds.util.Utils;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import static org.jclouds.http.HttpConstants.PROPERTY_SAX_DEBUG;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.name.Named;
/**
* This object will parse the body of an HttpResponse and return the result of type <T> back to the
* caller.
*
* @author Adrian Cole
*/
public class ParseSax<T> extends HttpFutureCommand.ResponseCallable<T> {
private final XMLReader parser;
private final HandlerWithResult<T> handler;
@Inject(optional = true)
@Named(PROPERTY_SAX_DEBUG)
private boolean suckFirst = false;
@Inject
public ParseSax(XMLReader parser, @Assisted HandlerWithResult<T> handler) {
super();
this.parser = checkNotNull(parser, "parser");
this.handler = checkNotNull(handler, "handler");
}
public T call() throws HttpException {
InputStream input = null;
try {
input = getResponse().getContent();
if (input != null) {
return parse(input);
} else {
throw new HttpException("No input to parse");
}
} catch (Exception e) {
Utils.<HttpException> rethrowIfRuntimeOrSameType(e);
throw new HttpException("Error parsing input for " + getResponse(), e);
}
}
public T parse(InputStream xml) throws HttpException {
parseAndCloseStream(xml, getHandler());
return getHandler().getResult();
}
private void parseAndCloseStream(InputStream xml, ContentHandler handler) throws HttpException {
parser.setContentHandler(handler);
String response = null;
try {
if (suckFirst) {
response = IOUtils.toString(xml);
logger.trace("received content %n%s", response);
IOUtils.closeQuietly(xml);
xml = IOUtils.toInputStream(response);
}
- parser.parse(new InputSource(xml));
+ InputSource input = new InputSource(xml);
+ input.setEncoding("UTF-8");
+ parser.parse(input);
} catch (Exception e) {
StringBuilder message = new StringBuilder();
message.append("Error parsing input for ").append(handler);
if (response != null) {
message.append("\n").append(response);
}
logger.error(e, message.toString());
if (!(e instanceof NullPointerException))
Utils.<HttpException> rethrowIfRuntimeOrSameType(e);
throw new HttpException(message.toString(), e);
} finally {
IOUtils.closeQuietly(xml);
}
}
public HandlerWithResult<T> getHandler() {
return handler;
}
/**
* Handler that produces a useable domain object accessible after parsing completes.
*
* @author Adrian Cole
*/
public abstract static class HandlerWithResult<T> extends DefaultHandler {
public abstract T getResult();
}
}
| true | true | private void parseAndCloseStream(InputStream xml, ContentHandler handler) throws HttpException {
parser.setContentHandler(handler);
String response = null;
try {
if (suckFirst) {
response = IOUtils.toString(xml);
logger.trace("received content %n%s", response);
IOUtils.closeQuietly(xml);
xml = IOUtils.toInputStream(response);
}
parser.parse(new InputSource(xml));
} catch (Exception e) {
StringBuilder message = new StringBuilder();
message.append("Error parsing input for ").append(handler);
if (response != null) {
message.append("\n").append(response);
}
logger.error(e, message.toString());
if (!(e instanceof NullPointerException))
Utils.<HttpException> rethrowIfRuntimeOrSameType(e);
throw new HttpException(message.toString(), e);
} finally {
IOUtils.closeQuietly(xml);
}
}
| private void parseAndCloseStream(InputStream xml, ContentHandler handler) throws HttpException {
parser.setContentHandler(handler);
String response = null;
try {
if (suckFirst) {
response = IOUtils.toString(xml);
logger.trace("received content %n%s", response);
IOUtils.closeQuietly(xml);
xml = IOUtils.toInputStream(response);
}
InputSource input = new InputSource(xml);
input.setEncoding("UTF-8");
parser.parse(input);
} catch (Exception e) {
StringBuilder message = new StringBuilder();
message.append("Error parsing input for ").append(handler);
if (response != null) {
message.append("\n").append(response);
}
logger.error(e, message.toString());
if (!(e instanceof NullPointerException))
Utils.<HttpException> rethrowIfRuntimeOrSameType(e);
throw new HttpException(message.toString(), e);
} finally {
IOUtils.closeQuietly(xml);
}
}
|
diff --git a/common/logisticspipes/modules/ModuleQuickSort.java b/common/logisticspipes/modules/ModuleQuickSort.java
index 8bc64082..aa3d141a 100644
--- a/common/logisticspipes/modules/ModuleQuickSort.java
+++ b/common/logisticspipes/modules/ModuleQuickSort.java
@@ -1,130 +1,130 @@
package logisticspipes.modules;
import java.util.List;
import logisticspipes.interfaces.IChassiePowerProvider;
import logisticspipes.interfaces.ILogisticsModule;
import logisticspipes.interfaces.ISendRoutedItem;
import logisticspipes.interfaces.IWorldProvider;
import logisticspipes.interfaces.routing.IFilter;
import logisticspipes.logisticspipes.IInventoryProvider;
import logisticspipes.pipefxhandlers.Particles;
import logisticspipes.proxy.MainProxy;
import logisticspipes.utils.Pair3;
import logisticspipes.utils.SinkReply;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class ModuleQuickSort implements ILogisticsModule {
private final int stalledDelay = 24;
private final int normalDelay = 6;
private int currentTick = 0;
private boolean stalled;
private int lastStackLookedAt = 0;
private int lastSuceededStack = 0;
private IInventoryProvider _invProvider;
private ISendRoutedItem _itemSender;
private IChassiePowerProvider _power;
private int xCoord;
private int yCoord;
private int zCoord;
private IWorldProvider _world;
public ModuleQuickSort() {}
@Override
public void registerHandler(IInventoryProvider invProvider, ISendRoutedItem itemSender, IWorldProvider world, IChassiePowerProvider powerprovider) {
_invProvider = invProvider;
_itemSender = itemSender;
_power = powerprovider;
_world = world;
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {}
@Override
public SinkReply sinksItem(ItemStack item, int bestPriority, int bestCustomPriority) {
return null;
}
@Override
public ILogisticsModule getSubModule(int slot) {
return null;
}
@Override
public void tick() {
if (--currentTick > 0) return;
if(stalled)
currentTick = stalledDelay;
else
currentTick = normalDelay;
//Extract Item
IInventory targetInventory = _invProvider.getPointedInventory();
if (targetInventory == null) return;
if (targetInventory.getSizeInventory() < 27) return;
if(!_power.canUseEnergy(500)) {
stalled = true;
return;
}
if(lastSuceededStack >= targetInventory.getSizeInventory())
lastSuceededStack = 0;
//incremented at the end of the previous loop.
if (lastStackLookedAt >= targetInventory.getSizeInventory())
lastStackLookedAt = 0;
ItemStack stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
while(stackToSend==null) {
lastStackLookedAt++;
- stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
if (lastStackLookedAt >= targetInventory.getSizeInventory())
lastStackLookedAt = 0;
+ stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
if(lastStackLookedAt == lastSuceededStack) {
stalled = true;
return; // then we have been around the list without sending, halt for now
}
}
Pair3<Integer, SinkReply, List<IFilter>> reply = _itemSender.hasDestination(stackToSend, false);
if (reply == null) {
if(lastStackLookedAt == lastSuceededStack) {
stalled = true;
}
lastStackLookedAt++;
return;
}
if(!_power.useEnergy(500)) {
stalled = true;
lastStackLookedAt++;
return;
}
lastSuceededStack=lastStackLookedAt;
lastStackLookedAt++;
stalled = false;
_itemSender.sendStack(stackToSend, reply);
MainProxy.sendSpawnParticlePacket(Particles.OrangeParticle, xCoord, yCoord, zCoord, _world.getWorld(), 8);
targetInventory.setInventorySlotContents(lastStackLookedAt, null);
}
@Override
public void registerPosition(int xCoord, int yCoord, int zCoord, int slot) {
this.xCoord = xCoord;
this.yCoord = yCoord;
this.zCoord = zCoord;
}
}
| false | true | public void tick() {
if (--currentTick > 0) return;
if(stalled)
currentTick = stalledDelay;
else
currentTick = normalDelay;
//Extract Item
IInventory targetInventory = _invProvider.getPointedInventory();
if (targetInventory == null) return;
if (targetInventory.getSizeInventory() < 27) return;
if(!_power.canUseEnergy(500)) {
stalled = true;
return;
}
if(lastSuceededStack >= targetInventory.getSizeInventory())
lastSuceededStack = 0;
//incremented at the end of the previous loop.
if (lastStackLookedAt >= targetInventory.getSizeInventory())
lastStackLookedAt = 0;
ItemStack stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
while(stackToSend==null) {
lastStackLookedAt++;
stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
if (lastStackLookedAt >= targetInventory.getSizeInventory())
lastStackLookedAt = 0;
if(lastStackLookedAt == lastSuceededStack) {
stalled = true;
return; // then we have been around the list without sending, halt for now
}
}
Pair3<Integer, SinkReply, List<IFilter>> reply = _itemSender.hasDestination(stackToSend, false);
if (reply == null) {
if(lastStackLookedAt == lastSuceededStack) {
stalled = true;
}
lastStackLookedAt++;
return;
}
if(!_power.useEnergy(500)) {
stalled = true;
lastStackLookedAt++;
return;
}
lastSuceededStack=lastStackLookedAt;
lastStackLookedAt++;
stalled = false;
_itemSender.sendStack(stackToSend, reply);
MainProxy.sendSpawnParticlePacket(Particles.OrangeParticle, xCoord, yCoord, zCoord, _world.getWorld(), 8);
targetInventory.setInventorySlotContents(lastStackLookedAt, null);
}
| public void tick() {
if (--currentTick > 0) return;
if(stalled)
currentTick = stalledDelay;
else
currentTick = normalDelay;
//Extract Item
IInventory targetInventory = _invProvider.getPointedInventory();
if (targetInventory == null) return;
if (targetInventory.getSizeInventory() < 27) return;
if(!_power.canUseEnergy(500)) {
stalled = true;
return;
}
if(lastSuceededStack >= targetInventory.getSizeInventory())
lastSuceededStack = 0;
//incremented at the end of the previous loop.
if (lastStackLookedAt >= targetInventory.getSizeInventory())
lastStackLookedAt = 0;
ItemStack stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
while(stackToSend==null) {
lastStackLookedAt++;
if (lastStackLookedAt >= targetInventory.getSizeInventory())
lastStackLookedAt = 0;
stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);
if(lastStackLookedAt == lastSuceededStack) {
stalled = true;
return; // then we have been around the list without sending, halt for now
}
}
Pair3<Integer, SinkReply, List<IFilter>> reply = _itemSender.hasDestination(stackToSend, false);
if (reply == null) {
if(lastStackLookedAt == lastSuceededStack) {
stalled = true;
}
lastStackLookedAt++;
return;
}
if(!_power.useEnergy(500)) {
stalled = true;
lastStackLookedAt++;
return;
}
lastSuceededStack=lastStackLookedAt;
lastStackLookedAt++;
stalled = false;
_itemSender.sendStack(stackToSend, reply);
MainProxy.sendSpawnParticlePacket(Particles.OrangeParticle, xCoord, yCoord, zCoord, _world.getWorld(), 8);
targetInventory.setInventorySlotContents(lastStackLookedAt, null);
}
|
diff --git a/core/src/main/java/org/apache/mahout/clustering/fuzzykmeans/FuzzyKMeansDriver.java b/core/src/main/java/org/apache/mahout/clustering/fuzzykmeans/FuzzyKMeansDriver.java
index 78aa4c09..f3c9d5eb 100644
--- a/core/src/main/java/org/apache/mahout/clustering/fuzzykmeans/FuzzyKMeansDriver.java
+++ b/core/src/main/java/org/apache/mahout/clustering/fuzzykmeans/FuzzyKMeansDriver.java
@@ -1,570 +1,573 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.clustering.fuzzykmeans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.common.io.Closeables;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.ToolRunner;
import org.apache.mahout.clustering.AbstractCluster;
import org.apache.mahout.clustering.Cluster;
import org.apache.mahout.clustering.ClusterObservations;
import org.apache.mahout.clustering.WeightedVectorWritable;
import org.apache.mahout.clustering.kmeans.RandomSeedGenerator;
import org.apache.mahout.common.AbstractJob;
import org.apache.mahout.common.HadoopUtil;
import org.apache.mahout.common.commandline.DefaultOptionCreator;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.common.distance.SquaredEuclideanDistanceMeasure;
import org.apache.mahout.common.iterator.sequencefile.PathFilters;
import org.apache.mahout.common.iterator.sequencefile.PathType;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirValueIterable;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileValueIterable;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileValueIterator;
import org.apache.mahout.math.VectorWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuzzyKMeansDriver extends AbstractJob {
public static final String M_OPTION = "m";
private static final Logger log = LoggerFactory.getLogger(FuzzyKMeansDriver.class);
public static void main(String[] args) throws Exception {
ToolRunner.run(new Configuration(), new FuzzyKMeansDriver(), args);
}
@Override
public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption(DefaultOptionCreator.distanceMeasureOption().create());
addOption(DefaultOptionCreator.clustersInOption()
.withDescription("The input centroids, as Vectors. Must be a SequenceFile of Writable, Cluster/Canopy. "
+ "If k is also specified, then a random set of vectors will be selected"
+ " and written out to this path first")
.create());
addOption(DefaultOptionCreator.numClustersOption()
.withDescription("The k in k-Means. If specified, then a random selection of k Vectors will be chosen"
+ " as the Centroid and written to the clusters input path.").create());
addOption(DefaultOptionCreator.convergenceOption().create());
addOption(DefaultOptionCreator.maxIterationsOption().create());
addOption(DefaultOptionCreator.overwriteOption().create());
addOption(M_OPTION, M_OPTION, "coefficient normalization factor, must be greater than 1", true);
addOption(DefaultOptionCreator.clusteringOption().create());
addOption(DefaultOptionCreator.emitMostLikelyOption().create());
addOption(DefaultOptionCreator.thresholdOption().create());
addOption(DefaultOptionCreator.methodOption().create());
if (parseArguments(args) == null) {
return -1;
}
Path input = getInputPath();
Path clusters = new Path(getOption(DefaultOptionCreator.CLUSTERS_IN_OPTION));
Path output = getOutputPath();
String measureClass = getOption(DefaultOptionCreator.DISTANCE_MEASURE_OPTION);
if (measureClass == null) {
measureClass = SquaredEuclideanDistanceMeasure.class.getName();
}
double convergenceDelta = Double.parseDouble(getOption(DefaultOptionCreator.CONVERGENCE_DELTA_OPTION));
float fuzziness = Float.parseFloat(getOption(M_OPTION));
int maxIterations = Integer.parseInt(getOption(DefaultOptionCreator.MAX_ITERATIONS_OPTION));
if (hasOption(DefaultOptionCreator.OVERWRITE_OPTION)) {
HadoopUtil.delete(getConf(), output);
}
boolean emitMostLikely = Boolean.parseBoolean(getOption(DefaultOptionCreator.EMIT_MOST_LIKELY_OPTION));
double threshold = Double.parseDouble(getOption(DefaultOptionCreator.THRESHOLD_OPTION));
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(measureClass).asSubclass(DistanceMeasure.class).newInstance();
if (hasOption(DefaultOptionCreator.NUM_CLUSTERS_OPTION)) {
- clusters = RandomSeedGenerator.buildRandom(getConf(), input, clusters, Integer.parseInt(parseArguments(args)
- .get(DefaultOptionCreator.NUM_CLUSTERS_OPTION)), measure);
+ clusters = RandomSeedGenerator.buildRandom(getConf(),
+ input,
+ clusters,
+ Integer.parseInt(getOption(DefaultOptionCreator.NUM_CLUSTERS_OPTION)),
+ measure);
}
boolean runClustering = hasOption(DefaultOptionCreator.CLUSTERING_OPTION);
boolean runSequential = getOption(DefaultOptionCreator.METHOD_OPTION).equalsIgnoreCase(
DefaultOptionCreator.SEQUENTIAL_METHOD);
run(getConf(),
input,
clusters,
output,
measure,
convergenceDelta,
maxIterations,
fuzziness,
runClustering,
emitMostLikely,
threshold,
runSequential);
return 0;
}
/**
* Iterate over the input vectors to produce clusters and, if requested, use the
* results of the final iteration to cluster the input vectors.
*
* @param input
* the directory pathname for input points
* @param clustersIn
* the directory pathname for initial & computed clusters
* @param output
* the directory pathname for output points
* @param convergenceDelta
* the convergence delta value
* @param maxIterations
* the maximum number of iterations
* @param m
* the fuzzification factor, see
* http://en.wikipedia.org/wiki/Data_clustering#Fuzzy_c-means_clustering
* @param runClustering
* true if points are to be clustered after iterations complete
* @param emitMostLikely
* a boolean if true emit only most likely cluster for each point
* @param threshold
* a double threshold value emits all clusters having greater pdf (emitMostLikely = false)
* @param runSequential if true run in sequential execution mode
*/
public static void run(Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
int maxIterations,
float m,
boolean runClustering,
boolean emitMostLikely,
double threshold,
boolean runSequential) throws IOException, ClassNotFoundException, InterruptedException {
Path clustersOut = buildClusters(new Configuration(),
input,
clustersIn,
output,
measure,
convergenceDelta,
maxIterations,
m,
runSequential);
if (runClustering) {
log.info("Clustering ");
clusterData(input,
clustersOut,
new Path(output, Cluster.CLUSTERED_POINTS_DIR),
measure,
convergenceDelta,
m,
emitMostLikely,
threshold,
runSequential);
}
}
/**
* Run the iteration using supplied arguments
* @param input
* the directory pathname for input points
* @param clustersIn
* the directory pathname for input clusters
* @param clustersOut
* the directory pathname for output clusters
* @param measureClass
* the classname of the DistanceMeasure
* @param convergenceDelta
* the convergence delta value
* @param m
* the fuzzification factor - see
* http://en.wikipedia.org/wiki/Data_clustering#Fuzzy_c-means_clustering
*
* @return true if the iteration successfully runs
* @throws ClassNotFoundException
* @throws InterruptedException
*/
private static boolean runIteration(Configuration conf,
Path input,
Path clustersIn,
Path clustersOut,
String measureClass,
double convergenceDelta,
float m) throws IOException, InterruptedException, ClassNotFoundException {
conf.set(FuzzyKMeansConfigKeys.CLUSTER_PATH_KEY, clustersIn.toString());
conf.set(FuzzyKMeansConfigKeys.DISTANCE_MEASURE_KEY, measureClass);
conf.set(FuzzyKMeansConfigKeys.CLUSTER_CONVERGENCE_KEY, String.valueOf(convergenceDelta));
conf.set(FuzzyKMeansConfigKeys.M_KEY, String.valueOf(m));
// these values don't matter during iterations as only used for clustering if requested
conf.set(FuzzyKMeansConfigKeys.EMIT_MOST_LIKELY_KEY, Boolean.toString(true));
conf.set(FuzzyKMeansConfigKeys.THRESHOLD_KEY, Double.toString(0));
Job job = new Job(conf, "FuzzyKMeans Driver running runIteration over clustersIn: " + clustersIn);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(ClusterObservations.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(SoftCluster.class);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setMapperClass(FuzzyKMeansMapper.class);
job.setCombinerClass(FuzzyKMeansCombiner.class);
job.setReducerClass(FuzzyKMeansReducer.class);
job.setJarByClass(FuzzyKMeansDriver.class);
FileInputFormat.addInputPath(job, input);
FileOutputFormat.setOutputPath(job, clustersOut);
if (!job.waitForCompletion(true)) {
throw new InterruptedException("Fuzzy K-Means Iteration failed processing " + clustersIn);
}
FileSystem fs = FileSystem.get(clustersOut.toUri(), conf);
return isConverged(clustersOut, conf, fs);
}
/**
* Iterate over the input vectors to produce clusters and, if requested, use the
* results of the final iteration to cluster the input vectors.
* @param input
* the directory pathname for input points
* @param clustersIn
* the directory pathname for initial & computed clusters
* @param output
* the directory pathname for output points
* @param convergenceDelta
* the convergence delta value
* @param maxIterations
* the maximum number of iterations
* @param m
* the fuzzification factor, see
* http://en.wikipedia.org/wiki/Data_clustering#Fuzzy_c-means_clustering
* @param runClustering
* true if points are to be clustered after iterations complete
* @param emitMostLikely
* a boolean if true emit only most likely cluster for each point
* @param threshold
* a double threshold value emits all clusters having greater pdf (emitMostLikely = false)
* @param runSequential if true run in sequential execution mode
*/
public static void run(Configuration conf,
Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
int maxIterations,
float m,
boolean runClustering,
boolean emitMostLikely,
double threshold,
boolean runSequential)
throws IOException, ClassNotFoundException, InterruptedException {
Path clustersOut =
buildClusters(conf, input, clustersIn, output, measure, convergenceDelta, maxIterations, m, runSequential);
if (runClustering) {
log.info("Clustering");
clusterData(input,
clustersOut,
new Path(output, Cluster.CLUSTERED_POINTS_DIR),
measure,
convergenceDelta,
m,
emitMostLikely,
threshold,
runSequential);
}
}
/**
* Iterate over the input vectors to produce cluster directories for each iteration
* @param input
* the directory pathname for input points
* @param clustersIn
* the directory pathname for initial & computed clusters
* @param output
* the directory pathname for output points
* @param measure
* the classname of the DistanceMeasure
* @param convergenceDelta
* the convergence delta value
* @param maxIterations
* the maximum number of iterations
* @param m
* the fuzzification factor, see
* http://en.wikipedia.org/wiki/Data_clustering#Fuzzy_c-means_clustering
* @param runSequential if true run in sequential execution mode
*
* @return the Path of the final clusters directory
*/
public static Path buildClusters(Configuration conf,
Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
int maxIterations,
float m,
boolean runSequential)
throws IOException, InterruptedException, ClassNotFoundException {
if (runSequential) {
return buildClustersSeq(input, clustersIn, output, measure, convergenceDelta, maxIterations, m);
} else {
return buildClustersMR(conf, input, clustersIn, output, measure, convergenceDelta, maxIterations, m);
}
}
private static Path buildClustersSeq(Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
int maxIterations,
float m) throws IOException {
FuzzyKMeansClusterer clusterer = new FuzzyKMeansClusterer(measure, convergenceDelta, m);
List<SoftCluster> clusters = new ArrayList<SoftCluster>();
FuzzyKMeansUtil.configureWithClusterInfo(clustersIn, clusters);
if (clusters.isEmpty()) {
throw new IllegalStateException("Clusters is empty!");
}
boolean converged = false;
int iteration = 1;
while (!converged && iteration <= maxIterations) {
log.info("Fuzzy k-Means Iteration: " + iteration);
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(input.toUri(), conf);
for (VectorWritable value
: new SequenceFileDirValueIterable<VectorWritable>(input,
PathType.LIST,
PathFilters.logsCRCFilter(),
conf)) {
clusterer.addPointToClusters(clusters,value.get());
}
converged = clusterer.testConvergence(clusters);
Path clustersOut = new Path(output, Cluster.CLUSTERS_DIR + iteration);
SequenceFile.Writer writer = new SequenceFile.Writer(fs,
conf,
new Path(clustersOut, "part-r-00000"),
Text.class,
SoftCluster.class);
try {
for (SoftCluster cluster : clusters) {
log.debug("Writing Cluster:{} center:{} numPoints:{} radius:{} to: {}",
new Object[] {
cluster.getId(),
AbstractCluster.formatVector(cluster.getCenter(), null),
cluster.getNumPoints(),
AbstractCluster.formatVector(cluster.getRadius(), null),
clustersOut.getName()
});
writer.append(new Text(cluster.getIdentifier()), cluster);
}
} finally {
Closeables.closeQuietly(writer);
}
clustersIn = clustersOut;
iteration++;
}
return clustersIn;
}
private static Path buildClustersMR(Configuration conf,
Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
int maxIterations,
float m) throws IOException, InterruptedException, ClassNotFoundException {
boolean converged = false;
int iteration = 1;
// iterate until the clusters converge
while (!converged && iteration <= maxIterations) {
log.info("Fuzzy K-Means Iteration {}", iteration);
// point the output to a new directory per iteration
Path clustersOut = new Path(output, Cluster.CLUSTERS_DIR + iteration);
converged = runIteration(conf, input, clustersIn, clustersOut, measure.getClass().getName(), convergenceDelta, m);
// now point the input to the old output directory
clustersIn = clustersOut;
iteration++;
}
return clustersIn;
}
/**
* Run the job using supplied arguments
*
* @param input
* the directory pathname for input points
* @param clustersIn
* the directory pathname for input clusters
* @param output
* the directory pathname for output points
* @param measure
* the classname of the DistanceMeasure
* @param convergenceDelta
* the convergence delta value
* @param emitMostLikely
* a boolean if true emit only most likely cluster for each point
* @param threshold
* a double threshold value emits all clusters having greater pdf (emitMostLikely = false)
* @param runSequential if true run in sequential execution mode
*/
public static void clusterData(Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
float m,
boolean emitMostLikely,
double threshold,
boolean runSequential)
throws IOException, ClassNotFoundException, InterruptedException {
if (runSequential) {
clusterDataSeq(input, clustersIn, output, measure, convergenceDelta, m);
} else {
clusterDataMR(input, clustersIn, output, measure, convergenceDelta, m, emitMostLikely, threshold);
}
}
private static void clusterDataSeq(Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
float m) throws IOException {
FuzzyKMeansClusterer clusterer = new FuzzyKMeansClusterer(measure, convergenceDelta, m);
List<SoftCluster> clusters = new ArrayList<SoftCluster>();
FuzzyKMeansUtil.configureWithClusterInfo(clustersIn, clusters);
if (clusters.isEmpty()) {
throw new IllegalStateException("Clusters is empty!");
}
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(input.toUri(), conf);
FileStatus[] status = fs.listStatus(input, PathFilters.logsCRCFilter());
int part = 0;
for (FileStatus s : status) {
SequenceFile.Writer writer = new SequenceFile.Writer(fs,
conf,
new Path(output, "part-m-" + part),
IntWritable.class,
WeightedVectorWritable.class);
try {
for (VectorWritable value : new SequenceFileValueIterable<VectorWritable>(s.getPath(), conf)) {
clusterer.emitPointToClusters(value, clusters, writer);
}
} finally {
Closeables.closeQuietly(writer);
}
}
}
private static void clusterDataMR(Path input,
Path clustersIn,
Path output,
DistanceMeasure measure,
double convergenceDelta,
float m,
boolean emitMostLikely,
double threshold) throws IOException, InterruptedException, ClassNotFoundException {
Configuration conf = new Configuration();
conf.set(FuzzyKMeansConfigKeys.CLUSTER_PATH_KEY, clustersIn.toString());
conf.set(FuzzyKMeansConfigKeys.DISTANCE_MEASURE_KEY, measure.getClass().getName());
conf.set(FuzzyKMeansConfigKeys.CLUSTER_CONVERGENCE_KEY, String.valueOf(convergenceDelta));
conf.set(FuzzyKMeansConfigKeys.M_KEY, String.valueOf(m));
conf.set(FuzzyKMeansConfigKeys.EMIT_MOST_LIKELY_KEY, Boolean.toString(emitMostLikely));
conf.set(FuzzyKMeansConfigKeys.THRESHOLD_KEY, Double.toString(threshold));
// Clear output
output.getFileSystem(conf).delete(output, true);
Job job = new Job(conf, "FuzzyKMeans Driver running clusterData over input: " + input);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(WeightedVectorWritable.class);
FileInputFormat.setInputPaths(job, input);
FileOutputFormat.setOutputPath(job, output);
job.setMapperClass(FuzzyKMeansClusterMapper.class);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setNumReduceTasks(0);
job.setJarByClass(FuzzyKMeansDriver.class);
if (!job.waitForCompletion(true)) {
throw new InterruptedException("Fuzzy K-Means Clustering failed processing " + clustersIn);
}
}
/**
* Return if all of the Clusters in the filePath have converged or not
*
* @param filePath
* the file path to the single file containing the clusters
* @return true if all Clusters are converged
* @throws IOException
* if there was an IO error
*/
private static boolean isConverged(Path filePath, Configuration conf, FileSystem fs) throws IOException {
Path clusterPath = new Path(filePath, "*");
Collection<Path> result = new ArrayList<Path>();
FileStatus[] matches =
fs.listStatus(FileUtil.stat2Paths(fs.globStatus(clusterPath, PathFilters.partFilter())),
PathFilters.partFilter());
for (FileStatus match : matches) {
result.add(fs.makeQualified(match.getPath()));
}
boolean converged = true;
for (Path path : result) {
SequenceFileValueIterator<SoftCluster> iterator = new SequenceFileValueIterator<SoftCluster>(path, true, conf);
try {
while (converged && iterator.hasNext()) {
converged = iterator.next().isConverged();
}
} finally {
Closeables.closeQuietly(iterator);
}
}
return converged;
}
}
| true | true | public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption(DefaultOptionCreator.distanceMeasureOption().create());
addOption(DefaultOptionCreator.clustersInOption()
.withDescription("The input centroids, as Vectors. Must be a SequenceFile of Writable, Cluster/Canopy. "
+ "If k is also specified, then a random set of vectors will be selected"
+ " and written out to this path first")
.create());
addOption(DefaultOptionCreator.numClustersOption()
.withDescription("The k in k-Means. If specified, then a random selection of k Vectors will be chosen"
+ " as the Centroid and written to the clusters input path.").create());
addOption(DefaultOptionCreator.convergenceOption().create());
addOption(DefaultOptionCreator.maxIterationsOption().create());
addOption(DefaultOptionCreator.overwriteOption().create());
addOption(M_OPTION, M_OPTION, "coefficient normalization factor, must be greater than 1", true);
addOption(DefaultOptionCreator.clusteringOption().create());
addOption(DefaultOptionCreator.emitMostLikelyOption().create());
addOption(DefaultOptionCreator.thresholdOption().create());
addOption(DefaultOptionCreator.methodOption().create());
if (parseArguments(args) == null) {
return -1;
}
Path input = getInputPath();
Path clusters = new Path(getOption(DefaultOptionCreator.CLUSTERS_IN_OPTION));
Path output = getOutputPath();
String measureClass = getOption(DefaultOptionCreator.DISTANCE_MEASURE_OPTION);
if (measureClass == null) {
measureClass = SquaredEuclideanDistanceMeasure.class.getName();
}
double convergenceDelta = Double.parseDouble(getOption(DefaultOptionCreator.CONVERGENCE_DELTA_OPTION));
float fuzziness = Float.parseFloat(getOption(M_OPTION));
int maxIterations = Integer.parseInt(getOption(DefaultOptionCreator.MAX_ITERATIONS_OPTION));
if (hasOption(DefaultOptionCreator.OVERWRITE_OPTION)) {
HadoopUtil.delete(getConf(), output);
}
boolean emitMostLikely = Boolean.parseBoolean(getOption(DefaultOptionCreator.EMIT_MOST_LIKELY_OPTION));
double threshold = Double.parseDouble(getOption(DefaultOptionCreator.THRESHOLD_OPTION));
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(measureClass).asSubclass(DistanceMeasure.class).newInstance();
if (hasOption(DefaultOptionCreator.NUM_CLUSTERS_OPTION)) {
clusters = RandomSeedGenerator.buildRandom(getConf(), input, clusters, Integer.parseInt(parseArguments(args)
.get(DefaultOptionCreator.NUM_CLUSTERS_OPTION)), measure);
}
boolean runClustering = hasOption(DefaultOptionCreator.CLUSTERING_OPTION);
boolean runSequential = getOption(DefaultOptionCreator.METHOD_OPTION).equalsIgnoreCase(
DefaultOptionCreator.SEQUENTIAL_METHOD);
run(getConf(),
input,
clusters,
output,
measure,
convergenceDelta,
maxIterations,
fuzziness,
runClustering,
emitMostLikely,
threshold,
runSequential);
return 0;
}
| public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption(DefaultOptionCreator.distanceMeasureOption().create());
addOption(DefaultOptionCreator.clustersInOption()
.withDescription("The input centroids, as Vectors. Must be a SequenceFile of Writable, Cluster/Canopy. "
+ "If k is also specified, then a random set of vectors will be selected"
+ " and written out to this path first")
.create());
addOption(DefaultOptionCreator.numClustersOption()
.withDescription("The k in k-Means. If specified, then a random selection of k Vectors will be chosen"
+ " as the Centroid and written to the clusters input path.").create());
addOption(DefaultOptionCreator.convergenceOption().create());
addOption(DefaultOptionCreator.maxIterationsOption().create());
addOption(DefaultOptionCreator.overwriteOption().create());
addOption(M_OPTION, M_OPTION, "coefficient normalization factor, must be greater than 1", true);
addOption(DefaultOptionCreator.clusteringOption().create());
addOption(DefaultOptionCreator.emitMostLikelyOption().create());
addOption(DefaultOptionCreator.thresholdOption().create());
addOption(DefaultOptionCreator.methodOption().create());
if (parseArguments(args) == null) {
return -1;
}
Path input = getInputPath();
Path clusters = new Path(getOption(DefaultOptionCreator.CLUSTERS_IN_OPTION));
Path output = getOutputPath();
String measureClass = getOption(DefaultOptionCreator.DISTANCE_MEASURE_OPTION);
if (measureClass == null) {
measureClass = SquaredEuclideanDistanceMeasure.class.getName();
}
double convergenceDelta = Double.parseDouble(getOption(DefaultOptionCreator.CONVERGENCE_DELTA_OPTION));
float fuzziness = Float.parseFloat(getOption(M_OPTION));
int maxIterations = Integer.parseInt(getOption(DefaultOptionCreator.MAX_ITERATIONS_OPTION));
if (hasOption(DefaultOptionCreator.OVERWRITE_OPTION)) {
HadoopUtil.delete(getConf(), output);
}
boolean emitMostLikely = Boolean.parseBoolean(getOption(DefaultOptionCreator.EMIT_MOST_LIKELY_OPTION));
double threshold = Double.parseDouble(getOption(DefaultOptionCreator.THRESHOLD_OPTION));
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(measureClass).asSubclass(DistanceMeasure.class).newInstance();
if (hasOption(DefaultOptionCreator.NUM_CLUSTERS_OPTION)) {
clusters = RandomSeedGenerator.buildRandom(getConf(),
input,
clusters,
Integer.parseInt(getOption(DefaultOptionCreator.NUM_CLUSTERS_OPTION)),
measure);
}
boolean runClustering = hasOption(DefaultOptionCreator.CLUSTERING_OPTION);
boolean runSequential = getOption(DefaultOptionCreator.METHOD_OPTION).equalsIgnoreCase(
DefaultOptionCreator.SEQUENTIAL_METHOD);
run(getConf(),
input,
clusters,
output,
measure,
convergenceDelta,
maxIterations,
fuzziness,
runClustering,
emitMostLikely,
threshold,
runSequential);
return 0;
}
|
diff --git a/src/com/android/stk/StkAppService.java b/src/com/android/stk/StkAppService.java
index 0b0fe0d..7364a50 100644
--- a/src/com/android/stk/StkAppService.java
+++ b/src/com/android/stk/StkAppService.java
@@ -1,1105 +1,1104 @@
/*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (c) 2009, Code Aurora Forum. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.stk;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.telephony.cat.AppInterface;
import com.android.internal.telephony.cat.LaunchBrowserMode;
import com.android.internal.telephony.cat.Menu;
import com.android.internal.telephony.cat.Item;
import com.android.internal.telephony.cat.ResultCode;
import com.android.internal.telephony.cat.CatCmdMessage;
import com.android.internal.telephony.cat.ToneSettings;
import com.android.internal.telephony.cat.CatCmdMessage.BrowserSettings;
import com.android.internal.telephony.cat.CatCmdMessage.SetupEventListSettings;
import com.android.internal.telephony.cat.CatLog;
import com.android.internal.telephony.cat.CatResponseMessage;
import com.android.internal.telephony.cat.TextMessage;
import com.android.internal.telephony.GsmAlphabet;
import com.android.internal.telephony.SimRefreshResponse;
import java.util.LinkedList;
import static com.android.internal.telephony.cat.CatCmdMessage.SetupEventListConstants.*;
/**
* SIM toolkit application level service. Interacts with Telephopny messages,
* application's launch and user input from STK UI elements.
*
*/
public class StkAppService extends Service implements Runnable {
// members
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private AppInterface mStkService;
private Context mContext = null;
private CatCmdMessage mMainCmd = null;
private CatCmdMessage mCurrentCmd = null;
private Menu mCurrentMenu = null;
private String lastSelectedItem = null;
private boolean mMenuIsVisibile = false;
private boolean responseNeeded = true;
private boolean mCmdInProgress = false;
private NotificationManager mNotificationManager = null;
private LinkedList<DelayedCmd> mCmdsQ = null;
private boolean launchBrowser = false;
private BrowserSettings mBrowserSettings = null;
static StkAppService sInstance = null;
private SetupEventListSettings mSetupEventListSettings = null;
private boolean mClearSelectItem = false;
private boolean mDisplayTextDlgIsVisibile = false;
private CatCmdMessage mCurrentSetupEventCmd = null;
// Used for setting FLAG_ACTIVITY_NO_USER_ACTION when
// creating an intent.
private enum InitiatedByUserAction {
yes, // The action was started via a user initiated action
unknown, // Not known for sure if user initated the action
}
// constants
static final String OPCODE = "op";
static final String CMD_MSG = "cmd message";
static final String RES_ID = "response id";
static final String MENU_SELECTION = "menu selection";
static final String INPUT = "input";
static final String HELP = "help";
static final String CONFIRMATION = "confirm";
static final String SCREEN_STATUS = "screen status";
// These below constants are used for SETUP_EVENT_LIST
static final String SETUP_EVENT_TYPE = "event";
static final String SETUP_EVENT_CAUSE = "cause";
// operations ids for different service functionality.
static final int OP_CMD = 1;
static final int OP_RESPONSE = 2;
static final int OP_LAUNCH_APP = 3;
static final int OP_END_SESSION = 4;
static final int OP_BOOT_COMPLETED = 5;
private static final int OP_DELAYED_MSG = 6;
static final int OP_IDLE_SCREEN = 7;
static final int OP_BROWSER_TERMINATION = 8;
static final int OP_LOCALE_CHANGED = 9;
static final int OP_ICC_STATUS_CHANGE = 10;
//Invalid SetupEvent
static final int INVALID_SETUP_EVENT = 0xFF;
// Response ids
static final int RES_ID_MENU_SELECTION = 11;
static final int RES_ID_INPUT = 12;
static final int RES_ID_CONFIRM = 13;
static final int RES_ID_DONE = 14;
static final int RES_ID_TIMEOUT = 20;
static final int RES_ID_BACKWARD = 21;
static final int RES_ID_END_SESSION = 22;
static final int RES_ID_EXIT = 23;
private static final String PACKAGE_NAME = "com.android.stk";
private static final String MENU_ACTIVITY_NAME =
PACKAGE_NAME + ".StkMenuActivity";
private static final String INPUT_ACTIVITY_NAME =
PACKAGE_NAME + ".StkInputActivity";
// Notification id used to display Idle Mode text in NotificationManager.
private static final int STK_NOTIFICATION_ID = 333;
private CatCmdMessage mIdleModeTextCmd = null;
private boolean mDisplayText = false;
private boolean mScreenIdle = true;
TonePlayer player = null;
Vibrator mVibrator = new Vibrator();
// Message id to signal tone duration timeout.
private static final int MSG_ID_STOP_TONE = 0xda;
// Inner class used for queuing telephony messages (proactive commands,
// session end) while the service is busy processing a previous message.
private class DelayedCmd {
// members
int id;
CatCmdMessage msg;
DelayedCmd(int id, CatCmdMessage msg) {
this.id = id;
this.msg = msg;
}
}
@Override
public void onCreate() {
// Initialize members
mStkService = com.android.internal.telephony.cat.CatService
.getInstance();
// NOTE mStkService is a singleton and continues to exist even if the GSMPhone is disposed
// after the radio technology change from GSM to CDMA so the PHONE_TYPE_CDMA check is
// needed. In case of switching back from CDMA to GSM the GSMPhone constructor updates
// the instance. (TODO: test).
if ((mStkService == null)
&& (TelephonyManager.getDefault().getPhoneType()
!= TelephonyManager.PHONE_TYPE_CDMA)) {
CatLog.d(this, " Unable to get Service handle");
return;
}
mCmdsQ = new LinkedList<DelayedCmd>();
Thread serviceThread = new Thread(null, this, "Stk App Service");
serviceThread.start();
mContext = getBaseContext();
mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
sInstance = this;
}
@Override
public void onStart(Intent intent, int startId) {
waitForLooper();
// onStart() method can be passed a null intent
// TODO: replace onStart() with onStartCommand()
if (intent == null) {
return;
}
Bundle args = intent.getExtras();
if (args == null) {
return;
}
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = args.getInt(OPCODE);
switch(msg.arg1) {
case OP_CMD:
msg.obj = args.getParcelable(CMD_MSG);
break;
case OP_RESPONSE:
case OP_BROWSER_TERMINATION:
case OP_LOCALE_CHANGED:
case OP_ICC_STATUS_CHANGE:
case OP_IDLE_SCREEN:
msg.obj = args;
/* falls through */
case OP_LAUNCH_APP:
case OP_END_SESSION:
case OP_BOOT_COMPLETED:
break;
default:
return;
}
mServiceHandler.sendMessage(msg);
}
@Override
public void onDestroy() {
waitForLooper();
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void run() {
Looper.prepare();
mServiceLooper = Looper.myLooper();
mServiceHandler = new ServiceHandler();
Looper.loop();
}
/*
* Package api used by StkMenuActivity to indicate if its on the foreground.
*/
void indicateMenuVisibility(boolean visibility) {
mMenuIsVisibile = visibility;
}
/*
* Package api used by StkMenuActivity to get its Menu parameter.
*/
Menu getMenu() {
return mCurrentMenu;
}
/*
* Package api used by UI Activities and Dialogs to communicate directly
* with the service to deliver state information and parameters.
*/
static StkAppService getInstance() {
return sInstance;
}
private void waitForLooper() {
while (mServiceHandler == null) {
synchronized (this) {
try {
wait(100);
} catch (InterruptedException e) {
}
}
}
}
private final class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
int opcode = msg.arg1;
switch (opcode) {
case OP_LAUNCH_APP:
if (mMainCmd == null) {
// nothing todo when no SET UP MENU command didn't arrive.
return;
}
launchMenuActivity(null);
break;
case OP_CMD:
CatCmdMessage cmdMsg = (CatCmdMessage) msg.obj;
// There are two types of commands:
// 1. Interactive - user's response is required.
// 2. Informative - display a message, no interaction with the user.
//
// Informative commands can be handled immediately without any delay.
// Interactive commands can't override each other. So if a command
// is already in progress, we need to queue the next command until
// the user has responded or a timeout expired.
if (!isCmdInteractive(cmdMsg)) {
handleCmd(cmdMsg);
} else {
if (!mCmdInProgress) {
mCmdInProgress = true;
handleCmd((CatCmdMessage) msg.obj);
} else {
mCmdsQ.addLast(new DelayedCmd(OP_CMD,
(CatCmdMessage) msg.obj));
}
}
break;
case OP_RESPONSE:
if (responseNeeded) {
handleCmdResponse((Bundle) msg.obj);
}
// call delayed commands if needed.
if (mCmdsQ.size() != 0) {
callDelayedMsg();
} else {
mCmdInProgress = false;
}
// reset response needed state var to its original value.
responseNeeded = true;
break;
case OP_END_SESSION:
if (!mCmdInProgress) {
mCmdInProgress = true;
handleSessionEnd();
} else {
mCmdsQ.addLast(new DelayedCmd(OP_END_SESSION, null));
}
break;
case OP_BOOT_COMPLETED:
CatLog.d(this, "OP_BOOT_COMPLETED");
if (mMainCmd == null) {
StkAppInstaller.unInstall(mContext);
}
break;
case OP_DELAYED_MSG:
handleDelayedCmd();
break;
case OP_BROWSER_TERMINATION:
CatLog.d(this, "Browser Closed");
checkForSetupEvent(BROWSER_TERMINATION_EVENT,(Bundle) msg.obj);
break;
case OP_IDLE_SCREEN:
handleScreenStatus((Bundle) msg.obj);
break;
case OP_LOCALE_CHANGED:
CatLog.d(this, "Locale Changed");
checkForSetupEvent(LANGUAGE_SELECTION_EVENT,(Bundle) msg.obj);
break;
case OP_ICC_STATUS_CHANGE:
CatLog.d(this, "Icc Status change received");
handleIccStatusChange((Bundle) msg.obj);
break;
case MSG_ID_STOP_TONE:
CatLog.d(this, "Received MSG_ID_STOP_TONE");
handleStopTone();
break;
}
}
}
private void handleIccStatusChange(Bundle args) {
Boolean RadioStatus = args.getBoolean("RADIO_AVAILABLE");
if (RadioStatus == false) {
CatLog.d(this, "RADIO_OFF_OR_UNAVAILABLE received");
// Unistall STKAPP, Clear Idle text, Stop StkAppService
StkAppInstaller.unInstall(mContext);
mNotificationManager.cancel(STK_NOTIFICATION_ID);
stopSelf();
} else {
SimRefreshResponse state = new SimRefreshResponse();
state.refreshResult = SimRefreshResponse.refreshResultFromRIL(
args.getInt("REFRESH_RESULT"));
CatLog.d(this, "Icc Refresh Result: "+ state.refreshResult);
if ((state.refreshResult == SimRefreshResponse.Result.SIM_INIT) ||
(state.refreshResult == SimRefreshResponse.Result.SIM_RESET)) {
// Clear Idle Text
mNotificationManager.cancel(STK_NOTIFICATION_ID);
mIdleModeTextCmd = null;
}
if (state.refreshResult == SimRefreshResponse.Result.SIM_RESET) {
// Uninstall STkmenu
StkAppInstaller.unInstall(mContext);
mCurrentMenu = null;
mMainCmd = null;
}
}
}
private void handleScreenStatus(Bundle args) {
mScreenIdle = args.getBoolean(SCREEN_STATUS);
// If the idle screen event is present in the list need to send the
// response to SIM.
if (mScreenIdle) {
CatLog.d(this, "Need to send IDLE SCREEN Available event to SIM");
checkForSetupEvent(IDLE_SCREEN_AVAILABLE_EVENT, null);
}
if (mIdleModeTextCmd != null) {
launchIdleText();
}
if (mDisplayText) {
if (!mScreenIdle) {
sendScreenBusyResponse();
} else {
launchTextDialog();
}
mDisplayText = false;
// If an idle text proactive command is set then the
// request for getting screen status still holds true.
if (mIdleModeTextCmd == null) {
Intent StkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
StkIntent.putExtra("SCREEN_STATUS_REQUEST", false);
sendBroadcast(StkIntent);
}
}
}
private void sendScreenBusyResponse() {
if (mCurrentCmd == null) {
return;
}
CatResponseMessage resMsg = new CatResponseMessage(mCurrentCmd);
CatLog.d(this, "SCREEN_BUSY");
resMsg.setResultCode(ResultCode.TERMINAL_CRNTLY_UNABLE_TO_PROCESS);
mStkService.onCmdResponse(resMsg);
// reset response needed state var to its original value.
responseNeeded = true;
if (mCmdsQ.size() != 0) {
callDelayedMsg();
} else {
mCmdInProgress = false;
}
}
private void handleStopTone() {
sendResponse(StkAppService.RES_ID_DONE);
player.stop();
player.release();
mVibrator.cancel();
CatLog.d(this, "Finished handling PlayTone with Null alpha");
}
private void sendResponse(int resId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = OP_RESPONSE;
Bundle args = new Bundle();
args.putInt(StkAppService.RES_ID, resId);
msg.obj = args;
mServiceHandler.sendMessage(msg);
}
private boolean isCmdInteractive(CatCmdMessage cmd) {
switch (cmd.getCmdType()) {
case SEND_DTMF:
case SEND_SMS:
case SEND_SS:
case SEND_USSD:
case SET_UP_IDLE_MODE_TEXT:
case SET_UP_MENU:
case SET_UP_EVENT_LIST:
return false;
}
return true;
}
private void handleDelayedCmd() {
if (mCmdsQ.size() != 0) {
DelayedCmd cmd = mCmdsQ.poll();
switch (cmd.id) {
case OP_CMD:
handleCmd(cmd.msg);
break;
case OP_END_SESSION:
handleSessionEnd();
break;
}
}
}
private void callDelayedMsg() {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = OP_DELAYED_MSG;
mServiceHandler.sendMessage(msg);
}
private void handleSessionEnd() {
mCurrentCmd = mMainCmd;
lastSelectedItem = null;
// In case of SET UP MENU command which removed the app, don't
// update the current menu member.
if (mCurrentMenu != null && mMainCmd != null) {
mCurrentMenu = mMainCmd.getMenu();
}
if (mMenuIsVisibile) {
launchMenuActivity(null);
}
if (mCmdsQ.size() != 0) {
callDelayedMsg();
} else {
mCmdInProgress = false;
}
// In case a launch browser command was just confirmed, launch that url.
if (launchBrowser) {
launchBrowser = false;
launchBrowser(mBrowserSettings);
}
}
private void handleCmd(CatCmdMessage cmdMsg) {
if (cmdMsg == null) {
return;
}
// save local reference for state tracking.
mCurrentCmd = cmdMsg;
boolean waitForUsersResponse = true;
CatLog.d(this, cmdMsg.getCmdType().name());
switch (cmdMsg.getCmdType()) {
case DISPLAY_TEXT:
TextMessage msg = cmdMsg.geTextMessage();
//In case when TR already sent no response is expected by Stk app
if (!msg.responseNeeded) {
waitForUsersResponse = false;
}
if (lastSelectedItem != null) {
msg.title = lastSelectedItem;
} else if (mMainCmd != null){
msg.title = mMainCmd.getMenu().title;
} else {
// TODO: get the carrier name from the SIM
msg.title = "";
}
launchTextDialog();
break;
case SELECT_ITEM:
mCurrentMenu = cmdMsg.getMenu();
launchMenuActivity(cmdMsg.getMenu());
break;
case SET_UP_MENU:
mMainCmd = mCurrentCmd;
mCurrentMenu = cmdMsg.getMenu();
if (removeMenu()) {
CatLog.d(this, "Uninstall App");
mCurrentMenu = null;
mMainCmd = null;
StkAppInstaller.unInstall(mContext);
} else {
CatLog.d(this, "Install App");
StkAppInstaller.install(mContext);
}
if (mMenuIsVisibile) {
launchMenuActivity(null);
}
break;
case GET_INPUT:
case GET_INKEY:
launchInputActivity();
break;
case SET_UP_IDLE_MODE_TEXT:
waitForUsersResponse = false;
launchIdleText();
mIdleModeTextCmd = mCurrentCmd;
TextMessage idleModeText = mCurrentCmd.geTextMessage();
// Send intent to ActivityManagerService to get the screen status
Intent idleStkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
if (idleModeText != null) {
if (idleModeText.text != null) {
idleStkIntent.putExtra("SCREEN_STATUS_REQUEST",true);
} else {
idleStkIntent.putExtra("SCREEN_STATUS_REQUEST",false);
launchIdleText();
mIdleModeTextCmd = null;
}
}
CatLog.d(this, "set up idle mode");
mCurrentCmd = mMainCmd;
sendBroadcast(idleStkIntent);
break;
case SEND_DTMF:
case SEND_SMS:
case SEND_SS:
case SEND_USSD:
- mCurrentCmd = mMainCmd;
waitForUsersResponse = false;
launchEventMessage();
break;
case LAUNCH_BROWSER:
launchConfirmationDialog(mCurrentCmd.geTextMessage());
break;
case CLOSE_CHANNEL:
case RECEIVE_DATA:
case SEND_DATA:
case GET_CHANNEL_STATUS:
waitForUsersResponse = false;
launchEventMessage();
break;
case OPEN_CHANNEL:
launchConfirmationDialog(mCurrentCmd.getCallSettings().confirmMsg);
break;
case SET_UP_CALL:
TextMessage mesg = mCurrentCmd.getCallSettings().confirmMsg;
if ((mesg != null) && (mesg.text == null || mesg.text.length() == 0)) {
mesg.text = getResources().getString(R.string.default_setup_call_msg);
}
CatLog.d(this, "SET_UP_CALL mesg.text " + mesg.text);
launchConfirmationDialog(mesg);
break;
case PLAY_TONE:
launchToneDialog();
break;
case SET_UP_EVENT_LIST:
mSetupEventListSettings = mCurrentCmd.getSetEventList();
mCurrentSetupEventCmd = mCurrentCmd;
mCurrentCmd = mMainCmd;
if ((mIdleModeTextCmd == null) && (!mDisplayText)) {
for (int i = 0; i < mSetupEventListSettings.eventList.length; i++) {
if (mSetupEventListSettings.eventList[i] == IDLE_SCREEN_AVAILABLE_EVENT) {
CatLog.d(this," IDLE_SCREEN_AVAILABLE_EVENT present in List");
// Request ActivityManagerService to get the screen status
Intent StkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
StkIntent.putExtra("SCREEN_STATUS_REQUEST", true);
sendBroadcast(StkIntent);
break;
}
}
}
break;
}
if (!waitForUsersResponse) {
if (mCmdsQ.size() != 0) {
callDelayedMsg();
} else {
mCmdInProgress = false;
}
}
}
private void handleCmdResponse(Bundle args) {
if (mCurrentCmd == null) {
return;
}
CatResponseMessage resMsg = new CatResponseMessage(mCurrentCmd);
// set result code
boolean helpRequired = args.getBoolean(HELP, false);
switch(args.getInt(RES_ID)) {
case RES_ID_MENU_SELECTION:
CatLog.d(this, "RES_ID_MENU_SELECTION");
int menuSelection = args.getInt(MENU_SELECTION);
switch(mCurrentCmd.getCmdType()) {
case SET_UP_MENU:
case SELECT_ITEM:
lastSelectedItem = getItemName(menuSelection);
if (helpRequired) {
resMsg.setResultCode(ResultCode.HELP_INFO_REQUIRED);
} else {
resMsg.setResultCode(mCurrentCmd.hasIconLoadFailed() ?
ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK);
}
resMsg.setMenuSelection(menuSelection);
break;
}
break;
case RES_ID_INPUT:
CatLog.d(this, "RES_ID_INPUT");
String input = args.getString(INPUT);
if (mCurrentCmd.geInput().yesNo) {
boolean yesNoSelection = input
.equals(StkInputActivity.YES_STR_RESPONSE);
resMsg.setYesNo(yesNoSelection);
} else {
if (helpRequired) {
resMsg.setResultCode(ResultCode.HELP_INFO_REQUIRED);
} else {
resMsg.setResultCode(mCurrentCmd.hasIconLoadFailed() ?
ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK);
resMsg.setInput(input);
}
}
break;
case RES_ID_CONFIRM:
CatLog.d(this, "RES_ID_CONFIRM");
boolean confirmed = args.getBoolean(CONFIRMATION);
switch (mCurrentCmd.getCmdType()) {
case DISPLAY_TEXT:
if (confirmed) {
resMsg.setResultCode(mCurrentCmd.hasIconLoadFailed() ?
ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK);
} else {
resMsg.setResultCode(ResultCode.UICC_SESSION_TERM_BY_USER);
}
break;
case LAUNCH_BROWSER:
resMsg.setResultCode(confirmed ? ResultCode.OK
: ResultCode.UICC_SESSION_TERM_BY_USER);
if (confirmed) {
launchBrowser = true;
mBrowserSettings = mCurrentCmd.getBrowserSettings();
}
break;
case OPEN_CHANNEL:
case SET_UP_CALL:
resMsg.setResultCode(ResultCode.OK);
resMsg.setConfirmation(confirmed);
if (confirmed) {
launchCallMsg();
}
break;
}
break;
case RES_ID_DONE:
resMsg.setResultCode(ResultCode.OK);
break;
case RES_ID_BACKWARD:
CatLog.d(this, "RES_ID_BACKWARD");
resMsg.setResultCode(ResultCode.BACKWARD_MOVE_BY_USER);
break;
case RES_ID_END_SESSION:
CatLog.d(this, "RES_ID_END_SESSION");
resMsg.setResultCode(ResultCode.UICC_SESSION_TERM_BY_USER);
break;
case RES_ID_TIMEOUT:
CatLog.d(this, "RES_ID_TIMEOUT");
// GCF test-case 27.22.4.1.1 Expected Sequence 1.5 (DISPLAY TEXT,
// Clear message after delay, successful) expects result code OK.
// If the command qualifier specifies no user response is required
// then send OK instead of NO_RESPONSE_FROM_USER
if ((mCurrentCmd.getCmdType().value() == AppInterface.CommandType.DISPLAY_TEXT
.value())
&& (mCurrentCmd.geTextMessage().userClear == false)) {
resMsg.setResultCode(ResultCode.OK);
} else {
resMsg.setResultCode(ResultCode.NO_RESPONSE_FROM_USER);
}
break;
default:
CatLog.d(this, "Unknown result id");
return;
}
mStkService.onCmdResponse(resMsg);
}
/**
* Returns 0 or FLAG_ACTIVITY_NO_USER_ACTION, 0 means the user initiated the action.
*
* @param userAction If the userAction is yes then we always return 0 otherwise
* mMenuIsVisible is used to determine what to return. If mMenuIsVisible is true
* then we are the foreground app and we'll return 0 as from our perspective a
* user action did cause. If it's false than we aren't the foreground app and
* FLAG_ACTIVITY_NO_USER_ACTION is returned.
*
* @return 0 or FLAG_ACTIVITY_NO_USER_ACTION
*/
private int getFlagActivityNoUserAction(InitiatedByUserAction userAction) {
return ((userAction == InitiatedByUserAction.yes) | mMenuIsVisibile) ?
0 : Intent.FLAG_ACTIVITY_NO_USER_ACTION;
}
private void launchMenuActivity(Menu menu) {
Intent newIntent = new Intent(Intent.ACTION_VIEW);
newIntent.setClassName(PACKAGE_NAME, MENU_ACTIVITY_NAME);
int intentFlags = Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP;
if (menu == null) {
// We assume this was initiated by the user pressing the tool kit icon
intentFlags |= getFlagActivityNoUserAction(InitiatedByUserAction.yes);
newIntent.putExtra("STATE", StkMenuActivity.STATE_MAIN);
} else {
// We don't know and we'll let getFlagActivityNoUserAction decide.
intentFlags |= getFlagActivityNoUserAction(InitiatedByUserAction.unknown);
newIntent.putExtra("STATE", StkMenuActivity.STATE_SECONDARY);
}
newIntent.setFlags(intentFlags);
mContext.startActivity(newIntent);
}
private void launchInputActivity() {
Intent newIntent = new Intent(Intent.ACTION_VIEW);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| getFlagActivityNoUserAction(InitiatedByUserAction.unknown));
newIntent.setClassName(PACKAGE_NAME, INPUT_ACTIVITY_NAME);
newIntent.putExtra("INPUT", mCurrentCmd.geInput());
mContext.startActivity(newIntent);
}
private void launchTextDialog() {
Intent newIntent = new Intent(this, StkDialogActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK
| Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| getFlagActivityNoUserAction(InitiatedByUserAction.unknown));
newIntent.putExtra("TEXT", mCurrentCmd.geTextMessage());
startActivity(newIntent);
}
private void sendSetUpEventResponse(int event, byte[] addedInfo) {
CatLog.d(this, "sendSetUpEventResponse: event : " + event);
if (mCurrentSetupEventCmd == null){
return;
}
CatResponseMessage resMsg = new CatResponseMessage(mCurrentSetupEventCmd);
resMsg.setResultCode(ResultCode.OK);
resMsg.setEventDownload(event, addedInfo);
mStkService.onCmdResponse(resMsg);
}
private void checkForSetupEvent(int event, Bundle args) {
boolean eventPresent = false;
byte[] addedInfo = null;
CatLog.d(this, "Event :" + event);
if (mSetupEventListSettings != null) {
/* Checks if the event is present in the EventList updated by last
* SetupEventList Proactive Command */
for (int i = 0; i < mSetupEventListSettings.eventList.length; i++) {
if (event == mSetupEventListSettings.eventList[i]) {
eventPresent = true;
break;
}
}
/* If Event is present send the response to ICC */
if (eventPresent == true) {
CatLog.d(this, " Event " + event + "exists in the EventList");
switch (event) {
case BROWSER_TERMINATION_EVENT:
int browserTerminationCause = args.getInt(AppInterface.BROWSER_TERMINATION_CAUSE);
CatLog.d(this, "BrowserTerminationCause: "+ browserTerminationCause);
//Single byte is sufficient to represent browser termination cause.
addedInfo = new byte[1];
addedInfo[0] = (byte) browserTerminationCause;
sendSetUpEventResponse(event, addedInfo);
break;
case IDLE_SCREEN_AVAILABLE_EVENT:
sendSetUpEventResponse(event, addedInfo);
removeSetUpEvent(event);
break;
case LANGUAGE_SELECTION_EVENT:
String language = mContext.getResources().getConfiguration().locale.getLanguage();
CatLog.d(this, "language: " + language);
// Each language code is a pair of alpha-numeric characters. Each alpha-numeric
// character shall be coded on one byte using the SMS default 7-bit coded alphabet
addedInfo = GsmAlphabet.stringToGsm8BitPacked(language);
sendSetUpEventResponse(event, addedInfo);
break;
default:
break;
}
} else {
CatLog.d(this, " Event does not exist in the EventList");
}
} else {
CatLog.d(this, "SetupEventList is not received. Ignoring the event: " + event);
}
}
private void removeSetUpEvent(int event) {
CatLog.d(this, "Remove Event :" + event);
if (mSetupEventListSettings != null) {
/*
* Make new Eventlist without the event
*/
for (int i = 0; i < mSetupEventListSettings.eventList.length; i++) {
if (event == mSetupEventListSettings.eventList[i]) {
mSetupEventListSettings.eventList[i] = INVALID_SETUP_EVENT;
break;
}
}
}
}
private void launchEventMessage() {
TextMessage msg = mCurrentCmd.geTextMessage();
if (msg == null || msg.text == null) {
return;
}
Toast toast = new Toast(mContext.getApplicationContext());
LayoutInflater inflate = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(R.layout.stk_event_msg, null);
TextView tv = (TextView) v
.findViewById(com.android.internal.R.id.message);
ImageView iv = (ImageView) v
.findViewById(com.android.internal.R.id.icon);
if (msg.icon != null) {
iv.setImageBitmap(msg.icon);
} else {
iv.setVisibility(View.GONE);
}
/** In case of 'self explanatory' stkapp should display the specified
** icon in proactive command (but not the alpha string).
** If icon is non-self explanatory and if the icon could not be displayed
** then alpha string or text data should be displayed
** Ref: ETSI 102.223,section 6.5.4
**/
if (mCurrentCmd.hasIconLoadFailed() || !msg.iconSelfExplanatory) {
tv.setText(msg.text);
}
toast.setView(v);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
private void launchConfirmationDialog(TextMessage msg) {
msg.title = lastSelectedItem;
Intent newIntent = new Intent(this, StkDialogActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| getFlagActivityNoUserAction(InitiatedByUserAction.unknown));
newIntent.putExtra("TEXT", msg);
startActivity(newIntent);
}
private void launchBrowser(BrowserSettings settings) {
if (settings == null) {
return;
}
// Set browser launch mode
Intent intent = new Intent();
intent.setClassName("com.android.browser",
"com.android.browser.BrowserActivity");
// to launch home page, make sure that data Uri is null.
Uri data = null;
if (settings.url != null) {
data = Uri.parse(settings.url);
}
intent.setData(data);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
switch (settings.mode) {
case USE_EXISTING_BROWSER:
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
case LAUNCH_NEW_BROWSER:
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
break;
case LAUNCH_IF_NOT_ALREADY_LAUNCHED:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
}
// start browser activity
startActivity(intent);
// a small delay, let the browser start, before processing the next command.
// this is good for scenarios where a related DISPLAY TEXT command is
// followed immediately.
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}
private void launchCallMsg() {
TextMessage msg = mCurrentCmd.getCallSettings().callMsg;
if (msg.text == null || msg.text.length() == 0) {
return;
}
msg.title = lastSelectedItem;
Toast toast = Toast.makeText(mContext.getApplicationContext(), msg.text,
Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
private void launchIdleText() {
TextMessage msg = mIdleModeTextCmd.geTextMessage();
if (msg.text == null) {
mNotificationManager.cancel(STK_NOTIFICATION_ID);
} else {
Notification notification = new Notification();
RemoteViews contentView = new RemoteViews(
PACKAGE_NAME,
com.android.internal.R.layout.status_bar_latest_event_content);
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.icon = com.android.internal.R.drawable.stat_notify_sim_toolkit;
/** In case of 'self explanatory' stkapp should display the specified
** icon in proactive command (but not the alpha string).
** If icon is non-self explanatory and if the icon could not be displayed
** then alpha string or text data should be displayed
** Ref: ETSI 102.223,section 6.5.4
**/
if (mCurrentCmd.hasIconLoadFailed() || !msg.iconSelfExplanatory) {
notification.tickerText = msg.text;
contentView.setTextViewText(com.android.internal.R.id.text,
msg.text);
}
if (msg.icon != null) {
contentView.setImageViewBitmap(com.android.internal.R.id.icon,
msg.icon);
} else {
contentView
.setImageViewResource(
com.android.internal.R.id.icon,
com.android.internal.R.drawable.stat_notify_sim_toolkit);
}
notification.contentView = contentView;
notification.contentIntent = PendingIntent.getService(mContext, 0,
new Intent(mContext, StkAppService.class), 0);
mNotificationManager.notify(STK_NOTIFICATION_ID, notification);
}
}
private void launchToneDialog() {
TextMessage toneMsg = mCurrentCmd.geTextMessage();
ToneSettings settings = mCurrentCmd.getToneSettings();
// Start activity only when there is alpha data otherwise play tone
if (toneMsg.text != null) {
CatLog.d(this, "toneMsg.text: " + toneMsg.text + " Starting Activity");
Intent newIntent = new Intent(this, ToneDialog.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| getFlagActivityNoUserAction(InitiatedByUserAction.unknown));
newIntent.putExtra("TEXT", toneMsg);
newIntent.putExtra("TONE", settings);
CatLog.d(this, "Starting Activity based on the ToneDialog Intent");
startActivity(newIntent);
} else {
CatLog.d(this, "toneMsg.text: " + toneMsg.text + " NO Activity, play tone");
onPlayToneNullAlphaTag(toneMsg, settings);
}
}
private void onPlayToneNullAlphaTag(TextMessage toneMsg, ToneSettings settings) {
// Start playing tone and vibration
player = new TonePlayer();
CatLog.d(this, "Play tone settings.tone:" + settings.tone);
player.play(settings.tone);
int timeout = StkApp.calculateDurationInMilis(settings.duration);
CatLog.d(this, "ToneDialog: Tone timeout :" + timeout);
if (timeout == 0) {
timeout = StkApp.TONE_DFEAULT_TIMEOUT;
}
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = MSG_ID_STOP_TONE;
// trigger tone stop after timeout duration
mServiceHandler.sendMessageDelayed(msg, timeout);
if (settings.vibrate) {
mVibrator.vibrate(timeout);
}
}
private String getItemName(int itemId) {
Menu menu = mCurrentCmd.getMenu();
if (menu == null) {
return null;
}
for (Item item : menu.items) {
if (item.id == itemId) {
return item.text;
}
}
return null;
}
private boolean removeMenu() {
try {
if (mCurrentMenu.items.size() == 1 &&
mCurrentMenu.items.get(0) == null) {
return true;
}
} catch (NullPointerException e) {
CatLog.d(this, "Unable to get Menu's items size");
return true;
}
return false;
}
}
| true | true | private void handleCmd(CatCmdMessage cmdMsg) {
if (cmdMsg == null) {
return;
}
// save local reference for state tracking.
mCurrentCmd = cmdMsg;
boolean waitForUsersResponse = true;
CatLog.d(this, cmdMsg.getCmdType().name());
switch (cmdMsg.getCmdType()) {
case DISPLAY_TEXT:
TextMessage msg = cmdMsg.geTextMessage();
//In case when TR already sent no response is expected by Stk app
if (!msg.responseNeeded) {
waitForUsersResponse = false;
}
if (lastSelectedItem != null) {
msg.title = lastSelectedItem;
} else if (mMainCmd != null){
msg.title = mMainCmd.getMenu().title;
} else {
// TODO: get the carrier name from the SIM
msg.title = "";
}
launchTextDialog();
break;
case SELECT_ITEM:
mCurrentMenu = cmdMsg.getMenu();
launchMenuActivity(cmdMsg.getMenu());
break;
case SET_UP_MENU:
mMainCmd = mCurrentCmd;
mCurrentMenu = cmdMsg.getMenu();
if (removeMenu()) {
CatLog.d(this, "Uninstall App");
mCurrentMenu = null;
mMainCmd = null;
StkAppInstaller.unInstall(mContext);
} else {
CatLog.d(this, "Install App");
StkAppInstaller.install(mContext);
}
if (mMenuIsVisibile) {
launchMenuActivity(null);
}
break;
case GET_INPUT:
case GET_INKEY:
launchInputActivity();
break;
case SET_UP_IDLE_MODE_TEXT:
waitForUsersResponse = false;
launchIdleText();
mIdleModeTextCmd = mCurrentCmd;
TextMessage idleModeText = mCurrentCmd.geTextMessage();
// Send intent to ActivityManagerService to get the screen status
Intent idleStkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
if (idleModeText != null) {
if (idleModeText.text != null) {
idleStkIntent.putExtra("SCREEN_STATUS_REQUEST",true);
} else {
idleStkIntent.putExtra("SCREEN_STATUS_REQUEST",false);
launchIdleText();
mIdleModeTextCmd = null;
}
}
CatLog.d(this, "set up idle mode");
mCurrentCmd = mMainCmd;
sendBroadcast(idleStkIntent);
break;
case SEND_DTMF:
case SEND_SMS:
case SEND_SS:
case SEND_USSD:
mCurrentCmd = mMainCmd;
waitForUsersResponse = false;
launchEventMessage();
break;
case LAUNCH_BROWSER:
launchConfirmationDialog(mCurrentCmd.geTextMessage());
break;
case CLOSE_CHANNEL:
case RECEIVE_DATA:
case SEND_DATA:
case GET_CHANNEL_STATUS:
waitForUsersResponse = false;
launchEventMessage();
break;
case OPEN_CHANNEL:
launchConfirmationDialog(mCurrentCmd.getCallSettings().confirmMsg);
break;
case SET_UP_CALL:
TextMessage mesg = mCurrentCmd.getCallSettings().confirmMsg;
if ((mesg != null) && (mesg.text == null || mesg.text.length() == 0)) {
mesg.text = getResources().getString(R.string.default_setup_call_msg);
}
CatLog.d(this, "SET_UP_CALL mesg.text " + mesg.text);
launchConfirmationDialog(mesg);
break;
case PLAY_TONE:
launchToneDialog();
break;
case SET_UP_EVENT_LIST:
mSetupEventListSettings = mCurrentCmd.getSetEventList();
mCurrentSetupEventCmd = mCurrentCmd;
mCurrentCmd = mMainCmd;
if ((mIdleModeTextCmd == null) && (!mDisplayText)) {
for (int i = 0; i < mSetupEventListSettings.eventList.length; i++) {
if (mSetupEventListSettings.eventList[i] == IDLE_SCREEN_AVAILABLE_EVENT) {
CatLog.d(this," IDLE_SCREEN_AVAILABLE_EVENT present in List");
// Request ActivityManagerService to get the screen status
Intent StkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
StkIntent.putExtra("SCREEN_STATUS_REQUEST", true);
sendBroadcast(StkIntent);
break;
}
}
}
break;
}
if (!waitForUsersResponse) {
if (mCmdsQ.size() != 0) {
callDelayedMsg();
} else {
mCmdInProgress = false;
}
}
}
| private void handleCmd(CatCmdMessage cmdMsg) {
if (cmdMsg == null) {
return;
}
// save local reference for state tracking.
mCurrentCmd = cmdMsg;
boolean waitForUsersResponse = true;
CatLog.d(this, cmdMsg.getCmdType().name());
switch (cmdMsg.getCmdType()) {
case DISPLAY_TEXT:
TextMessage msg = cmdMsg.geTextMessage();
//In case when TR already sent no response is expected by Stk app
if (!msg.responseNeeded) {
waitForUsersResponse = false;
}
if (lastSelectedItem != null) {
msg.title = lastSelectedItem;
} else if (mMainCmd != null){
msg.title = mMainCmd.getMenu().title;
} else {
// TODO: get the carrier name from the SIM
msg.title = "";
}
launchTextDialog();
break;
case SELECT_ITEM:
mCurrentMenu = cmdMsg.getMenu();
launchMenuActivity(cmdMsg.getMenu());
break;
case SET_UP_MENU:
mMainCmd = mCurrentCmd;
mCurrentMenu = cmdMsg.getMenu();
if (removeMenu()) {
CatLog.d(this, "Uninstall App");
mCurrentMenu = null;
mMainCmd = null;
StkAppInstaller.unInstall(mContext);
} else {
CatLog.d(this, "Install App");
StkAppInstaller.install(mContext);
}
if (mMenuIsVisibile) {
launchMenuActivity(null);
}
break;
case GET_INPUT:
case GET_INKEY:
launchInputActivity();
break;
case SET_UP_IDLE_MODE_TEXT:
waitForUsersResponse = false;
launchIdleText();
mIdleModeTextCmd = mCurrentCmd;
TextMessage idleModeText = mCurrentCmd.geTextMessage();
// Send intent to ActivityManagerService to get the screen status
Intent idleStkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
if (idleModeText != null) {
if (idleModeText.text != null) {
idleStkIntent.putExtra("SCREEN_STATUS_REQUEST",true);
} else {
idleStkIntent.putExtra("SCREEN_STATUS_REQUEST",false);
launchIdleText();
mIdleModeTextCmd = null;
}
}
CatLog.d(this, "set up idle mode");
mCurrentCmd = mMainCmd;
sendBroadcast(idleStkIntent);
break;
case SEND_DTMF:
case SEND_SMS:
case SEND_SS:
case SEND_USSD:
waitForUsersResponse = false;
launchEventMessage();
break;
case LAUNCH_BROWSER:
launchConfirmationDialog(mCurrentCmd.geTextMessage());
break;
case CLOSE_CHANNEL:
case RECEIVE_DATA:
case SEND_DATA:
case GET_CHANNEL_STATUS:
waitForUsersResponse = false;
launchEventMessage();
break;
case OPEN_CHANNEL:
launchConfirmationDialog(mCurrentCmd.getCallSettings().confirmMsg);
break;
case SET_UP_CALL:
TextMessage mesg = mCurrentCmd.getCallSettings().confirmMsg;
if ((mesg != null) && (mesg.text == null || mesg.text.length() == 0)) {
mesg.text = getResources().getString(R.string.default_setup_call_msg);
}
CatLog.d(this, "SET_UP_CALL mesg.text " + mesg.text);
launchConfirmationDialog(mesg);
break;
case PLAY_TONE:
launchToneDialog();
break;
case SET_UP_EVENT_LIST:
mSetupEventListSettings = mCurrentCmd.getSetEventList();
mCurrentSetupEventCmd = mCurrentCmd;
mCurrentCmd = mMainCmd;
if ((mIdleModeTextCmd == null) && (!mDisplayText)) {
for (int i = 0; i < mSetupEventListSettings.eventList.length; i++) {
if (mSetupEventListSettings.eventList[i] == IDLE_SCREEN_AVAILABLE_EVENT) {
CatLog.d(this," IDLE_SCREEN_AVAILABLE_EVENT present in List");
// Request ActivityManagerService to get the screen status
Intent StkIntent = new Intent(AppInterface.CHECK_SCREEN_IDLE_ACTION);
StkIntent.putExtra("SCREEN_STATUS_REQUEST", true);
sendBroadcast(StkIntent);
break;
}
}
}
break;
}
if (!waitForUsersResponse) {
if (mCmdsQ.size() != 0) {
callDelayedMsg();
} else {
mCmdInProgress = false;
}
}
}
|
diff --git a/phone/com/android/internal/policy/impl/PhoneWindowManager.java b/phone/com/android/internal/policy/impl/PhoneWindowManager.java
index e7a03e4..6708ac0 100755
--- a/phone/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/phone/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -1,2247 +1,2244 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IStatusBar;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Rect;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.LocalPowerManager;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Vibrator;
import android.provider.Settings;
import com.android.internal.policy.PolicyManager;
import com.android.internal.telephony.ITelephony;
import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.IWindowManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowOrientationListener;
import android.view.RawInputEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
import android.view.WindowManagerImpl;
import android.view.WindowManagerPolicy;
import android.view.WindowManagerPolicy.WindowState;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.media.IAudioService;
import android.media.AudioManager;
/**
* WindowManagerPolicy implementation for the Android phone UI. This
* introduces a new method suffix, Lp, for an internal lock of the
* PhoneWindowManager. This is used to protect some internal state, and
* can be acquired with either thw Lw and Li lock held, so has the restrictions
* of both of those when held.
*/
public class PhoneWindowManager implements WindowManagerPolicy {
static final String TAG = "WindowManager";
static final boolean DEBUG = false;
static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
static final boolean DEBUG_LAYOUT = false;
static final boolean SHOW_STARTING_ANIMATIONS = true;
static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
// wallpaper is at the bottom, though the window manager may move it.
static final int WALLPAPER_LAYER = 2;
static final int APPLICATION_LAYER = 2;
static final int PHONE_LAYER = 3;
static final int SEARCH_BAR_LAYER = 4;
static final int STATUS_BAR_PANEL_LAYER = 5;
// toasts and the plugged-in battery thing
static final int TOAST_LAYER = 6;
static final int STATUS_BAR_LAYER = 7;
// SIM errors and unlock. Not sure if this really should be in a high layer.
static final int PRIORITY_PHONE_LAYER = 8;
// like the ANR / app crashed dialogs
static final int SYSTEM_ALERT_LAYER = 9;
// system-level error dialogs
static final int SYSTEM_ERROR_LAYER = 10;
// on-screen keyboards and other such input method user interfaces go here.
static final int INPUT_METHOD_LAYER = 11;
// on-screen keyboards and other such input method user interfaces go here.
static final int INPUT_METHOD_DIALOG_LAYER = 12;
// the keyguard; nothing on top of these can take focus, since they are
// responsible for power management when displayed.
static final int KEYGUARD_LAYER = 13;
static final int KEYGUARD_DIALOG_LAYER = 14;
// things in here CAN NOT take focus, but are shown on top of everything else.
static final int SYSTEM_OVERLAY_LAYER = 15;
static final int APPLICATION_MEDIA_SUBLAYER = -2;
static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
static final int APPLICATION_PANEL_SUBLAYER = 1;
static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
static final float SLIDE_TOUCH_EVENT_SIZE_LIMIT = 0.6f;
// Debugging: set this to have the system act like there is no hard keyboard.
static final boolean KEYBOARD_ALWAYS_HIDDEN = false;
static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final Object mLock = new Object();
Context mContext;
IWindowManager mWindowManager;
LocalPowerManager mPowerManager;
Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
// Vibrator pattern for haptic feedback of a long press.
long[] mLongPressVibePattern;
// Vibrator pattern for haptic feedback of virtual key press.
long[] mVirtualKeyVibePattern;
// Vibrator pattern for haptic feedback during boot when safe mode is disabled.
long[] mSafeModeDisabledVibePattern;
// Vibrator pattern for haptic feedback during boot when safe mode is enabled.
long[] mSafeModeEnabledVibePattern;
/** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
boolean mEnableShiftMenuBugReports = false;
boolean mSafeMode;
WindowState mStatusBar = null;
WindowState mKeyguard = null;
KeyguardViewMediator mKeyguardMediator;
GlobalActions mGlobalActions;
boolean mShouldTurnOffOnKeyUp;
RecentApplicationsDialog mRecentAppsDialog;
Handler mHandler;
final IntentFilter mBatteryStatusFilter = new IntentFilter();
boolean mLidOpen;
int mPlugged;
boolean mRegisteredBatteryReceiver;
int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
int mLidOpenRotation;
int mCarDockRotation;
int mDeskDockRotation;
int mCarDockKeepsScreenOn;
int mDeskDockKeepsScreenOn;
boolean mCarDockEnablesAccelerometer;
boolean mDeskDockEnablesAccelerometer;
int mLidKeyboardAccessibility;
int mLidNavigationAccessibility;
boolean mScreenOn = false;
boolean mOrientationSensorEnabled = false;
int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
static final int DEFAULT_ACCELEROMETER_ROTATION = 0;
int mAccelerometerDefault = DEFAULT_ACCELEROMETER_ROTATION;
boolean mHasSoftInput = false;
// The current size of the screen.
int mW, mH;
// During layout, the current screen borders with all outer decoration
// (status bar, input method dock) accounted for.
int mCurLeft, mCurTop, mCurRight, mCurBottom;
// During layout, the frame in which content should be displayed
// to the user, accounting for all screen decoration except for any
// space they deem as available for other content. This is usually
// the same as mCur*, but may be larger if the screen decor has supplied
// content insets.
int mContentLeft, mContentTop, mContentRight, mContentBottom;
// During layout, the current screen borders along with input method
// windows are placed.
int mDockLeft, mDockTop, mDockRight, mDockBottom;
// During layout, the layer at which the doc window is placed.
int mDockLayer;
static final Rect mTmpParentFrame = new Rect();
static final Rect mTmpDisplayFrame = new Rect();
static final Rect mTmpContentFrame = new Rect();
static final Rect mTmpVisibleFrame = new Rect();
WindowState mTopFullscreenOpaqueWindowState;
boolean mForceStatusBar;
boolean mHideLockScreen;
boolean mDismissKeyguard;
boolean mHomePressed;
Intent mHomeIntent;
Intent mCarDockIntent;
Intent mDeskDockIntent;
boolean mSearchKeyPressed;
boolean mConsumeSearchKeyUp;
static final int ENDCALL_HOME = 0x1;
static final int ENDCALL_SLEEPS = 0x2;
static final int DEFAULT_ENDCALL_BEHAVIOR = ENDCALL_SLEEPS;
int mEndcallBehavior;
int mLandscapeRotation = -1;
int mPortraitRotation = -1;
// Nothing to see here, move along...
int mFancyRotationAnimation;
ShortcutManager mShortcutManager;
PowerManager.WakeLock mBroadcastWakeLock;
PowerManager.WakeLock mDockWakeLock;
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.END_BUTTON_BEHAVIOR), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.ACCELEROMETER_ROTATION), false, this);
resolver.registerContentObserver(Settings.Secure.getUriFor(
Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
"fancy_rotation_anim"), false, this);
update();
}
@Override public void onChange(boolean selfChange) {
update();
try {
mWindowManager.setRotation(USE_LAST_ROTATION, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
public void update() {
ContentResolver resolver = mContext.getContentResolver();
boolean updateRotation = false;
synchronized (mLock) {
mEndcallBehavior = Settings.System.getInt(resolver,
Settings.System.END_BUTTON_BEHAVIOR, DEFAULT_ENDCALL_BEHAVIOR);
mFancyRotationAnimation = Settings.System.getInt(resolver,
"fancy_rotation_anim", 0) != 0 ? 0x80 : 0;
int accelerometerDefault = Settings.System.getInt(resolver,
Settings.System.ACCELEROMETER_ROTATION, DEFAULT_ACCELEROMETER_ROTATION);
if (mAccelerometerDefault != accelerometerDefault) {
mAccelerometerDefault = accelerometerDefault;
updateOrientationListenerLp();
}
String imId = Settings.Secure.getString(resolver,
Settings.Secure.DEFAULT_INPUT_METHOD);
boolean hasSoftInput = imId != null && imId.length() > 0;
if (mHasSoftInput != hasSoftInput) {
mHasSoftInput = hasSoftInput;
updateRotation = true;
}
}
if (updateRotation) {
updateRotation(0);
}
}
}
class MyOrientationListener extends WindowOrientationListener {
MyOrientationListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int rotation) {
// Send updates based on orientation value
if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation);
try {
mWindowManager.setRotation(rotation, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
}
MyOrientationListener mOrientationListener;
boolean useSensorForOrientationLp(int appOrientation) {
// The app says use the sensor.
if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
return true;
}
// The user preference says we can rotate, and the app is willing to rotate.
if (mAccelerometerDefault != 0 &&
(appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) {
return true;
}
// We're in a dock that has a rotation affinity, an the app is willing to rotate.
if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR)
|| (mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) {
// Note we override the nosensor flag here.
if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
return true;
}
}
// Else, don't use the sensor.
return false;
}
/*
* We always let the sensor be switched on by default except when
* the user has explicitly disabled sensor based rotation or when the
* screen is switched off.
*/
boolean needSensorRunningLp() {
if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
// If the application has explicitly requested to follow the
// orientation, then we need to turn the sensor or.
return true;
}
if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR) ||
(mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) {
// enable accelerometer if we are docked in a dock that enables accelerometer
// orientation management,
return true;
}
if (mAccelerometerDefault == 0) {
// If the setting for using the sensor by default is enabled, then
// we will always leave it on. Note that the user could go to
// a window that forces an orientation that does not use the
// sensor and in theory we could turn it off... however, when next
// turning it on we won't have a good value for the current
// orientation for a little bit, which can cause orientation
// changes to lag, so we'd like to keep it always on. (It will
// still be turned off when the screen is off.)
return false;
}
return true;
}
/*
* Various use cases for invoking this function
* screen turning off, should always disable listeners if already enabled
* screen turned on and current app has sensor based orientation, enable listeners
* if not already enabled
* screen turned on and current app does not have sensor orientation, disable listeners if
* already enabled
* screen turning on and current app has sensor based orientation, enable listeners if needed
* screen turning on and current app has nosensor based orientation, do nothing
*/
void updateOrientationListenerLp() {
if (!mOrientationListener.canDetectOrientation()) {
// If sensor is turned off or nonexistent for some reason
return;
}
//Could have been invoked due to screen turning on or off or
//change of the currently visible window's orientation
if (localLOGV) Log.v(TAG, "Screen status="+mScreenOn+
", current orientation="+mCurrentAppOrientation+
", SensorEnabled="+mOrientationSensorEnabled);
boolean disable = true;
if (mScreenOn) {
if (needSensorRunningLp()) {
disable = false;
//enable listener if not already enabled
if (!mOrientationSensorEnabled) {
mOrientationListener.enable();
if(localLOGV) Log.v(TAG, "Enabling listeners");
mOrientationSensorEnabled = true;
}
}
}
//check if sensors need to be disabled
if (disable && mOrientationSensorEnabled) {
mOrientationListener.disable();
if(localLOGV) Log.v(TAG, "Disabling listeners");
mOrientationSensorEnabled = false;
}
}
Runnable mPowerLongPress = new Runnable() {
public void run() {
mShouldTurnOffOnKeyUp = false;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
showGlobalActionsDialog();
}
};
void showGlobalActionsDialog() {
if (mGlobalActions == null) {
mGlobalActions = new GlobalActions(mContext);
}
final boolean keyguardShowing = mKeyguardMediator.isShowingAndNotHidden();
mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
if (keyguardShowing) {
// since it took two seconds of long press to bring this up,
// poke the wake lock so they have some time to see the dialog.
mKeyguardMediator.pokeWakelock();
}
}
boolean isDeviceProvisioned() {
return Settings.Secure.getInt(
mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
}
/**
* When a home-key longpress expires, close other system windows and launch the recent apps
*/
Runnable mHomeLongPress = new Runnable() {
public void run() {
/*
* Eat the longpress so it won't dismiss the recent apps dialog when
* the user lets go of the home key
*/
mHomePressed = false;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
showRecentAppsDialog();
}
};
/**
* Create (if necessary) and launch the recent apps dialog
*/
void showRecentAppsDialog() {
if (mRecentAppsDialog == null) {
mRecentAppsDialog = new RecentApplicationsDialog(mContext);
}
mRecentAppsDialog.show();
}
/** {@inheritDoc} */
public void init(Context context, IWindowManager windowManager,
LocalPowerManager powerManager) {
mContext = context;
mWindowManager = windowManager;
mPowerManager = powerManager;
mKeyguardMediator = new KeyguardViewMediator(context, this, powerManager);
mHandler = new Handler();
mOrientationListener = new MyOrientationListener(mContext);
SettingsObserver settingsObserver = new SettingsObserver(mHandler);
settingsObserver.observe();
mShortcutManager = new ShortcutManager(context, mHandler);
mShortcutManager.observe();
mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mCarDockIntent = new Intent(Intent.ACTION_MAIN, null);
mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null);
mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mBroadcastWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"PhoneWindowManager.mBroadcastWakeLock");
mDockWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,
"PhoneWindowManager.mDockWakeLock");
mDockWakeLock.setReferenceCounted(false);
mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
mLidOpenRotation = readRotation(
com.android.internal.R.integer.config_lidOpenRotation);
mCarDockRotation = readRotation(
com.android.internal.R.integer.config_carDockRotation);
mDeskDockRotation = readRotation(
com.android.internal.R.integer.config_deskDockRotation);
mCarDockKeepsScreenOn = mContext.getResources().getInteger(
com.android.internal.R.integer.config_carDockKeepsScreenOn);
mDeskDockKeepsScreenOn = mContext.getResources().getInteger(
com.android.internal.R.integer.config_deskDockKeepsScreenOn);
mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_carDockEnablesAccelerometer);
mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
mLidKeyboardAccessibility = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lidKeyboardAccessibility);
mLidNavigationAccessibility = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lidNavigationAccessibility);
// register for battery events
mBatteryStatusFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mPlugged = 0;
updatePlugged(context.registerReceiver(null, mBatteryStatusFilter));
// register for dock events
context.registerReceiver(mDockReceiver, new IntentFilter(Intent.ACTION_DOCK_EVENT));
mVibrator = new Vibrator();
mLongPressVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_longPressVibePattern);
mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_virtualKeyVibePattern);
mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeDisabledVibePattern);
mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeEnabledVibePattern);
}
void updatePlugged(Intent powerIntent) {
if (localLOGV) Log.v(TAG, "New battery status: " + powerIntent.getExtras());
if (powerIntent != null) {
mPlugged = powerIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
if (localLOGV) Log.v(TAG, "PLUGGED: " + mPlugged);
}
}
private int readRotation(int resID) {
try {
int rotation = mContext.getResources().getInteger(resID);
switch (rotation) {
case 0:
return Surface.ROTATION_0;
case 90:
return Surface.ROTATION_90;
case 180:
return Surface.ROTATION_180;
case 270:
return Surface.ROTATION_270;
}
} catch (Resources.NotFoundException e) {
// fall through
}
return -1;
}
/** {@inheritDoc} */
public int checkAddPermission(WindowManager.LayoutParams attrs) {
int type = attrs.type;
if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
|| type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
return WindowManagerImpl.ADD_OKAY;
}
String permission = null;
switch (type) {
case TYPE_TOAST:
// XXX right now the app process has complete control over
// this... should introduce a token to let the system
// monitor/control what they are doing.
break;
case TYPE_INPUT_METHOD:
case TYPE_WALLPAPER:
// The window manager will check these.
break;
case TYPE_PHONE:
case TYPE_PRIORITY_PHONE:
case TYPE_SYSTEM_ALERT:
case TYPE_SYSTEM_ERROR:
case TYPE_SYSTEM_OVERLAY:
permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
break;
default:
permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
}
if (permission != null) {
if (mContext.checkCallingOrSelfPermission(permission)
!= PackageManager.PERMISSION_GRANTED) {
return WindowManagerImpl.ADD_PERMISSION_DENIED;
}
}
return WindowManagerImpl.ADD_OKAY;
}
public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
switch (attrs.type) {
case TYPE_SYSTEM_OVERLAY:
case TYPE_TOAST:
// These types of windows can't receive input events.
attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
break;
}
}
void readLidState() {
try {
int sw = mWindowManager.getSwitchState(RawInputEvent.SW_LID);
if (sw >= 0) {
mLidOpen = sw == 0;
}
} catch (RemoteException e) {
// Ignore
}
}
private int determineHiddenState(boolean lidOpen,
int mode, int hiddenValue, int visibleValue) {
switch (mode) {
case 1:
return lidOpen ? visibleValue : hiddenValue;
case 2:
return lidOpen ? hiddenValue : visibleValue;
}
return visibleValue;
}
/** {@inheritDoc} */
public void adjustConfigurationLw(Configuration config) {
readLidState();
final boolean lidOpen = !KEYBOARD_ALWAYS_HIDDEN && mLidOpen;
mPowerManager.setKeyboardVisibility(lidOpen);
config.hardKeyboardHidden = determineHiddenState(lidOpen,
mLidKeyboardAccessibility, Configuration.HARDKEYBOARDHIDDEN_YES,
Configuration.HARDKEYBOARDHIDDEN_NO);
config.navigationHidden = determineHiddenState(lidOpen,
mLidNavigationAccessibility, Configuration.NAVIGATIONHIDDEN_YES,
Configuration.NAVIGATIONHIDDEN_NO);
config.keyboardHidden = (config.hardKeyboardHidden
== Configuration.HARDKEYBOARDHIDDEN_NO || mHasSoftInput)
? Configuration.KEYBOARDHIDDEN_NO
: Configuration.KEYBOARDHIDDEN_YES;
}
public boolean isCheekPressedAgainstScreen(MotionEvent ev) {
if(ev.getSize() > SLIDE_TOUCH_EVENT_SIZE_LIMIT) {
return true;
}
int size = ev.getHistorySize();
for(int i = 0; i < size; i++) {
if(ev.getHistoricalSize(i) > SLIDE_TOUCH_EVENT_SIZE_LIMIT) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int windowTypeToLayerLw(int type) {
if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
return APPLICATION_LAYER;
}
switch (type) {
case TYPE_STATUS_BAR:
return STATUS_BAR_LAYER;
case TYPE_STATUS_BAR_PANEL:
return STATUS_BAR_PANEL_LAYER;
case TYPE_SEARCH_BAR:
return SEARCH_BAR_LAYER;
case TYPE_PHONE:
return PHONE_LAYER;
case TYPE_KEYGUARD:
return KEYGUARD_LAYER;
case TYPE_KEYGUARD_DIALOG:
return KEYGUARD_DIALOG_LAYER;
case TYPE_SYSTEM_ALERT:
return SYSTEM_ALERT_LAYER;
case TYPE_SYSTEM_ERROR:
return SYSTEM_ERROR_LAYER;
case TYPE_INPUT_METHOD:
return INPUT_METHOD_LAYER;
case TYPE_INPUT_METHOD_DIALOG:
return INPUT_METHOD_DIALOG_LAYER;
case TYPE_SYSTEM_OVERLAY:
return SYSTEM_OVERLAY_LAYER;
case TYPE_PRIORITY_PHONE:
return PRIORITY_PHONE_LAYER;
case TYPE_TOAST:
return TOAST_LAYER;
case TYPE_WALLPAPER:
return WALLPAPER_LAYER;
}
Log.e(TAG, "Unknown window type: " + type);
return APPLICATION_LAYER;
}
/** {@inheritDoc} */
public int subWindowTypeToLayerLw(int type) {
switch (type) {
case TYPE_APPLICATION_PANEL:
case TYPE_APPLICATION_ATTACHED_DIALOG:
return APPLICATION_PANEL_SUBLAYER;
case TYPE_APPLICATION_MEDIA:
return APPLICATION_MEDIA_SUBLAYER;
case TYPE_APPLICATION_MEDIA_OVERLAY:
return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
case TYPE_APPLICATION_SUB_PANEL:
return APPLICATION_SUB_PANEL_SUBLAYER;
}
Log.e(TAG, "Unknown sub-window type: " + type);
return 0;
}
public int getMaxWallpaperLayer() {
return STATUS_BAR_LAYER;
}
public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
}
public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
return attrs.type != WindowManager.LayoutParams.TYPE_STATUS_BAR
&& attrs.type != WindowManager.LayoutParams.TYPE_WALLPAPER;
}
/** {@inheritDoc} */
public View addStartingWindow(IBinder appToken, String packageName,
int theme, CharSequence nonLocalizedLabel,
int labelRes, int icon) {
if (!SHOW_STARTING_ANIMATIONS) {
return null;
}
if (packageName == null) {
return null;
}
Context context = mContext;
boolean setTheme = false;
//Log.i(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel="
// + nonLocalizedLabel + " theme=" + Integer.toHexString(theme));
if (theme != 0 || labelRes != 0) {
try {
context = context.createPackageContext(packageName, 0);
if (theme != 0) {
context.setTheme(theme);
setTheme = true;
}
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
if (!setTheme) {
context.setTheme(com.android.internal.R.style.Theme);
}
Window win = PolicyManager.makeNewWindow(context);
if (win.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowDisablePreview, false)) {
return null;
}
Resources r = context.getResources();
win.setTitle(r.getText(labelRes, nonLocalizedLabel));
win.setType(
WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
// Force the window flags: this is a fake window, so it is not really
// touchable or focusable by the user. We also add in the ALT_FOCUSABLE_IM
// flag because we do know that the next window will take input
// focus, so we want to get the IME window up on top of us right away.
win.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
win.setLayout(WindowManager.LayoutParams.FILL_PARENT,
WindowManager.LayoutParams.FILL_PARENT);
final WindowManager.LayoutParams params = win.getAttributes();
params.token = appToken;
params.packageName = packageName;
params.windowAnimations = win.getWindowStyle().getResourceId(
com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
params.setTitle("Starting " + packageName);
try {
WindowManagerImpl wm = (WindowManagerImpl)
context.getSystemService(Context.WINDOW_SERVICE);
View view = win.getDecorView();
if (win.isFloating()) {
// Whoops, there is no way to display an animation/preview
// of such a thing! After all that work... let's skip it.
// (Note that we must do this here because it is in
// getDecorView() where the theme is evaluated... maybe
// we should peek the floating attribute from the theme
// earlier.)
return null;
}
if (localLOGV) Log.v(
TAG, "Adding starting window for " + packageName
+ " / " + appToken + ": "
+ (view.getParent() != null ? view : null));
wm.addView(view, params);
// Only return the view if it was successfully added to the
// window manager... which we can tell by it having a parent.
return view.getParent() != null ? view : null;
} catch (WindowManagerImpl.BadTokenException e) {
// ignore
Log.w(TAG, appToken + " already running, starting window not displayed");
}
return null;
}
/** {@inheritDoc} */
public void removeStartingWindow(IBinder appToken, View window) {
// RuntimeException e = new RuntimeException();
// Log.i(TAG, "remove " + appToken + " " + window, e);
if (localLOGV) Log.v(
TAG, "Removing starting window for " + appToken + ": " + window);
if (window != null) {
WindowManagerImpl wm = (WindowManagerImpl) mContext.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(window);
}
}
/**
* Preflight adding a window to the system.
*
* Currently enforces that three window types are singletons:
* <ul>
* <li>STATUS_BAR_TYPE</li>
* <li>KEYGUARD_TYPE</li>
* </ul>
*
* @param win The window to be added
* @param attrs Information about the window to be added
*
* @return If ok, WindowManagerImpl.ADD_OKAY. If too many singletons, WindowManagerImpl.ADD_MULTIPLE_SINGLETON
*/
public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
switch (attrs.type) {
case TYPE_STATUS_BAR:
if (mStatusBar != null) {
return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
}
mStatusBar = win;
break;
case TYPE_KEYGUARD:
if (mKeyguard != null) {
return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
}
mKeyguard = win;
break;
}
return WindowManagerImpl.ADD_OKAY;
}
/** {@inheritDoc} */
public void removeWindowLw(WindowState win) {
if (mStatusBar == win) {
mStatusBar = null;
}
else if (mKeyguard == win) {
mKeyguard = null;
}
}
static final boolean PRINT_ANIM = false;
/** {@inheritDoc} */
public int selectAnimationLw(WindowState win, int transit) {
if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
+ ": transit=" + transit);
if (transit == TRANSIT_PREVIEW_DONE) {
if (win.hasAppShownWindows()) {
if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
return com.android.internal.R.anim.app_starting_exit;
}
}
return 0;
}
public Animation createForceHideEnterAnimation() {
return AnimationUtils.loadAnimation(mContext,
com.android.internal.R.anim.lock_screen_behind_enter);
}
static ITelephony getPhoneInterface() {
return ITelephony.Stub.asInterface(ServiceManager.checkService(Context.TELEPHONY_SERVICE));
}
static IAudioService getAudioInterface() {
return IAudioService.Stub.asInterface(ServiceManager.checkService(Context.AUDIO_SERVICE));
}
boolean keyguardOn() {
return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
}
private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
};
/** {@inheritDoc} */
public boolean interceptKeyTi(WindowState win, int code, int metaKeys, boolean down,
int repeatCount, int flags) {
boolean keyguardOn = keyguardOn();
if (false) {
Log.d(TAG, "interceptKeyTi code=" + code + " down=" + down + " repeatCount="
+ repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed);
}
// Clear a pending HOME longpress if the user releases Home
// TODO: This could probably be inside the next bit of logic, but that code
// turned out to be a bit fragile so I'm doing it here explicitly, for now.
if ((code == KeyEvent.KEYCODE_HOME) && !down) {
mHandler.removeCallbacks(mHomeLongPress);
}
// If the HOME button is currently being held, then we do special
// chording with it.
if (mHomePressed) {
// If we have released the home key, and didn't do anything else
// while it was pressed, then it is time to go home!
if (code == KeyEvent.KEYCODE_HOME) {
if (!down) {
mHomePressed = false;
if ((flags&KeyEvent.FLAG_CANCELED) == 0) {
// If an incoming call is ringing, HOME is totally disabled.
// (The user is already on the InCallScreen at this point,
// and his ONLY options are to answer or reject the call.)
boolean incomingRinging = false;
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
incomingRinging = phoneServ.isRinging();
} else {
Log.w(TAG, "Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
}
if (incomingRinging) {
Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
} else {
launchHomeFromHotKey();
}
} else {
Log.i(TAG, "Ignoring HOME; event canceled.");
}
}
}
return true;
}
// First we always handle the home key here, so applications
// can never break it, although if keyguard is on, we do let
// it handle it, because that gives us the correct 5 second
// timeout.
if (code == KeyEvent.KEYCODE_HOME) {
// If a system window has focus, then it doesn't make sense
// right now to interact with applications.
WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
if (attrs != null) {
final int type = attrs.type;
if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
|| type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
// the "app" is keyguard, so give it the key
return false;
}
final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
for (int i=0; i<typeCount; i++) {
if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
// don't do anything, but also don't pass it to the app
return true;
}
}
}
if (down && repeatCount == 0) {
if (!keyguardOn) {
mHandler.postDelayed(mHomeLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
}
mHomePressed = true;
}
return true;
} else if (code == KeyEvent.KEYCODE_MENU) {
// Hijack modified menu keys for debugging features
final int chordBug = KeyEvent.META_SHIFT_ON;
if (down && repeatCount == 0) {
if (mEnableShiftMenuBugReports && (metaKeys & chordBug) == chordBug) {
Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
mContext.sendOrderedBroadcast(intent, null);
return true;
} else if (SHOW_PROCESSES_ON_ALT_MENU &&
(metaKeys & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
Intent service = new Intent();
service.setClassName(mContext, "com.android.server.LoadAverageService");
ContentResolver res = mContext.getContentResolver();
boolean shown = Settings.System.getInt(
res, Settings.System.SHOW_PROCESSES, 0) != 0;
if (!shown) {
mContext.startService(service);
} else {
mContext.stopService(service);
}
Settings.System.putInt(
res, Settings.System.SHOW_PROCESSES, shown ? 0 : 1);
return true;
}
}
} else if (code == KeyEvent.KEYCODE_NOTIFICATION) {
if (down) {
// this key doesn't exist on current hardware, but if a device
// didn't have a touchscreen, it would want one of these to open
// the status bar.
IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar"));
if (sbs != null) {
try {
sbs.toggle();
} catch (RemoteException e) {
// we're screwed anyway, since it's in this process
throw new RuntimeException(e);
}
}
}
return true;
} else if (code == KeyEvent.KEYCODE_SEARCH) {
if (down) {
if (repeatCount == 0) {
mSearchKeyPressed = true;
}
} else {
mSearchKeyPressed = false;
if (mConsumeSearchKeyUp) {
// Consume the up-event
mConsumeSearchKeyUp = false;
return true;
}
}
}
// Shortcuts are invoked through Search+key, so intercept those here
if (mSearchKeyPressed) {
if (down && repeatCount == 0 && !keyguardOn) {
Intent shortcutIntent = mShortcutManager.getIntent(code, metaKeys);
if (shortcutIntent != null) {
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(shortcutIntent);
/*
* We launched an app, so the up-event of the search key
* should be consumed
*/
mConsumeSearchKeyUp = true;
return true;
}
}
}
return false;
}
/**
* A home key -> launch home action was detected. Take the appropriate action
* given the situation with the keyguard.
*/
void launchHomeFromHotKey() {
if (mKeyguardMediator.isShowingAndNotHidden()) {
// don't launch home if keyguard showing
} else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
// when in keyguard restricted mode, must first verify unlock
// before launching home
mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
public void onKeyguardExitResult(boolean success) {
if (success) {
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
startDockOrHome();
}
}
});
} else {
// no keyguard stuff to worry about, just launch home!
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
startDockOrHome();
}
}
public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
final int fl = attrs.flags;
if ((fl &
(FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
== (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
contentInset.set(mCurLeft, mCurTop, mW - mCurRight, mH - mCurBottom);
} else {
contentInset.setEmpty();
}
}
/** {@inheritDoc} */
public void beginLayoutLw(int displayWidth, int displayHeight) {
mW = displayWidth;
mH = displayHeight;
mDockLeft = mContentLeft = mCurLeft = 0;
mDockTop = mContentTop = mCurTop = 0;
mDockRight = mContentRight = mCurRight = displayWidth;
mDockBottom = mContentBottom = mCurBottom = displayHeight;
mDockLayer = 0x10000000;
mTopFullscreenOpaqueWindowState = null;
mForceStatusBar = false;
mHideLockScreen = false;
mDismissKeyguard = false;
// decide where the status bar goes ahead of time
if (mStatusBar != null) {
final Rect pf = mTmpParentFrame;
final Rect df = mTmpDisplayFrame;
final Rect vf = mTmpVisibleFrame;
pf.left = df.left = vf.left = 0;
pf.top = df.top = vf.top = 0;
pf.right = df.right = vf.right = displayWidth;
pf.bottom = df.bottom = vf.bottom = displayHeight;
mStatusBar.computeFrameLw(pf, df, vf, vf);
if (mStatusBar.isVisibleLw()) {
// If the status bar is hidden, we don't want to cause
// windows behind it to scroll.
mDockTop = mContentTop = mCurTop = mStatusBar.getFrameLw().bottom;
if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mDockBottom="
+ mDockBottom + " mContentBottom="
+ mContentBottom + " mCurBottom=" + mCurBottom);
}
}
}
void setAttachedWindowFrames(WindowState win, int fl, int sim,
WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
// Here's a special case: if this attached window is a panel that is
// above the dock window, and the window it is attached to is below
// the dock window, then the frames we computed for the window it is
// attached to can not be used because the dock is effectively part
// of the underlying window and the attached window is floating on top
// of the whole thing. So, we ignore the attached window and explicitly
// compute the frames that would be appropriate without the dock.
df.left = cf.left = vf.left = mDockLeft;
df.top = cf.top = vf.top = mDockTop;
df.right = cf.right = vf.right = mDockRight;
df.bottom = cf.bottom = vf.bottom = mDockBottom;
} else {
// The effective display frame of the attached window depends on
// whether it is taking care of insetting its content. If not,
// we need to use the parent's content frame so that the entire
// window is positioned within that content. Otherwise we can use
// the display frame and let the attached window take care of
// positioning its content appropriately.
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
cf.set(attached.getDisplayFrameLw());
} else {
// If the window is resizing, then we want to base the content
// frame on our attached content frame to resize... however,
// things can be tricky if the attached window is NOT in resize
// mode, in which case its content frame will be larger.
// Ungh. So to deal with that, make sure the content frame
// we end up using is not covering the IM dock.
cf.set(attached.getContentFrameLw());
if (attached.getSurfaceLayer() < mDockLayer) {
if (cf.left < mContentLeft) cf.left = mContentLeft;
if (cf.top < mContentTop) cf.top = mContentTop;
if (cf.right > mContentRight) cf.right = mContentRight;
if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
}
}
df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
vf.set(attached.getVisibleFrameLw());
}
// The LAYOUT_IN_SCREEN flag is used to determine whether the attached
// window should be positioned relative to its parent or the entire
// screen.
pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
? attached.getFrameLw() : df);
}
/** {@inheritDoc} */
public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
WindowState attached) {
// we've already done the status bar
if (win == mStatusBar) {
return;
}
if (false) {
if ("com.google.android.youtube".equals(attrs.packageName)
&& attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
Log.i(TAG, "GOTCHA!");
}
}
final int fl = attrs.flags;
final int sim = attrs.softInputMode;
final Rect pf = mTmpParentFrame;
final Rect df = mTmpDisplayFrame;
final Rect cf = mTmpContentFrame;
final Rect vf = mTmpVisibleFrame;
if (attrs.type == TYPE_INPUT_METHOD) {
pf.left = df.left = cf.left = vf.left = mDockLeft;
pf.top = df.top = cf.top = vf.top = mDockTop;
pf.right = df.right = cf.right = vf.right = mDockRight;
pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
// IM dock windows always go to the bottom of the screen.
attrs.gravity = Gravity.BOTTOM;
mDockLayer = win.getSurfaceLayer();
} else {
if ((fl &
(FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
== (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
// This is the case for a normal activity window: we want it
// to cover all of the screen space, and it can take care of
// moving its contents to account for screen decorations that
// intrude into that space.
if (attached != null) {
// If this window is attached to another, our display
// frame is the same as the one we are attached to.
setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf);
} else {
pf.left = df.left = 0;
pf.top = df.top = 0;
pf.right = df.right = mW;
pf.bottom = df.bottom = mH;
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
cf.left = mDockLeft;
cf.top = mDockTop;
cf.right = mDockRight;
cf.bottom = mDockBottom;
} else {
cf.left = mContentLeft;
cf.top = mContentTop;
cf.right = mContentRight;
cf.bottom = mContentBottom;
}
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
}
} else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0) {
// A window that has requested to fill the entire screen just
// gets everything, period.
pf.left = df.left = cf.left = 0;
pf.top = df.top = cf.top = 0;
pf.right = df.right = cf.right = mW;
pf.bottom = df.bottom = cf.bottom = mH;
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
} else if (attached != null) {
// A child window should be placed inside of the same visible
// frame that its parent had.
setAttachedWindowFrames(win, fl, sim, attached, false, pf, df, cf, vf);
} else {
// Otherwise, a normal window must be placed inside the content
// of all screen decorations.
pf.left = mContentLeft;
pf.top = mContentTop;
pf.right = mContentRight;
pf.bottom = mContentBottom;
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
df.left = cf.left = mDockLeft;
df.top = cf.top = mDockTop;
df.right = cf.right = mDockRight;
df.bottom = cf.bottom = mDockBottom;
} else {
df.left = cf.left = mContentLeft;
df.top = cf.top = mContentTop;
df.right = cf.right = mContentRight;
df.bottom = cf.bottom = mContentBottom;
}
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
}
}
if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
}
if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
+ ": sim=#" + Integer.toHexString(sim)
+ " pf=" + pf.toShortString() + " df=" + df.toShortString()
+ " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
if (false) {
if ("com.google.android.youtube".equals(attrs.packageName)
&& attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
if (true || localLOGV) Log.v(TAG, "Computing frame of " + win +
": sim=#" + Integer.toHexString(sim)
+ " pf=" + pf.toShortString() + " df=" + df.toShortString()
+ " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
}
}
win.computeFrameLw(pf, df, cf, vf);
if (mTopFullscreenOpaqueWindowState == null &&
win.isVisibleOrBehindKeyguardLw()) {
if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
mForceStatusBar = true;
}
if (attrs.type >= FIRST_APPLICATION_WINDOW
&& attrs.type <= LAST_APPLICATION_WINDOW
&& win.fillsScreenLw(mW, mH, false, false)) {
if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
mTopFullscreenOpaqueWindowState = win;
if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
mHideLockScreen = true;
}
}
if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
mDismissKeyguard = true;
}
}
// Dock windows carve out the bottom of the screen, so normal windows
// can't appear underneath them.
if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) {
int top = win.getContentFrameLw().top;
top += win.getGivenContentInsetsLw().top;
if (mContentBottom > top) {
mContentBottom = top;
}
top = win.getVisibleFrameLw().top;
top += win.getGivenVisibleInsetsLw().top;
if (mCurBottom > top) {
mCurBottom = top;
}
if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
+ mDockBottom + " mContentBottom="
+ mContentBottom + " mCurBottom=" + mCurBottom);
}
}
/** {@inheritDoc} */
public int finishLayoutLw() {
int changes = 0;
boolean hiding = false;
if (mStatusBar != null) {
if (localLOGV) Log.i(TAG, "force=" + mForceStatusBar
+ " top=" + mTopFullscreenOpaqueWindowState);
if (mForceStatusBar) {
if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
} else if (mTopFullscreenOpaqueWindowState != null) {
//Log.i(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
// + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
//Log.i(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs());
WindowManager.LayoutParams lp =
mTopFullscreenOpaqueWindowState.getAttrs();
boolean hideStatusBar =
(lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
if (hideStatusBar) {
if (DEBUG_LAYOUT) Log.v(TAG, "Hiding status bar");
if (mStatusBar.hideLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
hiding = true;
} else {
if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
}
}
}
// Hide the key guard if a visible window explicitly specifies that it wants to be displayed
// when the screen is locked
if (mKeyguard != null) {
if (localLOGV) Log.v(TAG, "finishLayoutLw::mHideKeyguard="+mHideLockScreen);
if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
if (mKeyguard.hideLw(false)) {
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
if (mKeyguardMediator.isShowing()) {
mHandler.post(new Runnable() {
public void run() {
mKeyguardMediator.keyguardDone(false, false);
}
});
}
} else if (mHideLockScreen) {
if (mKeyguard.hideLw(false)) {
mKeyguardMediator.setHidden(true);
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
} else {
if (mKeyguard.showLw(false)) {
mKeyguardMediator.setHidden(false);
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
}
}
if (changes != 0 && hiding) {
IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar"));
if (sbs != null) {
try {
// Make sure the window shade is hidden.
sbs.deactivate();
} catch (RemoteException e) {
}
}
}
return changes;
}
/** {@inheritDoc} */
public void beginAnimationLw(int displayWidth, int displayHeight) {
}
/** {@inheritDoc} */
public void animatingWindowLw(WindowState win,
WindowManager.LayoutParams attrs) {
}
/** {@inheritDoc} */
public boolean finishAnimationLw() {
return false;
}
/** {@inheritDoc} */
public boolean preprocessInputEventTq(RawInputEvent event) {
switch (event.type) {
case RawInputEvent.EV_SW:
if (event.keycode == RawInputEvent.SW_LID) {
// lid changed state
mLidOpen = event.value == 0;
boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen);
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
if (awakeNow) {
// If the lid opening and we don't have to keep the
// keyguard up, then we can turn on the screen
// immediately.
mKeyguardMediator.pokeWakelock();
} else if (keyguardIsShowingTq()) {
if (mLidOpen) {
// If we are opening the lid and not hiding the
// keyguard, then we need to have it turn on the
// screen once it is shown.
mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
KeyEvent.KEYCODE_POWER);
}
} else {
// Light up the keyboard if we are sliding up.
if (mLidOpen) {
mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
LocalPowerManager.BUTTON_EVENT);
} else {
mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
LocalPowerManager.OTHER_EVENT);
}
}
}
}
return false;
}
/** {@inheritDoc} */
public boolean isAppSwitchKeyTqTiLwLi(int keycode) {
return keycode == KeyEvent.KEYCODE_HOME
|| keycode == KeyEvent.KEYCODE_ENDCALL;
}
/** {@inheritDoc} */
public boolean isMovementKeyTi(int keycode) {
switch (keycode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
return true;
}
return false;
}
/**
* @return Whether a telephone call is in progress right now.
*/
boolean isInCall() {
final ITelephony phone = getPhoneInterface();
if (phone == null) {
Log.w(TAG, "couldn't get ITelephony reference");
return false;
}
try {
return phone.isOffhook();
} catch (RemoteException e) {
Log.w(TAG, "ITelephony.isOffhhook threw RemoteException " + e);
return false;
}
}
/**
* @return Whether music is being played right now.
*/
boolean isMusicActive() {
final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
if (am == null) {
Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
return false;
}
return am.isMusicActive();
}
/**
* Tell the audio service to adjust the volume appropriate to the event.
* @param keycode
*/
void handleVolumeKey(int stream, int keycode) {
final IAudioService audio = getAudioInterface();
if (audio == null) {
Log.w(TAG, "handleVolumeKey: couldn't get IAudioService reference");
return;
}
try {
// since audio is playing, we shouldn't have to hold a wake lock
// during the call, but we do it as a precaution for the rare possibility
// that the music stops right before we call this
mBroadcastWakeLock.acquire();
audio.adjustStreamVolume(stream,
keycode == KeyEvent.KEYCODE_VOLUME_UP
? AudioManager.ADJUST_RAISE
: AudioManager.ADJUST_LOWER,
0);
} catch (RemoteException e) {
Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
} finally {
mBroadcastWakeLock.release();
}
}
static boolean isMediaKey(int code) {
if (code == KeyEvent.KEYCODE_HEADSETHOOK ||
code == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ||
code == KeyEvent.KEYCODE_MEDIA_STOP ||
code == KeyEvent.KEYCODE_MEDIA_NEXT ||
code == KeyEvent.KEYCODE_MEDIA_PREVIOUS ||
code == KeyEvent.KEYCODE_MEDIA_PREVIOUS ||
code == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) {
return true;
}
return false;
}
/** {@inheritDoc} */
public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
// If screen is off then we treat the case where the keyguard is open but hidden
// the same as if it were open and in front.
// This will prevent any keys other than the power button from waking the screen
// when the keyguard is hidden by another activity.
final boolean keyguardActive = (screenIsOn ?
mKeyguardMediator.isShowingAndNotHidden() :
mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
+ // when keyguard is showing and screen off, we need
+ // to handle the volume key for calls and music here
if (isInCall()) {
- // if the keyguard didn't wake the device, we are in call, and
- // it is a volume key, turn on the screen so that the user
- // can more easily adjust the in call volume.
- mKeyguardMediator.pokeWakelock();
+ handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
} else if (isMusicActive()) {
- // when keyguard is showing and screen off, we need
- // to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome, sleeps;
if (code == KeyEvent.KEYCODE_ENDCALL) {
gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
} else {
gohome = false;
sleeps = true;
}
if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
class PassHeadsetKey implements Runnable {
KeyEvent mKeyEvent;
PassHeadsetKey(KeyEvent keyEvent) {
mKeyEvent = keyEvent;
}
public void run() {
if (ActivityManagerNative.isSystemReady()) {
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
intent.putExtra(Intent.EXTRA_KEY_EVENT, mKeyEvent);
mContext.sendOrderedBroadcast(intent, null, mBroadcastDone,
mHandler, Activity.RESULT_OK, null, null);
}
}
}
BroadcastReceiver mBroadcastDone = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
mBroadcastWakeLock.release();
}
};
BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
updatePlugged(intent);
updateDockKeepingScreenOn();
}
};
BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
Intent.EXTRA_DOCK_STATE_UNDOCKED);
boolean watchBattery = mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
if (watchBattery != mRegisteredBatteryReceiver) {
mRegisteredBatteryReceiver = watchBattery;
if (watchBattery) {
updatePlugged(mContext.registerReceiver(mBatteryReceiver,
mBatteryStatusFilter));
} else {
mContext.unregisterReceiver(mBatteryReceiver);
}
}
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
updateDockKeepingScreenOn();
updateOrientationListenerLp();
}
};
/** {@inheritDoc} */
public boolean isWakeRelMovementTq(int device, int classes,
RawInputEvent event) {
// if it's tagged with one of the wake bits, it wakes up the device
return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0);
}
/** {@inheritDoc} */
public boolean isWakeAbsMovementTq(int device, int classes,
RawInputEvent event) {
// if it's tagged with one of the wake bits, it wakes up the device
return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0);
}
/**
* Given the current state of the world, should this key wake up the device?
*/
protected boolean isWakeKeyTq(RawInputEvent event) {
// There are not key maps for trackball devices, but we'd still
// like to have pressing it wake the device up, so force it here.
int keycode = event.keycode;
int flags = event.flags;
if (keycode == RawInputEvent.BTN_MOUSE) {
flags |= WindowManagerPolicy.FLAG_WAKE;
}
return (flags
& (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
}
/** {@inheritDoc} */
public void screenTurnedOff(int why) {
EventLog.writeEvent(70000, 0);
mKeyguardMediator.onScreenTurnedOff(why);
synchronized (mLock) {
mScreenOn = false;
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void screenTurnedOn() {
EventLog.writeEvent(70000, 1);
mKeyguardMediator.onScreenTurnedOn();
synchronized (mLock) {
mScreenOn = true;
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void enableKeyguard(boolean enabled) {
mKeyguardMediator.setKeyguardEnabled(enabled);
}
/** {@inheritDoc} */
public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
mKeyguardMediator.verifyUnlock(callback);
}
private boolean keyguardIsShowingTq() {
return mKeyguardMediator.isShowingAndNotHidden();
}
/** {@inheritDoc} */
public boolean inKeyguardRestrictedKeyInputMode() {
return mKeyguardMediator.isInputRestricted();
}
void sendCloseSystemWindows() {
sendCloseSystemWindows(mContext, null);
}
void sendCloseSystemWindows(String reason) {
sendCloseSystemWindows(mContext, reason);
}
static void sendCloseSystemWindows(Context context, String reason) {
if (ActivityManagerNative.isSystemReady()) {
try {
ActivityManagerNative.getDefault().closeSystemDialogs(reason);
} catch (RemoteException e) {
}
}
}
public int rotationForOrientationLw(int orientation, int lastRotation,
boolean displayEnabled) {
if (mPortraitRotation < 0) {
// Initialize the rotation angles for each orientation once.
Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
if (d.getWidth() > d.getHeight()) {
mPortraitRotation = Surface.ROTATION_90;
mLandscapeRotation = Surface.ROTATION_0;
} else {
mPortraitRotation = Surface.ROTATION_0;
mLandscapeRotation = Surface.ROTATION_90;
}
}
synchronized (mLock) {
switch (orientation) {
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
//always return landscape if orientation set to landscape
return mLandscapeRotation;
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
//always return portrait if orientation set to portrait
return mPortraitRotation;
}
// case for nosensor meaning ignore sensor and consider only lid
// or orientation sensor disabled
//or case.unspecified
if (mLidOpen) {
return mLidOpenRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
return mCarDockRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
return mDeskDockRotation;
} else {
if (useSensorForOrientationLp(orientation)) {
// If the user has enabled auto rotation by default, do it.
int curRotation = mOrientationListener.getCurrentRotation();
return curRotation >= 0 ? curRotation : lastRotation;
}
return Surface.ROTATION_0;
}
}
}
public boolean detectSafeMode() {
try {
int menuState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_MENU);
int sState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_S);
int dpadState = mWindowManager.getDPadKeycodeState(KeyEvent.KEYCODE_DPAD_CENTER);
int trackballState = mWindowManager.getTrackballScancodeState(RawInputEvent.BTN_MOUSE);
mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0;
performHapticFeedbackLw(null, mSafeMode
? HapticFeedbackConstants.SAFE_MODE_ENABLED
: HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
if (mSafeMode) {
Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
+ " dpad=" + dpadState + " trackball=" + trackballState + ")");
} else {
Log.i(TAG, "SAFE MODE not enabled");
}
return mSafeMode;
} catch (RemoteException e) {
// Doom! (it's also local)
throw new RuntimeException("window manager dead");
}
}
static long[] getLongIntArray(Resources r, int resid) {
int[] ar = r.getIntArray(resid);
if (ar == null) {
return null;
}
long[] out = new long[ar.length];
for (int i=0; i<ar.length; i++) {
out[i] = ar[i];
}
return out;
}
/** {@inheritDoc} */
public void systemReady() {
// tell the keyguard
mKeyguardMediator.onSystemReady();
android.os.SystemProperties.set("dev.bootcomplete", "1");
synchronized (mLock) {
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void enableScreenAfterBoot() {
readLidState();
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
}
void updateDockKeepingScreenOn() {
if (mPlugged != 0) {
if (localLOGV) Log.v(TAG, "Update: mDockState=" + mDockState
+ " mPlugged=" + mPlugged
+ " mCarDockKeepsScreenOn" + mCarDockKeepsScreenOn
+ " mDeskDockKeepsScreenOn" + mDeskDockKeepsScreenOn);
if (mDockState == Intent.EXTRA_DOCK_STATE_CAR
&& (mPlugged&mCarDockKeepsScreenOn) != 0) {
if (!mDockWakeLock.isHeld()) {
mDockWakeLock.acquire();
}
return;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK
&& (mPlugged&mDeskDockKeepsScreenOn) != 0) {
if (!mDockWakeLock.isHeld()) {
mDockWakeLock.acquire();
}
return;
}
}
if (mDockWakeLock.isHeld()) {
mDockWakeLock.release();
}
}
void updateRotation(int animFlags) {
mPowerManager.setKeyboardVisibility(mLidOpen);
int rotation = Surface.ROTATION_0;
if (mLidOpen) {
rotation = mLidOpenRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
rotation = mCarDockRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
rotation = mDeskDockRotation;
}
//if lid is closed orientation will be portrait
try {
//set orientation on WindowManager
mWindowManager.setRotation(rotation, true,
mFancyRotationAnimation | animFlags);
} catch (RemoteException e) {
// Ignore
}
}
/**
* Return an Intent to launch the currently active dock as home. Returns
* null if the standard home should be launched.
* @return
*/
Intent createHomeDockIntent() {
if (mDockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
return null;
}
Intent intent;
if (mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
intent = mCarDockIntent;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
intent = mDeskDockIntent;
} else {
Log.w(TAG, "Unknown dock state: " + mDockState);
return null;
}
ActivityInfo ai = intent.resolveActivityInfo(
mContext.getPackageManager(), PackageManager.GET_META_DATA);
if (ai == null) {
return null;
}
if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
intent = new Intent(intent);
intent.setClassName(ai.packageName, ai.name);
return intent;
}
return null;
}
void startDockOrHome() {
Intent dock = createHomeDockIntent();
if (dock != null) {
try {
mContext.startActivity(dock);
return;
} catch (ActivityNotFoundException e) {
}
}
mContext.startActivity(mHomeIntent);
}
/**
* goes to the home screen
* @return whether it did anything
*/
boolean goHome() {
if (false) {
// This code always brings home to the front.
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows();
startDockOrHome();
} else {
// This code brings home to the front or, if it is already
// at the front, puts the device to sleep.
try {
ActivityManagerNative.getDefault().stopAppSwitches();
sendCloseSystemWindows();
Intent dock = createHomeDockIntent();
if (dock != null) {
int result = ActivityManagerNative.getDefault()
.startActivity(null, dock,
dock.resolveTypeIfNeeded(mContext.getContentResolver()),
null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
return false;
}
}
int result = ActivityManagerNative.getDefault()
.startActivity(null, mHomeIntent,
mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
return false;
}
} catch (RemoteException ex) {
// bummer, the activity manager, which is in this process, is dead
}
}
return true;
}
public void setCurrentOrientationLw(int newOrientation) {
synchronized (mLock) {
if (newOrientation != mCurrentAppOrientation) {
mCurrentAppOrientation = newOrientation;
updateOrientationListenerLp();
}
}
}
public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
return false;
}
switch (effectId) {
case HapticFeedbackConstants.LONG_PRESS:
mVibrator.vibrate(mLongPressVibePattern, -1);
return true;
case HapticFeedbackConstants.VIRTUAL_KEY:
mVibrator.vibrate(mVirtualKeyVibePattern, -1);
return true;
case HapticFeedbackConstants.SAFE_MODE_DISABLED:
mVibrator.vibrate(mSafeModeDisabledVibePattern, -1);
return true;
case HapticFeedbackConstants.SAFE_MODE_ENABLED:
mVibrator.vibrate(mSafeModeEnabledVibePattern, -1);
return true;
}
return false;
}
public void keyFeedbackFromInput(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& (event.getFlags()&KeyEvent.FLAG_VIRTUAL_HARD_KEY) != 0) {
performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
}
}
public void screenOnStoppedLw() {
if (!mKeyguardMediator.isShowingAndNotHidden() && mPowerManager.isScreenOn()) {
long curTime = SystemClock.uptimeMillis();
mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT);
}
}
public boolean allowKeyRepeat() {
// disable key repeat when screen is off
return mScreenOn;
}
}
| false | true | public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
// If screen is off then we treat the case where the keyguard is open but hidden
// the same as if it were open and in front.
// This will prevent any keys other than the power button from waking the screen
// when the keyguard is hidden by another activity.
final boolean keyguardActive = (screenIsOn ?
mKeyguardMediator.isShowingAndNotHidden() :
mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome, sleeps;
if (code == KeyEvent.KEYCODE_ENDCALL) {
gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
} else {
gohome = false;
sleeps = true;
}
if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
| public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
// If screen is off then we treat the case where the keyguard is open but hidden
// the same as if it were open and in front.
// This will prevent any keys other than the power button from waking the screen
// when the keyguard is hidden by another activity.
final boolean keyguardActive = (screenIsOn ?
mKeyguardMediator.isShowingAndNotHidden() :
mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
// when keyguard is showing and screen off, we need
// to handle the volume key for calls and music here
if (isInCall()) {
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
} else if (isMusicActive()) {
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome, sleeps;
if (code == KeyEvent.KEYCODE_ENDCALL) {
gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
} else {
gohome = false;
sleeps = true;
}
if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
|
diff --git a/src/org/GreenTeaScript/GreenTeaArray.java b/src/org/GreenTeaScript/GreenTeaArray.java
index a89e4d5..ef23419 100644
--- a/src/org/GreenTeaScript/GreenTeaArray.java
+++ b/src/org/GreenTeaScript/GreenTeaArray.java
@@ -1,60 +1,58 @@
// ***************************************************************************
// Copyright (c) 2013, JST/CREST DEOS project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// **************************************************************************
//ifdef JAVA
package org.GreenTeaScript;
import java.util.ArrayList;
import java.util.Arrays;
//endif VAJA
public class GreenTeaArray extends GreenTeaTopObject {
public ArrayList<Object> ArrayBody ;
public GreenTeaArray/*constructor*/(GtType GreenType) {
super(GreenType);
this.ArrayBody = new ArrayList<Object>();
}
public GreenTeaArray SubArray(int bindex, int eindex) {
/*local*/GreenTeaArray ArrayObject = new GreenTeaArray(this.GreenType);
for(/*local*/int i = bindex; i < eindex; i++) {
/*local*/Object Value = this.ArrayBody.get(i);
this.ArrayBody.add(Value);
}
return ArrayObject;
}
@Override public String toString() {
/*local*/String s = "[";
for(/*local*/int i = 0; i < this.ArrayBody.size(); i++) {
/*local*/Object Value = this.ArrayBody.get(i);
if(i > 0) {
- s += ", " + Value;
- }
- else {
- s += Value;
+ s += ", ";
}
+ s += LibGreenTea.Stringfy(Value);
}
return s + "]";
}
}
| false | true | @Override public String toString() {
/*local*/String s = "[";
for(/*local*/int i = 0; i < this.ArrayBody.size(); i++) {
/*local*/Object Value = this.ArrayBody.get(i);
if(i > 0) {
s += ", " + Value;
}
else {
s += Value;
}
}
return s + "]";
}
| @Override public String toString() {
/*local*/String s = "[";
for(/*local*/int i = 0; i < this.ArrayBody.size(); i++) {
/*local*/Object Value = this.ArrayBody.get(i);
if(i > 0) {
s += ", ";
}
s += LibGreenTea.Stringfy(Value);
}
return s + "]";
}
|
diff --git a/src/main/java/net/visualillusionsent/dconomy/addon/bank/dBankLiteBase.java b/src/main/java/net/visualillusionsent/dconomy/addon/bank/dBankLiteBase.java
index 3619c36..0f140fd 100755
--- a/src/main/java/net/visualillusionsent/dconomy/addon/bank/dBankLiteBase.java
+++ b/src/main/java/net/visualillusionsent/dconomy/addon/bank/dBankLiteBase.java
@@ -1,153 +1,153 @@
/*
* This file is part of dBankLite.
*
* Copyright © 2013 Visual Illusions Entertainment
*
* dBankLite 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.
*
* dBankLite 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 dBankLite.
* If not, see http://www.gnu.org/licenses/gpl.html.
*/
package net.visualillusionsent.dconomy.addon.bank;
import net.visualillusionsent.dconomy.MessageTranslator;
import net.visualillusionsent.dconomy.dCoBase;
import net.visualillusionsent.dconomy.io.logging.dCoLevel;
import net.visualillusionsent.utils.PropertiesFile;
import net.visualillusionsent.utils.UtilityException;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class dBankLiteBase {
private final float dCoVersion = 3.0F;
private final Logger logger;
private final Timer timer;
private static dBankLiteBase $;
public dBankLiteBase(dBankLite dbanklite) {
$ = this;
this.logger = dbanklite.getPluginLogger();
if (dCoBase.getVersion() > dCoVersion) {
- warning("dBankLite appears to be a newer version. Incompatibility could result.");
+ warning("dConomy appears to be a newer version. Incompatibility could result.");
}
testdBankLiteProps();
dbanklite.check();
installBankMessages();
if (getInterestInterval() > 0) { // interest enabled?
timer = new Timer();
timer.scheduleAtFixedRate(new InterestPayer(this), getInitialStart(), getInterestInterval());
} else {
timer = null;
}
}
private final void testdBankLiteProps() {
PropertiesFile dCoProps = dCoBase.getProperties().getPropertiesFile();
if (!dCoProps.containsKey("interest.rate")) {
dCoProps.setFloat("interest.rate", 2.0F, "dBankLite: Interest Rate (in percentage) (Default: 2%)");
}
if (!dCoProps.containsKey("interest.pay.interval")) {
dCoProps.setInt("interest.pay.interval", 360, "dBankLite: Interest Pay Interval (in minutes) (Default: 360 [6 Hours]) Set to 0 or less to disable");
}
if (!dCoProps.containsKey("interest.max.payout")) {
dCoProps.setInt("interest.max.payout", 10000, "dBankLite: Max Interest Payout (Default: 10000)");
}
if (!dCoProps.containsKey("sql.bank.table")) {
dCoProps.setString("sql.bank.table", "dBankLite", "dBankLite: SQL Bank table");
}
}
public final static void info(String msg) {
$.logger.info(msg);
}
public final static void info(String msg, Throwable thrown) {
$.logger.log(Level.INFO, msg, thrown);
}
public final static void warning(String msg) {
$.logger.warning(msg);
}
public final static void warning(String msg, Throwable thrown) {
$.logger.log(Level.WARNING, msg, thrown);
}
public final static void severe(String msg) {
$.logger.severe(msg);
}
public final static void severe(String msg, Throwable thrown) {
$.logger.log(Level.SEVERE, msg, thrown);
}
public final static void stacktrace(Throwable thrown) {
if (dCoBase.getProperties().getBooleanValue("debug.enabled")) {
$.logger.log(dCoLevel.STACKTRACE, "Stacktrace: ", thrown);
}
}
public final static void debug(String msg) {
if (dCoBase.getProperties().getBooleanValue("debug.enabled")) {
$.logger.log(dCoLevel.GENERAL, msg);
}
}
public final static void cleanUp() {
if ($.timer != null) {
$.timer.cancel();
$.timer.purge();
}
dCoBase.getProperties().getPropertiesFile().save();
}
private final long getInitialStart() {
if (dCoBase.getProperties().getPropertiesFile().containsKey("bank.timer.reset")) {
long reset = dCoBase.getProperties().getPropertiesFile().getLong("bank.timer.reset") - System.currentTimeMillis();
if (reset < 0) {
return 0;
} else {
dCoBase.getProperties().getPropertiesFile().setLong("bank.timer.reset", System.currentTimeMillis() + reset);
return reset;
}
} else {
setResetTime();
return getInterestInterval();
}
}
private final long getInterestInterval() {
return dCoBase.getProperties().getPropertiesFile().getLong("interest.pay.interval") * 60000;
}
final void setResetTime() {
dCoBase.getProperties().getPropertiesFile().setLong("bank.timer.reset", System.currentTimeMillis() + getInterestInterval());
}
private final void installBankMessages() {
try {
PropertiesFile lang = new PropertiesFile("config/dConomy3/lang/en_US.lang");
if (!lang.containsKey("bank.deposit")) {
lang.setString("bank.deposit", "$cAYou have deposited $cE{0, number, 0.00} $m$cA into your $c3Bank Account$cA.", ";dBankLite Message");
}
if (!lang.containsKey("bank.withdraw")) {
lang.setString("bank.withdraw", "$cAYou have withdrawn $cE{0, number, 0.00} $m$cA from your $c3Bank Account$cA.", ";dBankLite Message");
}
lang.save();
MessageTranslator.reloadMessages();
} catch (UtilityException uex) {
warning("Failed to install dBankLite messages into dConomy English file (en_US.lang)");
}
}
}
| true | true | public dBankLiteBase(dBankLite dbanklite) {
$ = this;
this.logger = dbanklite.getPluginLogger();
if (dCoBase.getVersion() > dCoVersion) {
warning("dBankLite appears to be a newer version. Incompatibility could result.");
}
testdBankLiteProps();
dbanklite.check();
installBankMessages();
if (getInterestInterval() > 0) { // interest enabled?
timer = new Timer();
timer.scheduleAtFixedRate(new InterestPayer(this), getInitialStart(), getInterestInterval());
} else {
timer = null;
}
}
| public dBankLiteBase(dBankLite dbanklite) {
$ = this;
this.logger = dbanklite.getPluginLogger();
if (dCoBase.getVersion() > dCoVersion) {
warning("dConomy appears to be a newer version. Incompatibility could result.");
}
testdBankLiteProps();
dbanklite.check();
installBankMessages();
if (getInterestInterval() > 0) { // interest enabled?
timer = new Timer();
timer.scheduleAtFixedRate(new InterestPayer(this), getInitialStart(), getInterestInterval());
} else {
timer = null;
}
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/evaluator/fa/EdgeTransition.java b/src/de/uni_koblenz/jgralab/greql2/evaluator/fa/EdgeTransition.java
index 893541fb0..d6e801cfd 100644
--- a/src/de/uni_koblenz/jgralab/greql2/evaluator/fa/EdgeTransition.java
+++ b/src/de/uni_koblenz/jgralab/greql2/evaluator/fa/EdgeTransition.java
@@ -1,162 +1,162 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2007 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.evaluator.fa;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VertexEvaluator;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueInvalidTypeException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueTypeCollection;
import de.uni_koblenz.jgralab.BooleanGraphMarker;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Vertex;
/**
* This transition accepts only one edge. Because this edge may be a variable
* or even the result of an expression containing a variable, a reference to the VertexEvaluator
* which evaluates this variable/expression is stored in this transition and the result of
* this evaluator is acceptes.
*
* This transition accepts the greql2 syntax: --{edge}->
*
* @author Daniel Bildhauer <[email protected]>
* Summer 2006, Diploma Thesis
*
*/
public class EdgeTransition extends SimpleTransition {
/**
* In GReQL 2 it is possible to specify an explicit edge. Cause this edge
* may be a variable or the result of an expression containing a variable,
* the VertexEvalutor which evaluates this edge expression is stored here so
* the result can be used as allowed edge
*/
private VertexEvaluator allowedEdgeEvaluator;
/**
* returns a string which describes the edge
*/
public String edgeString() {
String desc = "EdgeTransition";
//String desc = "EdgeTransition ( Dir:" + validDirection.toString() + " "
//+ edgeTypeRestriction.toString() + " Edge: " + allowedEdgeEvaluator.toString() + " )";
return desc;
}
/* (non-Javadoc)
* @see greql2.evaluator.fa.Transition#equalSymbol(greql2.evaluator.fa.EdgeTransition)
*/
public boolean equalSymbol(Transition t) {
if (!(t instanceof EdgeTransition))
return false;
EdgeTransition et = (EdgeTransition) t;
if (!typeCollection.equals(et.typeCollection))
return false;
if (validEdgeRole != et.validEdgeRole)
return false;
if (allowedEdgeEvaluator != et.allowedEdgeEvaluator)
return false;
if (validDirection != et.validDirection)
return false;
return true;
}
/**
* Copy-constructor, creates a copy of the given transition
*/
protected EdgeTransition(EdgeTransition t, boolean addToStates) {
super(t, addToStates);
allowedEdgeEvaluator = t.allowedEdgeEvaluator;
}
/**
* returns a copy of this transition
*/
public Transition copy(boolean addToStates) {
return new EdgeTransition(this, addToStates);
}
/**
* Creates a new transition from start state to end state. The Transition
* accepts all edges that have the right direction, role, startVertexType,
* endVertexType, edgeType and even it's possible to define a specific edge.
* This constructor creates a transition to accept a EdgePathDescription
*
* @param start
* The state where this transition starts
* @param end
* The state where this transition ends
* @param dir
* The direction of the accepted edges, may be EdeDirection.IN,
* EdgeDirection.OUT or EdgeDirection.ANY
* @param typeCollection
* The types which restrict the possible edges
* @param role
* The accepted edge role, or null if any role is accepted
* @param edgeEval
* If this is set, only the resulting edge of this evaluator will
* be accepted
*/
public EdgeTransition(State start, State end, AllowedEdgeDirection dir,
JValueTypeCollection typeCollection, String role, VertexEvaluator edgeEval) {
super(start, end, dir, typeCollection, role);
allowedEdgeEvaluator = edgeEval;
}
/* (non-Javadoc)
* @see greql2.evaluator.fa.Transition#accepts(jgralab.Vertex, jgralab.Edge, greql2.evaluator.SubgraphTempAttribute)
*/
public boolean accepts(Vertex v, Edge e, BooleanGraphMarker subgraph)
throws EvaluateException {
if ( !super.accepts(v,e,subgraph) ) {
return false;
}
//System.out.println("Checking edge path for Edge: " + e.toString());
// checks if only one edge is allowed an if e is this allowed edge
if (allowedEdgeEvaluator != null) {
try {
Edge allowedEdge = allowedEdgeEvaluator.getResult(
- subgraph).toEdge();
+ subgraph).toEdge().getNormalEdge();
//System.out.println("Allowed Edge is: " + allowedEdge.toString());
- if (e != allowedEdge)
+ if (e.getNormalEdge() != allowedEdge)
return false;
} catch (JValueInvalidTypeException ex) {
throw new EvaluateException(
"EdgeExpression in EdgePathDescription doesn't evaluate to edge",
ex);
}
}
return true;
}
}
| false | true | public boolean accepts(Vertex v, Edge e, BooleanGraphMarker subgraph)
throws EvaluateException {
if ( !super.accepts(v,e,subgraph) ) {
return false;
}
//System.out.println("Checking edge path for Edge: " + e.toString());
// checks if only one edge is allowed an if e is this allowed edge
if (allowedEdgeEvaluator != null) {
try {
Edge allowedEdge = allowedEdgeEvaluator.getResult(
subgraph).toEdge();
//System.out.println("Allowed Edge is: " + allowedEdge.toString());
if (e != allowedEdge)
return false;
} catch (JValueInvalidTypeException ex) {
throw new EvaluateException(
"EdgeExpression in EdgePathDescription doesn't evaluate to edge",
ex);
}
}
return true;
}
| public boolean accepts(Vertex v, Edge e, BooleanGraphMarker subgraph)
throws EvaluateException {
if ( !super.accepts(v,e,subgraph) ) {
return false;
}
//System.out.println("Checking edge path for Edge: " + e.toString());
// checks if only one edge is allowed an if e is this allowed edge
if (allowedEdgeEvaluator != null) {
try {
Edge allowedEdge = allowedEdgeEvaluator.getResult(
subgraph).toEdge().getNormalEdge();
//System.out.println("Allowed Edge is: " + allowedEdge.toString());
if (e.getNormalEdge() != allowedEdge)
return false;
} catch (JValueInvalidTypeException ex) {
throw new EvaluateException(
"EdgeExpression in EdgePathDescription doesn't evaluate to edge",
ex);
}
}
return true;
}
|
diff --git a/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/WonderlandHUDComponentManager.java b/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/WonderlandHUDComponentManager.java
index 19e38019d..6d3f4bc8f 100644
--- a/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/WonderlandHUDComponentManager.java
+++ b/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/WonderlandHUDComponentManager.java
@@ -1,829 +1,829 @@
/*
* 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.hud.client;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.state.BlendState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.RenderState;
import com.jme.system.DisplaySystem;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import org.jdesktop.mtgame.RenderUpdater;
import org.jdesktop.mtgame.WorldManager;
import org.jdesktop.wonderland.client.cell.Cell;
import org.jdesktop.wonderland.client.hud.HUD;
import org.jdesktop.wonderland.client.hud.HUDComponent;
import org.jdesktop.wonderland.client.hud.HUDComponentManager;
import org.jdesktop.wonderland.client.hud.HUDEvent;
import org.jdesktop.wonderland.client.hud.HUDLayoutManager;
import org.jdesktop.wonderland.client.hud.HUDObject.DisplayMode;
import org.jdesktop.wonderland.client.input.Event;
import org.jdesktop.wonderland.client.jme.ClientContextJME;
import org.jdesktop.wonderland.client.jme.input.MouseEnterExitEvent3D;
import org.jdesktop.wonderland.client.jme.input.test.EnterExitEvent3DLogger;
import org.jdesktop.wonderland.client.jme.utils.graphics.TexturedQuad;
import org.jdesktop.wonderland.modules.appbase.client.Window2D;
import org.jdesktop.wonderland.modules.appbase.client.Window2D.Type;
import org.jdesktop.wonderland.modules.appbase.client.swing.WindowSwing;
import org.jdesktop.wonderland.modules.appbase.client.view.GeometryNode;
import org.jdesktop.wonderland.modules.appbase.client.view.View2D;
/**
* A WonderlandHUDComponentManager manages a set of HUDComponents.
*
* It lays out HUDComponents within a HUD with a HUDLayoutManager layout manager.
* It also decorates HUDComponents with a frame border that allows the user
* to move, resize, minimize and maximize and close a HUDComponent.
*
* @author nsimpson
*/
public class WonderlandHUDComponentManager implements HUDComponentManager,
ActionListener, MouseMotionListener {
private static final Logger logger = Logger.getLogger(WonderlandHUDComponentManager.class.getName());
protected HUD hud;
// a mapping between HUD components and their states
protected Map<HUDComponent, HUDComponentState> hudStateMap;
// a mapping between views and HUD components
protected Map<HUDView2D, HUDComponent> hudViewMap;
// the layout manager for the HUD
protected HUDLayoutManager layout;
// displays HUD components on the glass
protected HUDView2DDisplayer hudDisplayer;
//
protected HUDApp2D hudApp;
protected Vector2f hudPixelScale = new Vector2f(0.75f, 0.75f);
protected Vector2f worldPixelScale = new Vector2f(0.013f, 0.013f);
protected boolean dragging = false;
protected int dragX = 0;
protected int dragY = 0;
protected static final float DEFAULT_FOCUSED_TRANSPARENCY = 0.0f;
protected static final float DEFAULT_UNFOCUSED_TRANSPARENCY = 0.2f;
protected static final long DEFAULT_FADE_IN_TIME = 250;
protected static final long DEFAULT_FADE_OUT_TIME = 1500;
protected static final String DEFAULT_HUD_ICON = "/org/jdesktop/wonderland/modules/hud/client/resources/GenericWindow32x32.png";
// TODO: set these from user properties
protected float focusedTransparency = DEFAULT_FOCUSED_TRANSPARENCY;
protected float unfocusedTransparency = DEFAULT_UNFOCUSED_TRANSPARENCY;
protected long fadeInTime = DEFAULT_FADE_IN_TIME;
protected long fadeOutTime = DEFAULT_FADE_OUT_TIME;
public WonderlandHUDComponentManager(HUD hud) {
this.hud = hud;
hudStateMap = Collections.synchronizedMap(new HashMap());
hudViewMap = Collections.synchronizedMap(new HashMap());
}
public Window2D createWindow(HUDComponent component) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("creating window for HUD component: " + component);
}
Window2D window = null;
//if (hudApp == null) {
hudApp = new HUDApp2D("HUD", new ControlArbHUD(), worldPixelScale);
//}
try {
// TODO: pixel scale doesn't match
window = hudApp.createWindow(component.getWidth(), component.getHeight(), Type.PRIMARY,
false, hudPixelScale, "HUD component");
JComponent comp = ((HUDComponent2D) component).getComponent();
((WindowSwing) window).setComponent(comp);
} catch (InstantiationException e) {
logger.warning("failed to create window for HUD component: " + e);
}
return window;
}
/**
* {@inheritDoc}
*/
public void addComponent(final HUDComponent component) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("adding HUD component to component manager: " + component);
}
HUDComponentState state = new HUDComponentState(component);
HUDComponent2D component2D = (HUDComponent2D) component;
Window2D window;
if (component2D.getWindow() != null) {
window = component2D.getWindow();
} else {
window = createWindow(component);
component2D.setWindow(window);
}
window.addEventListener(new EnterExitEvent3DLogger() {
@Override
public boolean propagatesToParent(Event event) {
return false;
}
@Override
public void commitEvent(Event event) {
MouseEnterExitEvent3D mouseEvent = (MouseEnterExitEvent3D) event;
switch (mouseEvent.getID()) {
case MouseEvent.MOUSE_ENTERED:
if (logger.isLoggable(Level.FINEST)) {
logger.finest("mouse entered component: " + component);
}
setFocused(component, true);
break;
case MouseEvent.MOUSE_EXITED:
if (logger.isLoggable(Level.FINEST)) {
logger.finest("mouse exited component: " + component);
}
setFocused(component, false);
break;
default:
break;
}
}
});
state.setWindow(window);
hudStateMap.put(component, state);
}
/**
* {@inheritDoc}
*/
public void removeComponent(HUDComponent component) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("removing HUD component from component manager: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
// remove HUD view
Window2D window = state.getWindow();
HUDView2D view2D = state.getView();
if ((window != null) && (view2D != null)) {
hudViewMap.remove(view2D);
window.removeView(view2D);
view2D.cleanup();
view2D = null;
}
// remove in-world view
HUDView3D view3D = state.getWorldView();
if (view3D != null) {
view3D.cleanup();
view3D = null;
}
hudStateMap.remove(component);
state = null;
}
}
/**
* {@inheritDoc}
*/
public Iterator<HUDComponent> getComponents() {
return hudStateMap.keySet().iterator();
}
public void actionPerformed(ActionEvent e) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("action performed: " + e);
}
if (e.getActionCommand().equals("close")) {
logger.info("close action performed: " + e);
close(hudViewMap.get((HUDView2D) e.getSource()));
} else if (e.getActionCommand().equals("minimize")) {
logger.info("minimize action performed: " + e);
minimizeComponent(hudViewMap.get((HUDView2D) e.getSource()));
}
}
public void mouseMoved(MouseEvent e) {
dragging = false;
}
public void mouseDragged(MouseEvent e) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("mouse dragged to: " + e.getPoint());
}
HUDView2D view = (HUDView2D) e.getSource();
if (view instanceof HUDView2D) {
HUDComponent hudComponent = hudViewMap.get(view);
if (hudComponent != null) {
if (!dragging) {
dragX = e.getX();
dragY = e.getY();
dragging = true;
}
// calculate new location of HUD component
Point location = hudComponent.getLocation();
float xDelta = hudPixelScale.x * (float) (e.getX() - dragX);
float yDelta = hudPixelScale.y * (float) (e.getY() - dragY);
location.setLocation(location.getX() + xDelta, location.getY() - yDelta);
// move the HUD component
hudComponent.setLocation(location);
dragX = e.getX();
dragY = e.getY();
}
}
}
protected void componentVisible(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("showing HUD component on HUD: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
HUDView2D view = state.getView();
if (view == null) {
if (hudDisplayer == null) {
hudDisplayer = new HUDView2DDisplayer();
}
view = hudDisplayer.createView(state.getWindow());
view.addActionListener(this);
view.addMouseMotionListener(this);
hudViewMap.put(view, component);
state.setView(view);
if (layout != null) {
layout.addView(component, view);
}
}
// move the component to the screen
view.setOrtho(true, false);
view.setPixelScaleOrtho(hudPixelScale, false);
// position the component on the screen.
- if (view.getType() == View2D.Type.PRIMARY) {
+ if ((view.getType() == View2D.Type.PRIMARY) || (view.getType() == View2D.Type.UNKNOWN)) {
Vector2f location = (layout != null) ? layout.getLocation(component) : new Vector2f(component.getX(), component.getY());
component.setLocation((int) location.x, (int) location.y, false);
view.setLocationOrtho(new Vector2f(location.x + view.getDisplayerLocalWidth() / 2, location.y + view.getDisplayerLocalHeight() / 2), false);
}
if (component.getPreferredTransparency() != 1.0f) {
// component has a preferred transparency, so set it to that
// transparency initially
component.setTransparency(component.getPreferredTransparency());
} else {
// fade the component in from invisible to the unfocused
// transparency
component.changeTransparency(1.0f, unfocusedTransparency);
}
// set the initial control state
view.setControlled(component.hasControl());
// set the text to display on the frame header (if displayed)
view.setTitle(component.getName());
// display the component
if (((HUDComponent2D) component).isHUDManagedWindow()) {
view.setDecorated(component.getDecoratable());
view.setVisibleApp(true);
}
view.setVisibleUser(true);
}
public void setFocused(HUDComponent component, boolean focused) {
if (component != null) {
component.changeTransparency(component.getTransparency(),
focused ? focusedTransparency : ((component.getPreferredTransparency() != 1.0f) ? component.getPreferredTransparency() : unfocusedTransparency),
focused ? fadeInTime : fadeOutTime);
}
}
public void setTransparency(HUDView2D view, final float transparency) {
if (view != null) {
GeometryNode node = view.getGeometryNode();
if (!(node.getChild(0) instanceof TexturedQuad)) {
logger.warning("can't find quad for view, unable to set transparency");
return;
}
final TexturedQuad quad = (TexturedQuad) node.getChild(0);
RenderUpdater updater = new RenderUpdater() {
public void update(Object arg0) {
WorldManager wm = (WorldManager) arg0;
BlendState as = (BlendState) wm.getRenderManager().createRendererState(RenderState.StateType.Blend);
// activate blending
as.setBlendEnabled(true);
// set the source function
as.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
// set the destination function
as.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
// disable test
as.setTestEnabled(false);
// activate the blend state
as.setEnabled(true);
// assign the blender state to the node
quad.setRenderState(as);
quad.updateRenderState();
MaterialState ms = (MaterialState) quad.getRenderState(RenderState.StateType.Material);
if (ms == null) {
ms = DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
quad.setRenderState(ms);
}
if (ms != null) {
ColorRGBA diffuse = ms.getDiffuse();
diffuse.a = 1.0f - transparency;
ms.setDiffuse(diffuse);
} else {
logger.warning("quad has no material state, unable to set transparency");
return;
}
ColorRGBA color = quad.getDefaultColor();
color.a = transparency;
quad.setDefaultColor(color);
wm.addToUpdateList(quad);
}
};
WorldManager wm = ClientContextJME.getWorldManager();
wm.addRenderUpdater(updater, wm);
}
}
public void setTransparency(HUDComponent2D component, final float transparency) {
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
setTransparency(state.getView(), transparency);
}
}
protected void componentInvisible(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("hiding HUD component on HUD: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if ((state != null) && (state.isVisible())) {
HUDView2D view = state.getView();
if (view != null) {
logger.fine("hiding HUD view");
view.setDecorated(false);
view.setVisibleApp(false, false);
view.setVisibleUser(false);
} else {
logger.warning("attempt to set HUD invisible with no HUD view");
}
}
}
protected void componentWorldVisible(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("showing HUD component in world: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if ((state != null) && (!state.isWorldVisible())) {
Cell cell = component.getCell();
if (cell != null) {
// can only create world views of HUD components that are
// associated with a cell
HUDView3D worldView = state.getWorldView();
if (worldView == null) {
logger.fine("creating new world displayer");
HUDView3DDisplayer worldDisplayer = new HUDView3DDisplayer(cell);
logger.fine("creating new in-world view");
worldView = worldDisplayer.createView(state.getWindow());
worldView.setPixelScale(worldPixelScale);
state.setWorldView(worldView);
}
logger.fine("displaying in-world view");
worldView.setOrtho(false, false);
worldView.setPixelScale(worldPixelScale);
worldView.setVisibleApp(true, false);
worldView.setVisibleUser(true, false);
componentMovedWorld(component);
worldView.update();
}
}
}
protected void componentWorldInvisible(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("hiding HUD component in world: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if ((state != null) && (state.isWorldVisible())) {
HUDView3D worldView = state.getWorldView();
if (worldView != null) {
logger.fine("hiding in-world view");
worldView.setVisibleApp(false, false);
worldView.setVisibleUser(false, false);
worldView.update();
} else {
logger.warning("attempt to set world invisible with no world view");
}
}
}
protected void componentMoved(HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("moving component to: " + component.getX() + ", " + component.getY());
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
HUDView2D view = state.getView();
if (view != null) {
// position the component on the screen
Vector2f location = (layout != null) ? layout.getLocation(component) : new Vector2f(component.getX(), component.getY());
view.setLocationOrtho(new Vector2f(location.x + view.getDisplayerLocalWidth() / 2, location.y + view.getDisplayerLocalHeight() / 2), true);
}
}
protected void componentMovedWorld(HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("moving HUD component in world: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
HUDView3D view = state.getWorldView();
if (view != null) {
Vector3f worldOffset = component.getWorldLocation();
// position HUD in x, y
view.setOffset(new Vector2f(worldOffset.x, worldOffset.y));
}
}
protected void componentResized(final HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("resizing HUD component: " + component);
}
final HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
final HUDView2D view = state.getView();
if (view != null) {
view.setSizeApp(component.getSize());
}
}
protected void componentViewChanged(HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.fine("changing HUD component view: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
HUDView2D view = state.getView();
if (component.getDisplayMode().equals(DisplayMode.HUD)) {
// moving to HUD
view.setLocationOrtho(new Vector2f(component.getX(), component.getY()), false);
view.setOrtho(true);
} else {
// moving to world
view.applyDeltaTranslationUser(component.getWorldLocation());
view.setOrtho(false);
}
}
protected void componentMinimized(final HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("minimizing HUD component: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
component.setVisible(false);
}
}
protected void componentMaximized(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("maximizing HUD component: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
component.setVisible(true);
}
}
protected void componentClosed(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("closing HUD component: " + component);
}
}
protected void componentTransparencyChanged(HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("changing transparency of: " + component);
}
float transparency = component.getTransparency();
setTransparency(component, transparency);
}
protected void componentNameChanged(HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("changing name of: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
HUDView2D view = state.getView();
if (view != null) {
view.setTitle(component.getName());
}
}
}
protected void componentControlChanged(HUDComponent2D component) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("changing control of: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
HUDView2D view = state.getView();
if (view != null) {
view.setControlled(component.hasControl());
}
}
}
private void handleHUDComponentChanged(HUDEvent event) {
HUDComponent2D comp = (HUDComponent2D) event.getObject();
switch (event.getEventType()) {
case ADDED:
// event generated by HUD
addComponent(comp);
break;
case REMOVED:
// event generated by HUD
removeComponent(comp);
break;
case APPEARED:
componentVisible(comp);
break;
case APPEARED_WORLD:
componentWorldVisible(comp);
break;
case DISAPPEARED:
componentInvisible(comp);
break;
case DISAPPEARED_WORLD:
componentWorldInvisible(comp);
break;
case CHANGED_MODE:
componentViewChanged(comp);
break;
case MOVED:
componentMoved(comp);
break;
case MOVED_WORLD:
componentMovedWorld(comp);
break;
case RESIZED:
componentResized(comp);
break;
case MINIMIZED:
componentMinimized(comp);
break;
case MAXIMIZED:
componentMaximized(comp);
break;
case ENABLED:
break;
case DISABLED:
break;
case CHANGED_TRANSPARENCY:
componentTransparencyChanged(comp);
break;
case CHANGED_NAME:
componentNameChanged(comp);
break;
case CHANGED_CONTROL:
componentControlChanged(comp);
break;
case CLOSED:
componentClosed(comp);
break;
default:
logger.info("TODO: handle HUD event type: " + event.getEventType());
break;
}
}
private void handleHUDChanged(HUDEvent event) {
switch (event.getEventType()) {
case RESIZED:
relayout();
break;
default:
break;
}
}
/**
* {@inheritDoc}
*/
public void HUDObjectChanged(HUDEvent event) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("HUD object changed: " + event);
}
if (event.getObject() instanceof HUDComponent2D) {
handleHUDComponentChanged(event);
} else if (event.getObject() instanceof HUD) {
handleHUDChanged(event);
}
}
/**
* {@inheritDoc}
*/
public void setLayoutManager(HUDLayoutManager layout) {
this.layout = layout;
}
/**
* {@inheritDoc}
*/
public HUDLayoutManager getLayoutManager() {
return layout;
}
/**
* {@inheritDoc}
*/
public void relayout() {
if (layout != null) {
layout.relayout();
}
}
/**
* {@inheritDoc}
*/
public void relayout(HUDComponent component) {
if (layout != null) {
layout.relayout(component);
}
}
/**
* {@inheritDoc}
*/
public void setVisible(HUDComponent component, boolean visible) {
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
component.setVisible(visible);
}
}
/**
* {@inheritDoc}
*/
public boolean isVisible(HUDComponent component) {
boolean visible = false;
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
visible = state.isVisible();
}
return visible;
}
/**
* {@inheritDoc}
*/
public void minimizeComponent(HUDComponent component) {
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
component.setMinimized();
}
}
/**
* {@inheritDoc}
*/
public void maximizeComponent(HUDComponent component) {
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
component.setMaximized();
}
}
/**
* {@inheritDoc}
*/
public void raiseComponent(HUDComponent component) {
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
int zorder = state.getZOrder();
state.setZOrder(zorder++);
// TODO: update component
}
}
/**
* {@inheritDoc}
*/
public void lowerComponent(HUDComponent component) {
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
int zorder = state.getZOrder();
state.setZOrder(zorder--);
// TODO: update component
}
}
/**
* {@inheritDoc}
*/
public int getComponentZOrder(HUDComponent component) {
int zorder = 0;
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state != null) {
zorder = state.getZOrder();
}
return zorder;
}
public void close(HUDComponent component) {
component.setVisible(false);
component.setClosed();
}
}
| true | true | protected void componentVisible(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("showing HUD component on HUD: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
HUDView2D view = state.getView();
if (view == null) {
if (hudDisplayer == null) {
hudDisplayer = new HUDView2DDisplayer();
}
view = hudDisplayer.createView(state.getWindow());
view.addActionListener(this);
view.addMouseMotionListener(this);
hudViewMap.put(view, component);
state.setView(view);
if (layout != null) {
layout.addView(component, view);
}
}
// move the component to the screen
view.setOrtho(true, false);
view.setPixelScaleOrtho(hudPixelScale, false);
// position the component on the screen.
if (view.getType() == View2D.Type.PRIMARY) {
Vector2f location = (layout != null) ? layout.getLocation(component) : new Vector2f(component.getX(), component.getY());
component.setLocation((int) location.x, (int) location.y, false);
view.setLocationOrtho(new Vector2f(location.x + view.getDisplayerLocalWidth() / 2, location.y + view.getDisplayerLocalHeight() / 2), false);
}
if (component.getPreferredTransparency() != 1.0f) {
// component has a preferred transparency, so set it to that
// transparency initially
component.setTransparency(component.getPreferredTransparency());
} else {
// fade the component in from invisible to the unfocused
// transparency
component.changeTransparency(1.0f, unfocusedTransparency);
}
// set the initial control state
view.setControlled(component.hasControl());
// set the text to display on the frame header (if displayed)
view.setTitle(component.getName());
// display the component
if (((HUDComponent2D) component).isHUDManagedWindow()) {
view.setDecorated(component.getDecoratable());
view.setVisibleApp(true);
}
view.setVisibleUser(true);
}
| protected void componentVisible(HUDComponent2D component) {
if (logger.isLoggable(Level.INFO)) {
logger.info("showing HUD component on HUD: " + component);
}
HUDComponentState state = (HUDComponentState) hudStateMap.get(component);
if (state == null) {
return;
}
HUDView2D view = state.getView();
if (view == null) {
if (hudDisplayer == null) {
hudDisplayer = new HUDView2DDisplayer();
}
view = hudDisplayer.createView(state.getWindow());
view.addActionListener(this);
view.addMouseMotionListener(this);
hudViewMap.put(view, component);
state.setView(view);
if (layout != null) {
layout.addView(component, view);
}
}
// move the component to the screen
view.setOrtho(true, false);
view.setPixelScaleOrtho(hudPixelScale, false);
// position the component on the screen.
if ((view.getType() == View2D.Type.PRIMARY) || (view.getType() == View2D.Type.UNKNOWN)) {
Vector2f location = (layout != null) ? layout.getLocation(component) : new Vector2f(component.getX(), component.getY());
component.setLocation((int) location.x, (int) location.y, false);
view.setLocationOrtho(new Vector2f(location.x + view.getDisplayerLocalWidth() / 2, location.y + view.getDisplayerLocalHeight() / 2), false);
}
if (component.getPreferredTransparency() != 1.0f) {
// component has a preferred transparency, so set it to that
// transparency initially
component.setTransparency(component.getPreferredTransparency());
} else {
// fade the component in from invisible to the unfocused
// transparency
component.changeTransparency(1.0f, unfocusedTransparency);
}
// set the initial control state
view.setControlled(component.hasControl());
// set the text to display on the frame header (if displayed)
view.setTitle(component.getName());
// display the component
if (((HUDComponent2D) component).isHUDManagedWindow()) {
view.setDecorated(component.getDecoratable());
view.setVisibleApp(true);
}
view.setVisibleUser(true);
}
|
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
index d84e515..5788a40 100644
--- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
+++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java
@@ -1,1330 +1,1330 @@
/**
* Copyright (C) 2009-2012 Enstratius, Inc.
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.openstack.nova.os.compute;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.compute.AbstractVMSupport;
import org.dasein.cloud.compute.Architecture;
import org.dasein.cloud.compute.ImageClass;
import org.dasein.cloud.compute.MachineImage;
import org.dasein.cloud.compute.Platform;
import org.dasein.cloud.compute.VMLaunchOptions;
import org.dasein.cloud.compute.VirtualMachine;
import org.dasein.cloud.compute.VirtualMachineProduct;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.identity.IdentityServices;
import org.dasein.cloud.identity.ShellKeySupport;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.network.FirewallSupport;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.IpAddress;
import org.dasein.cloud.network.IpAddressSupport;
import org.dasein.cloud.network.NetworkServices;
import org.dasein.cloud.network.RawAddress;
import org.dasein.cloud.network.VLAN;
import org.dasein.cloud.network.VLANSupport;
import org.dasein.cloud.openstack.nova.os.NovaException;
import org.dasein.cloud.openstack.nova.os.NovaMethod;
import org.dasein.cloud.openstack.nova.os.NovaOpenStack;
import org.dasein.cloud.openstack.nova.os.network.NovaNetworkServices;
import org.dasein.cloud.openstack.nova.os.network.Quantum;
import org.dasein.cloud.util.APITrace;
import org.dasein.cloud.util.Cache;
import org.dasein.cloud.util.CacheLevel;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.dasein.util.uom.time.Day;
import org.dasein.util.uom.time.TimePeriod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Implements services supporting interaction with cloud virtual machines.
* @author George Reese ([email protected])
* @version 2012.09 addressed issue with alternate security group lookup in some OpenStack environments (issue #1)
* @version 2013.02 implemented setting kernel/ramdisk image IDs (see issue #40 in dasein-cloud-core)
* @version 2013.02 updated with support for Dasein Cloud 2013.02 model
* @version 2013.02 added support for fetching shell keys (issue #4)
* @since unknown
*/
public class NovaServer extends AbstractVMSupport {
static private final Logger logger = NovaOpenStack.getLogger(NovaServer.class, "std");
static public final String SERVICE = "compute";
NovaServer(NovaOpenStack provider) {
super(provider);
}
private @Nonnull String getTenantId() throws CloudException, InternalException {
return ((NovaOpenStack)getProvider()).getAuthenticationContext().getTenantId();
}
@Override
public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.getConsoleOutput");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("os-getConsoleOutput", new HashMap<String,Object>());
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
String console = method.postServersForString("/servers", vmId, new JSONObject(json), true);
return (console == null ? "" : console);
}
finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getProduct");
try {
for( VirtualMachineProduct product : listProducts(Architecture.I64) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "server";
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getVirtualMachine");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", vmId, true);
if( ob == null ) {
return null;
}
Iterable<IpAddress> ipv4, ipv6;
Iterable<VLAN> networks;
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipv4 = support.listIpPool(IPVersion.IPV4, false);
ipv6 = support.listIpPool(IPVersion.IPV6, false);
}
else {
ipv4 = ipv6 = Collections.emptyList();
}
VLANSupport vs = services.getVlanSupport();
if( vs != null ) {
networks = vs.listVlans();
}
else {
networks = Collections.emptyList();
}
}
else {
ipv4 = ipv6 = Collections.emptyList();
networks = Collections.emptyList();
}
try {
if( ob.has("server") ) {
JSONObject server = ob.getJSONObject("server");
VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, networks);
if( vm != null ) {
return vm;
}
}
}
catch( JSONException e ) {
logger.error("getVirtualMachine(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers");
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.OPTIONAL);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
IdentityServices services = getProvider().getIdentityServices();
if( services == null ) {
return Requirement.NONE;
}
ShellKeySupport support = services.getShellKeySupport();
if( support == null ) {
return Requirement.NONE;
}
return Requirement.OPTIONAL;
}
@Override
public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
NetworkServices services = getProvider().getNetworkServices();
if( services == null ) {
return Requirement.NONE;
}
VLANSupport support = services.getVlanSupport();
if( support == null || !support.isSubscribed() ) {
return Requirement.NONE;
}
return Requirement.OPTIONAL;
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return true;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.isSubscribed");
try {
return (getProvider().testContext() != null);
}
finally {
APITrace.end();
}
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return true;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions options) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.launch");
try {
MachineImage targetImage = getProvider().getComputeServices().getImageSupport().getImage(options.getMachineImageId());
if( targetImage == null ) {
throw new CloudException("No such machine image: " + options.getMachineImageId());
}
HashMap<String,Object> wrapper = new HashMap<String,Object>();
HashMap<String,Object> json = new HashMap<String,Object>();
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
json.put("name", options.getHostName());
if( options.getUserData() != null ) {
try {
json.put("user_data", Base64.encodeBase64String(options.getUserData().getBytes("utf-8")));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
}
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
json.put("imageId", String.valueOf(options.getMachineImageId()));
json.put("flavorId", options.getStandardProductId());
}
else {
if( getProvider().getProviderName().equals("HP") ) {
json.put("imageRef", options.getMachineImageId());
}
else {
json.put("imageRef", ((NovaOpenStack)getProvider()).getComputeServices().getImageSupport().getImageRef(options.getMachineImageId()));
}
json.put("flavorRef", getFlavorRef(options.getStandardProductId()));
}
if( options.getVlanId() != null && ((NovaOpenStack)getProvider()).isRackspace() ) {
ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>();
HashMap<String,Object> vlan = new HashMap<String, Object>();
vlan.put("uuid", options.getVlanId());
vlans.add(vlan);
json.put("networks", vlans);
}
else {
if( options.getVlanId() != null && !((NovaOpenStack)getProvider()).isRackspace() ) {
try {
NovaNetworkServices services = ((NovaOpenStack)getProvider()).getNetworkServices();
if( services != null ) {
Quantum support = services.getVlanSupport();
if( support != null ) {
ArrayList<Map<String,Object>> vlans = new ArrayList<Map<String, Object>>();
HashMap<String,Object> vlan = new HashMap<String, Object>();
vlan.put("port", support.createPort(options.getVlanId(), options.getHostName()));
vlans.add(vlan);
json.put("networks", vlans);
}
}
}
catch( Throwable ignore ) {
// ignore this error
}
}
}
if( options.getBootstrapKey() != null ) {
json.put("key_name", options.getBootstrapKey());
}
if( options.getFirewallIds().length > 0 ) {
ArrayList<HashMap<String,Object>> firewalls = new ArrayList<HashMap<String,Object>>();
for( String id : options.getFirewallIds() ) {
NetworkServices services = getProvider().getNetworkServices();
Firewall firewall = null;
if( services != null ) {
FirewallSupport support = services.getFirewallSupport();
if( support != null ) {
firewall = support.getFirewall(id);
}
}
if( firewall != null ) {
HashMap<String,Object> fw = new HashMap<String, Object>();
fw.put("name", firewall.getName());
firewalls.add(fw);
}
}
json.put("security_groups", firewalls);
}
if( !targetImage.getPlatform().equals(Platform.UNKNOWN) ) {
options.withMetaData("org.dasein.platform", targetImage.getPlatform().name());
}
options.withMetaData("org.dasein.description", options.getDescription());
json.put("metadata", options.getMetaData());
wrapper.put("server", json);
JSONObject result = method.postServers("/servers", null, new JSONObject(wrapper), true);
if( result.has("server") ) {
try {
Collection<IpAddress> ips = Collections.emptyList();
Collection<VLAN> nets = Collections.emptyList();
JSONObject server = result.getJSONObject("server");
VirtualMachine vm = toVirtualMachine(server, ips, ips, nets);
if( vm != null ) {
return vm;
}
}
catch( JSONException e ) {
logger.error("launch(): Unable to understand launch response: " + e.getMessage());
if( logger.isTraceEnabled() ) {
e.printStackTrace();
}
throw new CloudException(e);
}
}
logger.error("launch(): No server was created by the launch attempt, and no error was returned");
throw new CloudException("No virtual machine was launched");
}
finally {
APITrace.end();
}
}
private @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId, @Nonnull JSONObject server) throws InternalException, CloudException {
try {
if( server.has("security_groups") ) {
NetworkServices services = getProvider().getNetworkServices();
Collection<Firewall> firewalls = null;
if( services != null ) {
FirewallSupport support = services.getFirewallSupport();
if( support != null ) {
firewalls = support.list();
}
}
if( firewalls == null ) {
firewalls = Collections.emptyList();
}
JSONArray groups = server.getJSONArray("security_groups");
ArrayList<String> results = new ArrayList<String>();
for( int i=0; i<groups.length(); i++ ) {
JSONObject group = groups.getJSONObject(i);
String id = group.has("id") ? group.getString("id") : null;
String name = group.has("name") ? group.getString("name") : null;
if( id != null || name != null ) {
for( Firewall fw : firewalls ) {
if( id != null ) {
if( id.equals(fw.getProviderFirewallId()) ) {
results.add(id);
}
}
else if( name.equals(fw.getName()) ) {
results.add(fw.getProviderFirewallId());
}
}
}
}
return results;
}
else {
ArrayList<String> results = new ArrayList<String>();
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", vmId + "/os-security-groups", true);
if( ob != null ) {
if( ob.has("security_groups") ) {
JSONArray groups = ob.getJSONArray("security_groups");
for( int i=0; i<groups.length(); i++ ) {
JSONObject group = groups.getJSONObject(i);
if( group.has("id") ) {
results.add(group.getString("id"));
}
}
}
}
return results;
}
}
catch( JSONException e ) {
throw new CloudException(e);
}
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFirewalls");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", vmId, true);
if( ob == null ) {
return Collections.emptyList();
}
try {
if( ob.has("server") ) {
JSONObject server = ob.getJSONObject("server");
return listFirewalls(vmId, server);
}
throw new CloudException("No such server: " + vmId);
}
catch( JSONException e ) {
logger.error("listFirewalls(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers");
}
}
finally {
APITrace.end();
}
}
static public class FlavorRef {
public String id;
public String[][] links;
VirtualMachineProduct product;
public String toString() { return (id + " -> " + product); }
}
private @Nonnull Iterable<FlavorRef> listFlavors() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFlavors");
try {
Cache<FlavorRef> cache = Cache.getInstance(getProvider(), "flavorRefs", FlavorRef.class, CacheLevel.REGION_ACCOUNT, new TimePeriod<Day>(1, TimePeriod.DAY));
Iterable<FlavorRef> refs = cache.get(getContext());
if( refs != null ) {
return refs;
}
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/flavors", null, true);
ArrayList<FlavorRef> flavors = new ArrayList<FlavorRef>();
try {
if( ob != null && ob.has("flavors") ) {
JSONArray list = ob.getJSONArray("flavors");
for( int i=0; i<list.length(); i++ ) {
JSONObject p = list.getJSONObject(i);
FlavorRef ref = new FlavorRef();
if( p.has("id") ) {
ref.id = p.getString("id");
}
else {
continue;
}
if( p.has("links") ) {
JSONArray links = p.getJSONArray("links");
ref.links = new String[links.length()][];
for( int j=0; j<links.length(); j++ ) {
JSONObject link = links.getJSONObject(j);
ref.links[j] = new String[2];
if( link.has("rel") ) {
ref.links[j][0] = link.getString("rel");
}
if( link.has("href") ) {
ref.links[j][1] = link.getString("href");
}
}
}
else {
ref.links = new String[0][];
}
ref.product = toProduct(p);
if( ref.product != null ) {
flavors.add(ref);
}
}
}
}
catch( JSONException e ) {
logger.error("listProducts(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors: " + e.getMessage());
}
cache.put(getContext(), flavors);
return flavors;
}
finally {
APITrace.end();
}
}
public @Nullable String getFlavorRef(@Nonnull String flavorId) throws InternalException, CloudException {
for( FlavorRef ref : listFlavors() ) {
if( ref.id.equals(flavorId) ) {
String def = null;
for( String[] link : ref.links ) {
if( link[0] != null && link[0].equals("self") && link[1] != null ) {
return link[1];
}
else if( def == null && link[1] != null ) {
def = link[1];
}
}
return def;
}
}
return null;
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
if( !architecture.equals(Architecture.I32) && !architecture.equals(Architecture.I64) ) {
return Collections.emptyList();
}
APITrace.begin(getProvider(), "VM.listProducts");
try {
ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>();
for( FlavorRef flavor : listFlavors() ) {
products.add(flavor.product);
}
return products;
}
finally {
APITrace.end();
}
}
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
ArrayList<Architecture> architectures = new ArrayList<Architecture>();
architectures.add(Architecture.I32);
architectures.add(Architecture.I64);
return architectures;
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachineStatus");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", null, true);
ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>();
try {
if( ob != null && ob.has("servers") ) {
JSONArray list = ob.getJSONArray("servers");
for( int i=0; i<list.length(); i++ ) {
JSONObject server = list.getJSONObject(i);
ResourceStatus vm = toStatus(server);
if( vm != null ) {
servers.add(vm);
}
}
}
}
catch( JSONException e ) {
logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace();
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString());
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachines");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/servers", null, true);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
Iterable<IpAddress> ipv4 = Collections.emptyList(), ipv6 = Collections.emptyList();
Iterable<VLAN> nets = Collections.emptyList();
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipv4 = support.listIpPool(IPVersion.IPV4, false);
ipv6 = support.listIpPool(IPVersion.IPV6, false);
}
VLANSupport vs = services.getVlanSupport();
if( vs != null ) {
nets = vs.listVlans();
}
}
try {
if( ob != null && ob.has("servers") ) {
JSONArray list = ob.getJSONArray("servers");
for( int i=0; i<list.length(); i++ ) {
JSONObject server = list.getJSONObject(i);
VirtualMachine vm = toVirtualMachine(server, ipv4, ipv6, nets);
if( vm != null ) {
servers.add(vm);
}
}
}
}
catch( JSONException e ) {
logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace();
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString());
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public void pause(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.pause");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsPauseUnpause(vm) ) {
throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("pause", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void resume(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.resume");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsSuspendResume(vm) ) {
throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("resume", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.start");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsStartStop(vm) ) {
throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("os-start", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.stop");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsStartStop(vm) ) {
throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("os-stop", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void suspend(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.suspend");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsSuspendResume(vm) ) {
throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("suspend", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void unpause(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.unpause");
try {
VirtualMachine vm = getVirtualMachine(vmId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + vmId);
}
if( !supportsPauseUnpause(vm) ) {
throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName());
}
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("unpause", null);
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String vmId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.reboot");
try {
HashMap<String,Object> json = new HashMap<String,Object>();
HashMap<String,Object> action = new HashMap<String,Object>();
action.put("type", "HARD");
json.put("reboot", action);
NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider()));
method.postServers("/servers", vmId, new JSONObject(json), true);
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return ((NovaOpenStack)getProvider()).getCloudProvider().supportsPauseUnpause(vm);
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return ((NovaOpenStack)getProvider()).getCloudProvider().supportsStartStop(vm);
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return ((NovaOpenStack)getProvider()).getCloudProvider().supportsSuspendResume(vm);
}
@Override
public void terminate(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.terminate");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;
do {
try {
method.deleteServers("/servers", vmId);
return;
}
catch( NovaException e ) {
if( e.getHttpCode() != HttpServletResponse.SC_CONFLICT ) {
throw e;
}
}
try { Thread.sleep(CalendarWrapper.MINUTE); }
catch( InterruptedException e ) { /* ignore */ }
} while( System.currentTimeMillis() < timeout );
}
finally {
APITrace.end();
}
}
private @Nullable VirtualMachineProduct toProduct(@Nullable JSONObject json) throws JSONException, InternalException, CloudException {
if( json == null ) {
return null;
}
VirtualMachineProduct product = new VirtualMachineProduct();
if( json.has("id") ) {
product.setProviderProductId(json.getString("id"));
}
if( json.has("name") ) {
product.setName(json.getString("name"));
}
if( json.has("description") ) {
product.setDescription(json.getString("description"));
}
if( json.has("ram") ) {
product.setRamSize(new Storage<Megabyte>(json.getInt("ram"), Storage.MEGABYTE));
}
if( json.has("disk") ) {
product.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("disk"), Storage.GIGABYTE));
}
product.setCpuCount(1);
if( product.getProviderProductId() == null ) {
return null;
}
if( product.getName() == null ) {
product.setName(product.getProviderProductId());
}
if( product.getDescription() == null ) {
product.setDescription(product.getName());
}
return product;
}
private @Nullable ResourceStatus toStatus(@Nullable JSONObject server) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
String serverId = null;
if( server.has("id") ) {
serverId = server.getString("id");
}
if( serverId == null ) {
return null;
}
VmState state = VmState.PENDING;
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
state = VmState.RUNNING;
}
else if( s.equals("build") ) {
state = VmState.PENDING;
}
else if( s.equals("deleted") ) {
state = VmState.TERMINATED;
}
else if( s.equals("suspended") ) {
state = VmState.SUSPENDED;
}
else if( s.equalsIgnoreCase("paused") ) {
state = VmState.PAUSED;
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
state = VmState.STOPPED;
}
else if( s.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( s.equalsIgnoreCase("pausing") ) {
state = VmState.PAUSING;
}
else if( s.equalsIgnoreCase("suspending") ) {
state = VmState.SUSPENDING;
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
state = VmState.REBOOTING;
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
state = VmState.PENDING;
}
}
return new ResourceStatus(serverId, state);
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
String description = null;
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(getTenantId());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(server.getString("id"));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") && !server.isNull("description") ) {
description = server.getString("description");
}
if( server.has("kernel_id") ) {
vm.setProviderKernelImageId(server.getString("kernel_id"));
}
if( server.has("ramdisk_id") ) {
vm.setProviderRamdiskImageId(server.getString("ramdisk_id"));
}
JSONObject md = (server.has("metadata") && !server.isNull("metadata")) ? server.getJSONObject("metadata") : null;
HashMap<String,String> map = new HashMap<String,String>();
boolean imaging = false;
if( md != null ) {
if( md.has("org.dasein.description") && vm.getDescription() == null ) {
description = md.getString("org.dasein.description");
}
else if( md.has("Server Label") ) {
description = md.getString("Server Label");
}
if( md.has("org.dasein.platform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( server.has("OS-EXT-STS:task_state") && !server.isNull("OS-EXT-STS:task_state") ) {
String t = server.getString("OS-EXT-STS:task_state");
map.put("OS-EXT-STS:task_state", t);
imaging = t.equalsIgnoreCase("image_snapshot");
}
if( description == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
else {
vm.setDescription(description);
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
if( server.has("image") ) {
JSONObject img = server.getJSONObject("image");
if( img.has("id") ) {
vm.setProviderMachineImageId(img.getString("id"));
}
}
if( server.has("flavor") ) {
JSONObject f = server.getJSONObject("flavor");
if( f.has("id") ) {
vm.setProductId(f.getString("id"));
}
}
else if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
- vm.setRootPassword("adminPass");
+ vm.setRootPassword(server.getString("adminPass"));
}
if( server.has("key_name") ) {
vm.setProviderShellKeyIds(server.getString("key_name"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.startsWith("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equalsIgnoreCase("paused") ) {
vm.setCurrentState(VmState.PAUSED);
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
vm.setCurrentState(VmState.STOPPED);
}
else if( s.equalsIgnoreCase("stopping") ) {
vm.setCurrentState(VmState.STOPPING);
}
else if( s.equalsIgnoreCase("pausing") ) {
vm.setCurrentState(VmState.PAUSING);
}
else if( s.equalsIgnoreCase("suspending") ) {
vm.setCurrentState(VmState.SUSPENDING);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( vm.getCurrentState().equals(VmState.RUNNING) && imaging ) {
vm.setCurrentState(VmState.PENDING);
}
if( server.has("created") ) {
vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created")));
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
String[] names = JSONObject.getNames(addrs);
if( names != null && names.length > 0 ) {
ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
ArrayList<RawAddress> priv = new ArrayList<RawAddress>();
for( String name : names ) {
JSONArray arr = addrs.getJSONArray(name);
for( int i=0; i<arr.length(); i++ ) {
RawAddress addr = null;
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4);
}
else {
JSONObject a = arr.getJSONObject(i);
if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV4);
}
else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV6);
}
}
if( addr != null ) {
if( addr.isPublicIpAddress() ) {
pub.add(addr);
}
else {
priv.add(addr);
}
}
}
if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) {
for( VLAN network : networks ) {
if( network.getName().equals(name) ) {
vm.setProviderVlanId(network.getProviderVlanId());
break;
}
}
}
}
vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
}
RawAddress[] raw = vm.getPublicAddresses();
if( raw != null ) {
for( RawAddress addr : vm.getPublicAddresses() ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv4 ) {
String serverId = addr.getServerId();
if( serverId != null && serverId.equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv6 ) {
String serverId = addr.getServerId();
if( serverId != null && addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv6 ) {
if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
if( vm.getDescription() == null ) {
vm.setDescription(vm.getName());
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
if (getProvider().getProviderName().equalsIgnoreCase("RACKSPACE")){
//Rackspace does not support the concept for firewalls in servers
vm.setProviderFirewallIds(null);
}
else{
Iterable<String> fwIds = listFirewalls(vm.getProviderVirtualMachineId(), server);
int count = 0;
//noinspection UnusedDeclaration
for( String id : fwIds ) {
count++;
}
String[] ids = new String[count];
int i = 0;
for( String id : fwIds ) {
ids[i++] = id;
}
vm.setProviderFirewallIds(ids);
}
return vm;
}
}
| true | true | private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
String description = null;
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(getTenantId());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(server.getString("id"));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") && !server.isNull("description") ) {
description = server.getString("description");
}
if( server.has("kernel_id") ) {
vm.setProviderKernelImageId(server.getString("kernel_id"));
}
if( server.has("ramdisk_id") ) {
vm.setProviderRamdiskImageId(server.getString("ramdisk_id"));
}
JSONObject md = (server.has("metadata") && !server.isNull("metadata")) ? server.getJSONObject("metadata") : null;
HashMap<String,String> map = new HashMap<String,String>();
boolean imaging = false;
if( md != null ) {
if( md.has("org.dasein.description") && vm.getDescription() == null ) {
description = md.getString("org.dasein.description");
}
else if( md.has("Server Label") ) {
description = md.getString("Server Label");
}
if( md.has("org.dasein.platform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( server.has("OS-EXT-STS:task_state") && !server.isNull("OS-EXT-STS:task_state") ) {
String t = server.getString("OS-EXT-STS:task_state");
map.put("OS-EXT-STS:task_state", t);
imaging = t.equalsIgnoreCase("image_snapshot");
}
if( description == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
else {
vm.setDescription(description);
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
if( server.has("image") ) {
JSONObject img = server.getJSONObject("image");
if( img.has("id") ) {
vm.setProviderMachineImageId(img.getString("id"));
}
}
if( server.has("flavor") ) {
JSONObject f = server.getJSONObject("flavor");
if( f.has("id") ) {
vm.setProductId(f.getString("id"));
}
}
else if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
vm.setRootPassword("adminPass");
}
if( server.has("key_name") ) {
vm.setProviderShellKeyIds(server.getString("key_name"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.startsWith("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equalsIgnoreCase("paused") ) {
vm.setCurrentState(VmState.PAUSED);
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
vm.setCurrentState(VmState.STOPPED);
}
else if( s.equalsIgnoreCase("stopping") ) {
vm.setCurrentState(VmState.STOPPING);
}
else if( s.equalsIgnoreCase("pausing") ) {
vm.setCurrentState(VmState.PAUSING);
}
else if( s.equalsIgnoreCase("suspending") ) {
vm.setCurrentState(VmState.SUSPENDING);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( vm.getCurrentState().equals(VmState.RUNNING) && imaging ) {
vm.setCurrentState(VmState.PENDING);
}
if( server.has("created") ) {
vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created")));
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
String[] names = JSONObject.getNames(addrs);
if( names != null && names.length > 0 ) {
ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
ArrayList<RawAddress> priv = new ArrayList<RawAddress>();
for( String name : names ) {
JSONArray arr = addrs.getJSONArray(name);
for( int i=0; i<arr.length(); i++ ) {
RawAddress addr = null;
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4);
}
else {
JSONObject a = arr.getJSONObject(i);
if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV4);
}
else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV6);
}
}
if( addr != null ) {
if( addr.isPublicIpAddress() ) {
pub.add(addr);
}
else {
priv.add(addr);
}
}
}
if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) {
for( VLAN network : networks ) {
if( network.getName().equals(name) ) {
vm.setProviderVlanId(network.getProviderVlanId());
break;
}
}
}
}
vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
}
RawAddress[] raw = vm.getPublicAddresses();
if( raw != null ) {
for( RawAddress addr : vm.getPublicAddresses() ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv4 ) {
String serverId = addr.getServerId();
if( serverId != null && serverId.equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv6 ) {
String serverId = addr.getServerId();
if( serverId != null && addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv6 ) {
if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
if( vm.getDescription() == null ) {
vm.setDescription(vm.getName());
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
if (getProvider().getProviderName().equalsIgnoreCase("RACKSPACE")){
//Rackspace does not support the concept for firewalls in servers
vm.setProviderFirewallIds(null);
}
else{
Iterable<String> fwIds = listFirewalls(vm.getProviderVirtualMachineId(), server);
int count = 0;
//noinspection UnusedDeclaration
for( String id : fwIds ) {
count++;
}
String[] ids = new String[count];
int i = 0;
for( String id : fwIds ) {
ids[i++] = id;
}
vm.setProviderFirewallIds(ids);
}
return vm;
}
| private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server, @Nonnull Iterable<IpAddress> ipv4, @Nonnull Iterable<IpAddress> ipv6, @Nonnull Iterable<VLAN> networks) throws JSONException, InternalException, CloudException {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
String description = null;
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(getTenantId());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(server.getString("id"));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") && !server.isNull("description") ) {
description = server.getString("description");
}
if( server.has("kernel_id") ) {
vm.setProviderKernelImageId(server.getString("kernel_id"));
}
if( server.has("ramdisk_id") ) {
vm.setProviderRamdiskImageId(server.getString("ramdisk_id"));
}
JSONObject md = (server.has("metadata") && !server.isNull("metadata")) ? server.getJSONObject("metadata") : null;
HashMap<String,String> map = new HashMap<String,String>();
boolean imaging = false;
if( md != null ) {
if( md.has("org.dasein.description") && vm.getDescription() == null ) {
description = md.getString("org.dasein.description");
}
else if( md.has("Server Label") ) {
description = md.getString("Server Label");
}
if( md.has("org.dasein.platform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("org.dasein.platform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( server.has("OS-EXT-STS:task_state") && !server.isNull("OS-EXT-STS:task_state") ) {
String t = server.getString("OS-EXT-STS:task_state");
map.put("OS-EXT-STS:task_state", t);
imaging = t.equalsIgnoreCase("image_snapshot");
}
if( description == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
else {
vm.setDescription(description);
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
if( server.has("image") ) {
JSONObject img = server.getJSONObject("image");
if( img.has("id") ) {
vm.setProviderMachineImageId(img.getString("id"));
}
}
if( server.has("flavor") ) {
JSONObject f = server.getJSONObject("flavor");
if( f.has("id") ) {
vm.setProductId(f.getString("id"));
}
}
else if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
vm.setRootPassword(server.getString("adminPass"));
}
if( server.has("key_name") ) {
vm.setProviderShellKeyIds(server.getString("key_name"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.startsWith("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equalsIgnoreCase("paused") ) {
vm.setCurrentState(VmState.PAUSED);
}
else if( s.equalsIgnoreCase("stopped") || s.equalsIgnoreCase("shutoff")) {
vm.setCurrentState(VmState.STOPPED);
}
else if( s.equalsIgnoreCase("stopping") ) {
vm.setCurrentState(VmState.STOPPING);
}
else if( s.equalsIgnoreCase("pausing") ) {
vm.setCurrentState(VmState.PAUSING);
}
else if( s.equalsIgnoreCase("suspending") ) {
vm.setCurrentState(VmState.SUSPENDING);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
logger.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( vm.getCurrentState().equals(VmState.RUNNING) && imaging ) {
vm.setCurrentState(VmState.PENDING);
}
if( server.has("created") ) {
vm.setCreationTimestamp(((NovaOpenStack)getProvider()).parseTimestamp(server.getString("created")));
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
String[] names = JSONObject.getNames(addrs);
if( names != null && names.length > 0 ) {
ArrayList<RawAddress> pub = new ArrayList<RawAddress>();
ArrayList<RawAddress> priv = new ArrayList<RawAddress>();
for( String name : names ) {
JSONArray arr = addrs.getJSONArray(name);
for( int i=0; i<arr.length(); i++ ) {
RawAddress addr = null;
if( ((NovaOpenStack)getProvider()).getMinorVersion() == 0 && ((NovaOpenStack)getProvider()).getMajorVersion() == 1 ) {
addr = new RawAddress(arr.getString(i).trim(), IPVersion.IPV4);
}
else {
JSONObject a = arr.getJSONObject(i);
if( a.has("version") && a.getInt("version") == 4 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV4);
}
else if( a.has("version") && a.getInt("version") == 6 && a.has("addr") ) {
addr = new RawAddress(a.getString("addr"), IPVersion.IPV6);
}
}
if( addr != null ) {
if( addr.isPublicIpAddress() ) {
pub.add(addr);
}
else {
priv.add(addr);
}
}
}
if( vm.getProviderVlanId() == null && !name.equals("public") && !name.equals("private") && !name.equals("nova_fixed") ) {
for( VLAN network : networks ) {
if( network.getName().equals(name) ) {
vm.setProviderVlanId(network.getProviderVlanId());
break;
}
}
}
}
vm.setPublicAddresses(pub.toArray(new RawAddress[pub.size()]));
vm.setPrivateAddresses(priv.toArray(new RawAddress[priv.size()]));
}
RawAddress[] raw = vm.getPublicAddresses();
if( raw != null ) {
for( RawAddress addr : vm.getPublicAddresses() ) {
if( addr.getVersion().equals(IPVersion.IPV4) ) {
for( IpAddress a : ipv4 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
else if( addr.getVersion().equals(IPVersion.IPV6) ) {
for( IpAddress a : ipv6 ) {
if( a.getRawAddress().getIpAddress().equals(addr.getIpAddress()) ) {
vm.setProviderAssignedIpAddressId(a.getProviderIpAddressId());
break;
}
}
}
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv4 ) {
String serverId = addr.getServerId();
if( serverId != null && serverId.equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv6 ) {
String serverId = addr.getServerId();
if( serverId != null && addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getProviderAssignedIpAddressId() == null ) {
for( IpAddress addr : ipv6 ) {
if( addr.getServerId().equals(vm.getProviderVirtualMachineId()) ) {
vm.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
}
vm.setProviderRegionId(getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "-a");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
if( vm.getDescription() == null ) {
vm.setDescription(vm.getName());
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
if (getProvider().getProviderName().equalsIgnoreCase("RACKSPACE")){
//Rackspace does not support the concept for firewalls in servers
vm.setProviderFirewallIds(null);
}
else{
Iterable<String> fwIds = listFirewalls(vm.getProviderVirtualMachineId(), server);
int count = 0;
//noinspection UnusedDeclaration
for( String id : fwIds ) {
count++;
}
String[] ids = new String[count];
int i = 0;
for( String id : fwIds ) {
ids[i++] = id;
}
vm.setProviderFirewallIds(ids);
}
return vm;
}
|
diff --git a/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/text/ScionTokenScanner.java b/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/text/ScionTokenScanner.java
index 1193c28f..ec34a2a8 100644
--- a/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/text/ScionTokenScanner.java
+++ b/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/text/ScionTokenScanner.java
@@ -1,291 +1,308 @@
package net.sf.eclipsefp.haskell.ui.internal.editors.haskell.text;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import net.sf.eclipsefp.haskell.buildwrapper.BWFacade;
import net.sf.eclipsefp.haskell.buildwrapper.BuildWrapperPlugin;
import net.sf.eclipsefp.haskell.buildwrapper.types.Occurrence;
import net.sf.eclipsefp.haskell.buildwrapper.types.TokenDef;
import net.sf.eclipsefp.haskell.core.codeassist.IScionTokens;
import net.sf.eclipsefp.haskell.core.util.ResourceUtil;
import net.sf.eclipsefp.haskell.ui.HaskellUIPlugin;
import net.sf.eclipsefp.haskell.ui.internal.preferences.editor.IEditorPreferenceNames;
import net.sf.eclipsefp.haskell.ui.internal.preferences.editor.SyntaxPreviewer;
import net.sf.eclipsefp.haskell.ui.internal.util.UITexts;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.rules.IPartitionTokenScanner;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.swt.widgets.Display;
import org.json.JSONArray;
/**
* Uses Scion tokenTypesArbitrary function to get tokens for a haskell source
*
* @author JP Moresmau
*/
public class ScionTokenScanner implements IPartitionTokenScanner, IEditorPreferenceNames {
private final ScannerManager man;
private final IFile file;
private IDocument doc;
private String contents;
private TokenDef currentTokenDef;
private List<TokenDef> lTokenDefs;
private ListIterator<TokenDef> tokenDefs;
private final Map<List<String>,List<TokenDef>> occurrences=new HashMap<List<String>,List<TokenDef>>();
private final List<List<String>> tokenLocations=new ArrayList<List<String>>();
private IToken currentToken;
private int currentOffset;
private int currentLength;
private int offset;
private int length;
private File tgt;
private boolean checkedTabs=false;
private final Map<String,IToken> tokenByTypes;
public ScionTokenScanner(final ScannerManager man,final IFile file){
this.man=man;
this.file=file;
this.tokenByTypes = new HashMap<String, IToken>() {
// Eclipse insists on a serial version identifier, not that this hash map will ever
// get serialized...
private static final long serialVersionUID = 3579246300065591883L;
{
put( IScionTokens.LITERAL_STRING, man.createToken( EDITOR_STRING_COLOR, EDITOR_STRING_BOLD ) );
put( IScionTokens.LITERAL_CHAR, man.createToken( EDITOR_CHAR_COLOR, EDITOR_CHAR_BOLD ) );
put( IScionTokens.DOCUMENTATION_ANNOTATION, man.createToken( EDITOR_COMMENT_COLOR,EDITOR_COMMENT_BOLD ) );
put( IScionTokens.LITERATE_COMMENT, man.createToken( EDITOR_LITERATE_COMMENT_COLOR, EDITOR_LITERATE_COMMENT_BOLD ) );
put( IScionTokens.KEYWORD, man.createToken( EDITOR_KEYWORD_COLOR, EDITOR_KEYWORD_BOLD ) );
put( IScionTokens.GHC_EXTENSION_KEYWORD, man.createToken( EDITOR_KEYWORD_COLOR, EDITOR_KEYWORD_BOLD ) );
put( IScionTokens.LITERAL_INTEGER, man.createToken( EDITOR_NUMBER_COLOR, EDITOR_NUMBER_BOLD ) );
put( IScionTokens.LITERAL_RATIONAL, man.createToken( EDITOR_NUMBER_COLOR, EDITOR_NUMBER_BOLD ) );
put( IScionTokens.LITERAL_WORD, man.createToken( EDITOR_NUMBER_COLOR, EDITOR_NUMBER_BOLD ) );
put( IScionTokens.LITERAL_FLOAT, man.createToken( EDITOR_NUMBER_COLOR, EDITOR_NUMBER_BOLD ) );
put( IScionTokens.IDENTIFIER_CONSTRUCTOR, man.createToken( EDITOR_CON_COLOR, EDITOR_CON_BOLD ) );
put( IScionTokens.IDENTIFIER_VARIABLE, man.createToken( EDITOR_VAR_COLOR, EDITOR_VAR_BOLD ) );
put( IScionTokens.SYMBOL_RESERVED, man.createToken( EDITOR_SYMBOL_COLOR, EDITOR_SYMBOL_BOLD ) );
put( IScionTokens.SYMBOL_SPECIAL, man.createToken( EDITOR_SYMBOL_COLOR, EDITOR_SYMBOL_BOLD ) );
put( IScionTokens.PREPROCESSOR_TEXT, man.createToken( EDITOR_CPP_COLOR, EDITOR_CPP_BOLD ) );
put( IScionTokens.TEMPLATE_HASKELL, man.createToken( EDITOR_TH_COLOR, EDITOR_TH_BOLD ) );
}
};
}
public int getTokenLength() {
if (currentTokenDef!=null){
return currentLength;
}
return 0;
}
public int getTokenOffset() {
if (currentTokenDef!=null){
return currentOffset;
}
return 0;
}
public IToken nextToken() {
do {
if (tokenDefs!=null && tokenDefs.hasNext()){
TokenDef nextTokenDef=tokenDefs.next();
try {
int nextOffset=nextTokenDef.getLocation().getStartOffset( doc );
int nextEnd=nextTokenDef.getLocation().getEndOffset( doc );
int end=Math.min( offset+length,nextEnd);
//addTokenOccurence( nextOffset, nextEnd, nextTokenDef );
IToken nextToken=getTokenFromTokenDef( nextTokenDef);
if (currentToken!=null && currentToken.getData().equals( nextToken.getData() ) &&
currentOffset+currentLength<nextOffset){
nextOffset= currentOffset+currentLength;
}
int nextLength=end-nextOffset;
currentLength=nextLength;
currentOffset=nextOffset;
currentTokenDef=nextTokenDef;
currentToken=nextToken;
if (currentOffset>offset+length) {
return Token.EOF;
}
} catch (BadLocationException ble){
HaskellUIPlugin.log( ble );
}
} else {
return Token.EOF;
}
} while(currentOffset<offset);
return currentToken;
}
private void addTokenOccurence(final String s,final int offset,final int end,final TokenDef td){
String name=td.getName();
if (name.equals( IScionTokens.KEYWORD )
|| name.equals( IScionTokens.GHC_EXTENSION_KEYWORD )
|| name.equals( IScionTokens.IDENTIFIER_CONSTRUCTOR )
|| name.equals( IScionTokens.IDENTIFIER_VARIABLE )
|| name.equals( IScionTokens.SYMBOL_RESERVED )
){ //|| name.equals( IScionTokens.SYMBOL_SPECIAL )
List<String> key=new LinkedList<String>();
key.add(td.getName());
key.add( s.substring(offset,end) );
while (tokenLocations.size()<offset){
tokenLocations.add( null );
}
while(tokenLocations.size()<end){
tokenLocations.add(key);
}
List<TokenDef> l=occurrences.get( key );
if (l==null){
l=new LinkedList<TokenDef>();
occurrences.put( key, l );
}
l.add(td);
}
}
public List<Occurrence> getOccurrences(final int offset){
LinkedList<Occurrence> ret=new LinkedList<Occurrence>();
if (offset>0 && offset<tokenLocations.size()){
List<String> key=tokenLocations.get( offset );
if (key!=null){
List<TokenDef> l=occurrences.get( key );
if (l!=null){
for (TokenDef td:l){
ret.add(new Occurrence( td ));
}
return ret;
}
}
}
return ret;
}
public void setRange( final IDocument document, final int offset, final int length ) {
currentTokenDef = null;
// currentToken=null;
tokenDefs = null;
occurrences.clear();
tokenLocations.clear();
if( file != null ) {
String newContents = document.get();
if( !document.equals( doc ) || !newContents.equals( contents ) || lTokenDefs == null ) {
doc = document;
contents = newContents;
if (!checkedTabs){
checkedTabs=true;
if (contents.contains( "\t" )){
if (MessageDialog.openConfirm( Display.getCurrent().getActiveShell() , UITexts.error_tabs , UITexts.error_tabs_message )){
/*IDocumentProvider prov=new TextFileDocumentProvider();
prov.connect(file);
IDocument doc2=prov.getDocument( file );*/
int tw=HaskellUIPlugin.getDefault().getPreferenceStore().getInt( EDITOR_TAB_WIDTH );
StringBuilder sb=new StringBuilder();
for (int a=0;a<tw;a++){
sb.append(" ");
}
contents=contents.replace( "\t",sb.toString() );
// doc2.set(contents);
document.set(contents);
// prov.saveDocument( new NullProgressMonitor(), file, doc2, true );
}
}
}
BWFacade f=BuildWrapperPlugin.getFacade( file.getProject() );
if (f==null){
f=new BWFacade();
f.setBwPath( BuildWrapperPlugin.getBwPath() );
f.setProject( file.getProject() );
f.setWorkingDir(new File(file.getProject().getLocation().toOSString()));
}
//long t0=System.currentTimeMillis();
if (tgt==null){
tgt=f.write( file, contents );
} else {
f.write( tgt, contents );
}
//long t01=System.currentTimeMillis();
lTokenDefs = f.tokenTypes( file);
//long t1=System.currentTimeMillis();
//int l=ScionPlugin.getSharedScionInstance().tokenTypes( file, contents ).size();
//long t2=System.currentTimeMillis();
//HaskellUIPlugin.log( "bw:"+(t1-t0)+"ms ("+lTokenDefs.size()+",write: "+(t01-t0)+"ms ), scion:"+(t2-t1)+"ms ("+l+")", IStatus.INFO );
}
} else {
try {
InputStream stream = SyntaxPreviewer.class.getResourceAsStream( "preview.json" );
// preview file
JSONArray result = new JSONArray( ResourceUtil.readStream( stream ) );
lTokenDefs = new ArrayList<TokenDef>( result.length() );
for( int i = 0; i < result.length(); ++i ) {
JSONArray arr = result.getJSONArray( i );
lTokenDefs.add( new TokenDef( arr ) );
}
} catch( Exception ex ) {
HaskellUIPlugin.log( "Could not read preview file.", ex ); //$NON-NLS-1$
}
}
this.doc = document;
if( lTokenDefs != null && lTokenDefs.size() > 0 ) {
tokenDefs = lTokenDefs.listIterator();
}
String s=doc.get();
+ //long previousOffset=-1;
+ //long previousEnd=-1;
for (TokenDef nextTokenDef:lTokenDefs){
try {
int nextOffset=nextTokenDef.getLocation().getStartOffset( doc );
+// if (nextOffset<previousOffset){
+// HaskellUIPlugin.log( "offset error: "+nextOffset+"<"+previousOffset, IStatus.ERROR );
+// }
+// if (nextOffset<previousEnd){
+// HaskellUIPlugin.log( "offset error at line "+nextTokenDef.getLocation().getStartLine()+": "+nextOffset+"<"+previousEnd, IStatus.ERROR );
+// }
int nextEnd=nextTokenDef.getLocation().getEndOffset( doc );
+// if (nextOffset>nextEnd){
+// HaskellUIPlugin.log( "extent error: "+nextOffset+">"+nextEnd, IStatus.ERROR );
+// }
+// if (previousOffset>nextEnd){
+// HaskellUIPlugin.log( "extent error: "+nextEnd+">"+previousOffset, IStatus.ERROR );
+// }
+ //HaskellUIPlugin.log(nextOffset+"->"+nextEnd, IStatus.INFO);
addTokenOccurence( s,nextOffset, nextEnd, nextTokenDef );
+// previousOffset=nextOffset;
+// previousEnd=nextEnd;
} catch (BadLocationException ble){
HaskellUIPlugin.log( ble );
}
}
this.offset = offset;
this.length = length;
}
private IToken getTokenFromTokenDef(final TokenDef td){
IToken tok=tokenByTypes.get(td.getName());
if (tok!=null){
return tok;
}
return man.createToken( EDITOR_DEFAULT_COLOR, EDITOR_DEFAULT_BOLD );
}
public void setPartialRange( final IDocument document, final int offset, final int length,
final String contentType, final int partitionOffset ) {
setRange( document, offset, length );
}
}
| false | true | public void setRange( final IDocument document, final int offset, final int length ) {
currentTokenDef = null;
// currentToken=null;
tokenDefs = null;
occurrences.clear();
tokenLocations.clear();
if( file != null ) {
String newContents = document.get();
if( !document.equals( doc ) || !newContents.equals( contents ) || lTokenDefs == null ) {
doc = document;
contents = newContents;
if (!checkedTabs){
checkedTabs=true;
if (contents.contains( "\t" )){
if (MessageDialog.openConfirm( Display.getCurrent().getActiveShell() , UITexts.error_tabs , UITexts.error_tabs_message )){
/*IDocumentProvider prov=new TextFileDocumentProvider();
prov.connect(file);
IDocument doc2=prov.getDocument( file );*/
int tw=HaskellUIPlugin.getDefault().getPreferenceStore().getInt( EDITOR_TAB_WIDTH );
StringBuilder sb=new StringBuilder();
for (int a=0;a<tw;a++){
sb.append(" ");
}
contents=contents.replace( "\t",sb.toString() );
// doc2.set(contents);
document.set(contents);
// prov.saveDocument( new NullProgressMonitor(), file, doc2, true );
}
}
}
BWFacade f=BuildWrapperPlugin.getFacade( file.getProject() );
if (f==null){
f=new BWFacade();
f.setBwPath( BuildWrapperPlugin.getBwPath() );
f.setProject( file.getProject() );
f.setWorkingDir(new File(file.getProject().getLocation().toOSString()));
}
//long t0=System.currentTimeMillis();
if (tgt==null){
tgt=f.write( file, contents );
} else {
f.write( tgt, contents );
}
//long t01=System.currentTimeMillis();
lTokenDefs = f.tokenTypes( file);
//long t1=System.currentTimeMillis();
//int l=ScionPlugin.getSharedScionInstance().tokenTypes( file, contents ).size();
//long t2=System.currentTimeMillis();
//HaskellUIPlugin.log( "bw:"+(t1-t0)+"ms ("+lTokenDefs.size()+",write: "+(t01-t0)+"ms ), scion:"+(t2-t1)+"ms ("+l+")", IStatus.INFO );
}
} else {
try {
InputStream stream = SyntaxPreviewer.class.getResourceAsStream( "preview.json" );
// preview file
JSONArray result = new JSONArray( ResourceUtil.readStream( stream ) );
lTokenDefs = new ArrayList<TokenDef>( result.length() );
for( int i = 0; i < result.length(); ++i ) {
JSONArray arr = result.getJSONArray( i );
lTokenDefs.add( new TokenDef( arr ) );
}
} catch( Exception ex ) {
HaskellUIPlugin.log( "Could not read preview file.", ex ); //$NON-NLS-1$
}
}
this.doc = document;
if( lTokenDefs != null && lTokenDefs.size() > 0 ) {
tokenDefs = lTokenDefs.listIterator();
}
String s=doc.get();
for (TokenDef nextTokenDef:lTokenDefs){
try {
int nextOffset=nextTokenDef.getLocation().getStartOffset( doc );
int nextEnd=nextTokenDef.getLocation().getEndOffset( doc );
addTokenOccurence( s,nextOffset, nextEnd, nextTokenDef );
} catch (BadLocationException ble){
HaskellUIPlugin.log( ble );
}
}
this.offset = offset;
this.length = length;
}
| public void setRange( final IDocument document, final int offset, final int length ) {
currentTokenDef = null;
// currentToken=null;
tokenDefs = null;
occurrences.clear();
tokenLocations.clear();
if( file != null ) {
String newContents = document.get();
if( !document.equals( doc ) || !newContents.equals( contents ) || lTokenDefs == null ) {
doc = document;
contents = newContents;
if (!checkedTabs){
checkedTabs=true;
if (contents.contains( "\t" )){
if (MessageDialog.openConfirm( Display.getCurrent().getActiveShell() , UITexts.error_tabs , UITexts.error_tabs_message )){
/*IDocumentProvider prov=new TextFileDocumentProvider();
prov.connect(file);
IDocument doc2=prov.getDocument( file );*/
int tw=HaskellUIPlugin.getDefault().getPreferenceStore().getInt( EDITOR_TAB_WIDTH );
StringBuilder sb=new StringBuilder();
for (int a=0;a<tw;a++){
sb.append(" ");
}
contents=contents.replace( "\t",sb.toString() );
// doc2.set(contents);
document.set(contents);
// prov.saveDocument( new NullProgressMonitor(), file, doc2, true );
}
}
}
BWFacade f=BuildWrapperPlugin.getFacade( file.getProject() );
if (f==null){
f=new BWFacade();
f.setBwPath( BuildWrapperPlugin.getBwPath() );
f.setProject( file.getProject() );
f.setWorkingDir(new File(file.getProject().getLocation().toOSString()));
}
//long t0=System.currentTimeMillis();
if (tgt==null){
tgt=f.write( file, contents );
} else {
f.write( tgt, contents );
}
//long t01=System.currentTimeMillis();
lTokenDefs = f.tokenTypes( file);
//long t1=System.currentTimeMillis();
//int l=ScionPlugin.getSharedScionInstance().tokenTypes( file, contents ).size();
//long t2=System.currentTimeMillis();
//HaskellUIPlugin.log( "bw:"+(t1-t0)+"ms ("+lTokenDefs.size()+",write: "+(t01-t0)+"ms ), scion:"+(t2-t1)+"ms ("+l+")", IStatus.INFO );
}
} else {
try {
InputStream stream = SyntaxPreviewer.class.getResourceAsStream( "preview.json" );
// preview file
JSONArray result = new JSONArray( ResourceUtil.readStream( stream ) );
lTokenDefs = new ArrayList<TokenDef>( result.length() );
for( int i = 0; i < result.length(); ++i ) {
JSONArray arr = result.getJSONArray( i );
lTokenDefs.add( new TokenDef( arr ) );
}
} catch( Exception ex ) {
HaskellUIPlugin.log( "Could not read preview file.", ex ); //$NON-NLS-1$
}
}
this.doc = document;
if( lTokenDefs != null && lTokenDefs.size() > 0 ) {
tokenDefs = lTokenDefs.listIterator();
}
String s=doc.get();
//long previousOffset=-1;
//long previousEnd=-1;
for (TokenDef nextTokenDef:lTokenDefs){
try {
int nextOffset=nextTokenDef.getLocation().getStartOffset( doc );
// if (nextOffset<previousOffset){
// HaskellUIPlugin.log( "offset error: "+nextOffset+"<"+previousOffset, IStatus.ERROR );
// }
// if (nextOffset<previousEnd){
// HaskellUIPlugin.log( "offset error at line "+nextTokenDef.getLocation().getStartLine()+": "+nextOffset+"<"+previousEnd, IStatus.ERROR );
// }
int nextEnd=nextTokenDef.getLocation().getEndOffset( doc );
// if (nextOffset>nextEnd){
// HaskellUIPlugin.log( "extent error: "+nextOffset+">"+nextEnd, IStatus.ERROR );
// }
// if (previousOffset>nextEnd){
// HaskellUIPlugin.log( "extent error: "+nextEnd+">"+previousOffset, IStatus.ERROR );
// }
//HaskellUIPlugin.log(nextOffset+"->"+nextEnd, IStatus.INFO);
addTokenOccurence( s,nextOffset, nextEnd, nextTokenDef );
// previousOffset=nextOffset;
// previousEnd=nextEnd;
} catch (BadLocationException ble){
HaskellUIPlugin.log( ble );
}
}
this.offset = offset;
this.length = length;
}
|
diff --git a/src/main/java/me/wizzledonker/plugins/telepads/telepadsPlayerListener.java b/src/main/java/me/wizzledonker/plugins/telepads/telepadsPlayerListener.java
index 4683108..b685a80 100644
--- a/src/main/java/me/wizzledonker/plugins/telepads/telepadsPlayerListener.java
+++ b/src/main/java/me/wizzledonker/plugins/telepads/telepadsPlayerListener.java
@@ -1,62 +1,63 @@
package me.wizzledonker.plugins.telepads;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
/**
*
* @author Win
*/
public class telepadsPlayerListener implements Listener{
public static Telepads plugin;
private Set<Player> onPad = new HashSet<Player>();
public telepadsPlayerListener(Telepads instance) {
plugin = instance;
}
@EventHandler
public void whenPlayerMoves(PlayerMoveEvent event) {
final Player player = event.getPlayer();
if (onPad.contains(player)) return;
if (player.hasPermission("telepads.use")) {
Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (!checkPad(block)) {
return;
}
final Location loc = new Location(null, block.getX(), block.getY(), block.getZ());
if (!plugin.telepads.containsKey(loc)) {
return;
}
onPad.add(player);
player.sendMessage(ChatColor.GRAY + plugin.wait_msg.replace("%time%", plugin.telepad_teleport_time + " Seconds"));
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
onPad.remove(player);
Block cBlock = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (!checkPad(cBlock)) return;
- if (!plugin.telepads.containsKey(loc)) return;
+ Location floc = new Location(null, cBlock.getX(), cBlock.getY(), cBlock.getZ());
+ if (!plugin.telepads.containsKey(floc)) return;
plugin.gotoPad(loc, player);
}
}, plugin.telepad_teleport_time * 20L);
}
}
private boolean checkPad(Block block) {
if (block.getTypeId() != plugin.telepad_item_id) {
return false;
}
return true;
}
}
| true | true | public void whenPlayerMoves(PlayerMoveEvent event) {
final Player player = event.getPlayer();
if (onPad.contains(player)) return;
if (player.hasPermission("telepads.use")) {
Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (!checkPad(block)) {
return;
}
final Location loc = new Location(null, block.getX(), block.getY(), block.getZ());
if (!plugin.telepads.containsKey(loc)) {
return;
}
onPad.add(player);
player.sendMessage(ChatColor.GRAY + plugin.wait_msg.replace("%time%", plugin.telepad_teleport_time + " Seconds"));
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
onPad.remove(player);
Block cBlock = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (!checkPad(cBlock)) return;
if (!plugin.telepads.containsKey(loc)) return;
plugin.gotoPad(loc, player);
}
}, plugin.telepad_teleport_time * 20L);
}
}
| public void whenPlayerMoves(PlayerMoveEvent event) {
final Player player = event.getPlayer();
if (onPad.contains(player)) return;
if (player.hasPermission("telepads.use")) {
Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (!checkPad(block)) {
return;
}
final Location loc = new Location(null, block.getX(), block.getY(), block.getZ());
if (!plugin.telepads.containsKey(loc)) {
return;
}
onPad.add(player);
player.sendMessage(ChatColor.GRAY + plugin.wait_msg.replace("%time%", plugin.telepad_teleport_time + " Seconds"));
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
onPad.remove(player);
Block cBlock = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (!checkPad(cBlock)) return;
Location floc = new Location(null, cBlock.getX(), cBlock.getY(), cBlock.getZ());
if (!plugin.telepads.containsKey(floc)) return;
plugin.gotoPad(loc, player);
}
}, plugin.telepad_teleport_time * 20L);
}
}
|
diff --git a/ide/eclipse/dependencies/wso2-esb-template-plugin/src/main/java/org/wso2/maven/template/ESBTemplatePOMGenMojo.java b/ide/eclipse/dependencies/wso2-esb-template-plugin/src/main/java/org/wso2/maven/template/ESBTemplatePOMGenMojo.java
index 7565a590c..dcde7fc58 100644
--- a/ide/eclipse/dependencies/wso2-esb-template-plugin/src/main/java/org/wso2/maven/template/ESBTemplatePOMGenMojo.java
+++ b/ide/eclipse/dependencies/wso2-esb-template-plugin/src/main/java/org/wso2/maven/template/ESBTemplatePOMGenMojo.java
@@ -1,146 +1,150 @@
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.template;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.wso2.maven.capp.model.Artifact;
import org.wso2.maven.capp.mojo.AbstractPOMGenMojo;
import org.wso2.maven.capp.utils.CAppMavenUtils;
import org.wso2.maven.capp.utils.WSO2MavenPluginConstantants;
import org.wso2.maven.esb.ESBArtifact;
import org.wso2.maven.esb.utils.ESBMavenUtils;
/**
* This is the Maven Mojo used for generating a pom for a sequence artifact
* from the old CApp project structure
*
* @goal pom-gen
*
*/
public class ESBTemplatePOMGenMojo extends AbstractPOMGenMojo {
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/**
* Maven ProjectHelper.
*
* @component
*/
private MavenProjectHelper projectHelper;
/**
* The path of the location to output the pom
*
* @parameter expression="${project.build.directory}/artifacts"
*/
private File outputLocation;
/**
* The resulting extension of the file
*
* @parameter
*/
private File artifactLocation;
/**
* POM location for the module project
*
* @parameter expression="${project.build.directory}/pom.xml"
*/
private File moduleProject;
/**
* Group id to use for the generated pom
*
* @parameter
*/
private String groupId;
/**
* Comma separated list of "artifact_type=extension" to be used when creating dependencies for other capp artifacts
*
* @parameter
*/
public String typeList;
private MavenProject mavenModuleProject;
private static final String ARTIFACT_TYPE="synapse/template";
private List<ESBArtifact> retrieveArtifacts() {
return ESBMavenUtils.retrieveArtifacts(getArtifactLocation());
}
public void execute() throws MojoExecutionException, MojoFailureException {
//Retrieving all the existing ESB Artifacts for the given Maven project
List<ESBArtifact> artifacts = retrieveArtifacts();
//Artifact list
List<Artifact> mappedArtifacts=new ArrayList<Artifact>();
//Mapping ESBArtifacts to C-App artifacts so that we can reuse the maven-endpoint-plugin
for (ESBArtifact esbArtifact : artifacts) {
Artifact artifact=new Artifact();
artifact.setName(esbArtifact.getName());
artifact.setVersion(this.getProject().getVersion());
- artifact.setType(esbArtifact.getType());
+ if(("synapse/sequenceTemplate".equals(esbArtifact.getType()))||("synapse/endpointTemplate".equals(esbArtifact.getType()))){
+ artifact.setType("synapse/template");
+ }else{
+ artifact.setType(esbArtifact.getType());
+ }
artifact.setServerRole(esbArtifact.getServerRole());
artifact.setFile(esbArtifact.getFile());
artifact.setSource(new File(getArtifactLocation(),"artifact.xml"));
mappedArtifacts.add(artifact);
}
//Calling the process artifacts method of super type to continue the sequence.
super.processArtifacts(mappedArtifacts);
}
protected void copyResources(MavenProject project, File projectLocation, Artifact artifact)throws IOException {
File sequenceArtifact = artifact.getFile();
FileUtils.copyFile(sequenceArtifact, new File(projectLocation, sequenceArtifact.getName()));
}
protected void addPlugins(MavenProject artifactMavenProject, Artifact artifact) {
Plugin plugin = CAppMavenUtils.createPluginEntry(artifactMavenProject,
"org.wso2.maven", "wso2-esb-template-plugin",
WSO2MavenPluginConstantants.WSO2_ESB_TEMPLATE_VERSION,true);
Xpp3Dom configuration = (Xpp3Dom)plugin.getConfiguration();
//add configuration
Xpp3Dom aritfact = CAppMavenUtils.createConfigurationNode(configuration,"artifact");
aritfact.setValue(artifact.getFile().getName());
}
protected String getArtifactType() {
return ARTIFACT_TYPE;
}
}
| true | true | public void execute() throws MojoExecutionException, MojoFailureException {
//Retrieving all the existing ESB Artifacts for the given Maven project
List<ESBArtifact> artifacts = retrieveArtifacts();
//Artifact list
List<Artifact> mappedArtifacts=new ArrayList<Artifact>();
//Mapping ESBArtifacts to C-App artifacts so that we can reuse the maven-endpoint-plugin
for (ESBArtifact esbArtifact : artifacts) {
Artifact artifact=new Artifact();
artifact.setName(esbArtifact.getName());
artifact.setVersion(this.getProject().getVersion());
artifact.setType(esbArtifact.getType());
artifact.setServerRole(esbArtifact.getServerRole());
artifact.setFile(esbArtifact.getFile());
artifact.setSource(new File(getArtifactLocation(),"artifact.xml"));
mappedArtifacts.add(artifact);
}
//Calling the process artifacts method of super type to continue the sequence.
super.processArtifacts(mappedArtifacts);
}
| public void execute() throws MojoExecutionException, MojoFailureException {
//Retrieving all the existing ESB Artifacts for the given Maven project
List<ESBArtifact> artifacts = retrieveArtifacts();
//Artifact list
List<Artifact> mappedArtifacts=new ArrayList<Artifact>();
//Mapping ESBArtifacts to C-App artifacts so that we can reuse the maven-endpoint-plugin
for (ESBArtifact esbArtifact : artifacts) {
Artifact artifact=new Artifact();
artifact.setName(esbArtifact.getName());
artifact.setVersion(this.getProject().getVersion());
if(("synapse/sequenceTemplate".equals(esbArtifact.getType()))||("synapse/endpointTemplate".equals(esbArtifact.getType()))){
artifact.setType("synapse/template");
}else{
artifact.setType(esbArtifact.getType());
}
artifact.setServerRole(esbArtifact.getServerRole());
artifact.setFile(esbArtifact.getFile());
artifact.setSource(new File(getArtifactLocation(),"artifact.xml"));
mappedArtifacts.add(artifact);
}
//Calling the process artifacts method of super type to continue the sequence.
super.processArtifacts(mappedArtifacts);
}
|
diff --git a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java
index 73c6d81fe..f5d8d92f5 100644
--- a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java
+++ b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java
@@ -1,918 +1,914 @@
/*******************************************************************************
* Copyright (c) 2006 The Regents of the University of California.
* This material was produced under U.S. Government contract W-7405-ENG-36
* for Los Alamos National Laboratory, which is operated by the University
* of California for the U.S. Department of Energy. The U.S. Government has
* rights to use, reproduce, and distribute this software. NEITHER THE
* GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* Additionally, 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
*
* LA-CC 04-115
*******************************************************************************/
package org.eclipse.ptp.rtsystem;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ptp.core.PTPCorePlugin;
import org.eclipse.ptp.core.attributes.AttributeDefinitionManager;
import org.eclipse.ptp.core.attributes.AttributeManager;
import org.eclipse.ptp.core.attributes.IAttribute;
import org.eclipse.ptp.core.attributes.IAttributeDefinition;
import org.eclipse.ptp.core.attributes.IllegalValueException;
import org.eclipse.ptp.core.attributes.IntegerAttribute;
import org.eclipse.ptp.core.attributes.StringAttribute;
import org.eclipse.ptp.core.elements.IPJob;
import org.eclipse.ptp.core.elements.attributes.ElementAttributeManager;
import org.eclipse.ptp.core.elements.attributes.ElementAttributes;
import org.eclipse.ptp.core.elements.attributes.ErrorAttributes;
import org.eclipse.ptp.core.elements.attributes.JobAttributes;
import org.eclipse.ptp.core.elements.attributes.MessageAttributes.Level;
import org.eclipse.ptp.core.util.RangeSet;
import org.eclipse.ptp.rtsystem.events.RuntimeAttributeDefinitionEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeConnectedStateEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeErrorStateEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeJobChangeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeMachineChangeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeMessageEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeNewJobEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeNewMachineEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeNewNodeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeNewProcessEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeNewQueueEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeNodeChangeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeProcessChangeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeQueueChangeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRemoveAllEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRemoveJobEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRemoveMachineEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRemoveNodeEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRemoveProcessEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRemoveQueueEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeRunningStateEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeShutdownStateEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeStartupErrorEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeSubmitJobErrorEvent;
import org.eclipse.ptp.rtsystem.events.RuntimeTerminateJobErrorEvent;
import org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeClient;
import org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeEventListener;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeAttributeDefEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeConnectedStateEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeErrorStateEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeJobChangeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeMachineChangeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeMessageEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewJobEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewMachineEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewNodeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewProcessEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewQueueEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNodeChangeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeProcessChangeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeQueueChangeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveAllEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveJobEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveMachineEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveNodeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveProcessEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveQueueEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRunningStateEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeShutdownStateEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeStartupErrorEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeSubmitJobErrorEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeTerminateJobErrorEvent;
/*
* ProxyAttributeDefEvents are formatted as follows:
*
* EVENT_HEADER NUM_DEFS ATTR_DEF ... ATTR_DEF
*
* where:
*
* EVENT_HEADER is the event message header
* NUM_DEFS is the number of attribute definitions to follow
* ATTR_DEF is an attribute definition of the form:
*
* NUM_ARGS ID TYPE NAME DESCRIPTION DEFAULT [ADDITIONAL_PARAMS]
*
* where:
*
* NUM_ARGS is the number of arguments in the attribute definition
* ID is a unique definition ID
* TYPE is the type of the attribute. Legal types are:
* 'BOOLEAN', 'DATE', 'DOUBLE', 'ENUMERATED', 'INTEGER', 'STRING', 'ARRAY'
* NAME is the short name of the attribute
* DESCRIPTION is the long name of the attribute
* DEFAULT is the default value of the attribute
* ADDITIONAL_PARAMS are optional parameters depending on the attribute type:
* BOOLEAN - none
* DATE - DATE_STYLE TIME_STYLE LOCALE [MIN MAX]
* DOUBLE - [MIN MAX]
* ENUMERATED - VAL ... VAL
* INTEGER - [MIN MAX]
* STRING - none
* ARRAY - none
* MIN is the minimum allowable value for the attribute
* MAX is the maximum allowable value for the attribute
* DATE_STYLE is the date format: SHORT, MEDIUM, LONG, or FULL
* TIME_STYLE is the time format: SHORT, MEDIUM, LONG, or FULL
* LOCALE is the country (see java.lang.Local)
* NUM_VALS is the number of enumerated values
* VAL is the enumerated value
*
* ProxyNew*Events are formatted as follows:
*
* EVENT_HEADER PARENT_ID NUM_RANGES ID_RANGE NUM_ATTRS KEY=VALUE ... KEY=VALUE ...
*
* where:
*
* EVENT_HEADER is the event message header
* PARENT_ID is the model element ID of the parent element
* NUM_RANGES is the number of ID_RANGEs to follow
* ID_RANGE is a range of model element ID's in RangeSet notation
* NUM_ATTRS is the number of attributes to follow
* KEY=VALUE are key/value pairs, where KEY is the attribute ID and VALUE is the attribute value
*
* Proxy*ChangeEvents are formatted as follows:
*
* EVENT_HEADER NUM_RANGES ID_RANGE NUM_ATTRS KEY=VALUE ... KEY=VALUE
*
* where:
*
* EVENT_HEADER is the event message header
* NUM_RANGES is the number of ID_RANGEs to follow
* ID_RANGE is a range of model element ID's in RangeSet notation
* NUM_ATTRS is the number of attributes to follow
* KEY=VALUE are key/value pairs, where KEY is the attribute ID and VALUE is the new attribute value
*
* ProxyRemove*Events (apart from ProxyRemoveAllEvent) are formatted as follows:
*
* EVENT_HEADER ID_RANGE
*
* where:
*
* EVENT_HEADER is the event message header
* ID_RANGE is a range of model element ID's in RangeSet notation.
*
* The ProxyRemoveAllEvent is formatted as follows:
*
* EVENT_HEADER
*
* where:
*
* EVENT_HEADER is the event message header
*/
public abstract class AbstractProxyRuntimeSystem extends AbstractRuntimeSystem implements IProxyRuntimeEventListener {
private final static int ATTR_MIN_LEN = 5;
protected IProxyRuntimeClient proxy = null;
private AttributeDefinitionManager attrDefManager;
private int jobSubIdCount = 0;
private Map<String, AttributeManager> jobSubs = Collections.synchronizedMap(new HashMap<String, AttributeManager>());
public AbstractProxyRuntimeSystem(IProxyRuntimeClient proxy, AttributeDefinitionManager manager) {
this.proxy = proxy;
this.attrDefManager = manager;
proxy.addProxyRuntimeEventListener(this);
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeAttributeDefEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeAttributeDefEvent)
*/
public void handleEvent(IProxyRuntimeAttributeDefEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length >= ATTR_MIN_LEN + 2) {
try {
int numDefs = Integer.parseInt(attrs[0]);
ArrayList<IAttributeDefinition<?,?,?>> attrDefs =
new ArrayList<IAttributeDefinition<?,?,?>>(numDefs);
int pos = 1;
for (int i = 0; i < numDefs; i++) {
int numArgs = Integer.parseInt(attrs[pos]);
if (numArgs >= ATTR_MIN_LEN && pos + numArgs < attrs.length) {
IAttributeDefinition<?,?,?> attrDef =
parseAttributeDefinition(attrs, pos + 1, pos + numArgs);
if (attrDef != null) {
attrDefs.add(attrDef);
}
pos += numArgs + 1;
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: bad arg count"));
return;
}
}
fireRuntimeAttributeDefinitionEvent(new RuntimeAttributeDefinitionEvent(attrDefs.toArray(new IAttributeDefinition[attrDefs.size()])));
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert arg to integer"));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: not enough arguments"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeEventListener#handleProxyRuntimeErrorStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeErrorStateEvent)
*/
public void handleEvent(IProxyRuntimeErrorStateEvent e) {
fireRuntimeErrorStateEvent(new RuntimeErrorStateEvent());
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeErrorEvent)
*/
public void handleEvent(IProxyRuntimeMessageEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length > 0) {
AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1);
fireRuntimeMessageEvent(new RuntimeMessageEvent(mgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeJobChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeJobChangeEvent)
*/
public void handleEvent(IProxyRuntimeJobChangeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0);
if (eMgr != null) {
fireRuntimeJobChangeEvent(new RuntimeJobChangeEvent(eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeMachineChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeMachineChangeEvent)
*/
public void handleEvent(IProxyRuntimeMachineChangeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0);
if (eMgr != null) {
fireRuntimeMachineChangeEvent(new RuntimeMachineChangeEvent(eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewJobEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewJobEvent)
*/
public void handleEvent(IProxyRuntimeNewJobEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 2) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1);
if (eMgr != null) {
/*
* Find any job submission attributes and add to the jobs
*/
for (Map.Entry<RangeSet, AttributeManager> entry : eMgr.getEntrySet()) {
StringAttribute subIdAttr = entry.getValue().getAttribute(JobAttributes.getSubIdAttributeDefinition());
if (subIdAttr != null) {
String subId = subIdAttr.getValueAsString();
AttributeManager mgr = jobSubs.get(subId);
if (mgr != null) {
entry.getValue().addAttributes(mgr.getAttributes());
}
jobSubs.remove(subId);
}
}
fireRuntimeNewJobEvent(new RuntimeNewJobEvent(attrs[0], eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewMachineEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewMachineEvent)
*/
public void handleEvent(IProxyRuntimeNewMachineEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 2) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1);
if (eMgr != null) {
fireRuntimeNewMachineEvent(new RuntimeNewMachineEvent(attrs[0], eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewNodeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewNodeEvent)
*/
public void handleEvent(IProxyRuntimeNewNodeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 2) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1);
if (eMgr != null) {
fireRuntimeNewNodeEvent(new RuntimeNewNodeEvent(attrs[0], eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewProcessEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewProcessEvent)
*/
public void handleEvent(IProxyRuntimeNewProcessEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 2) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1);
if (eMgr != null) {
fireRuntimeNewProcessEvent(new RuntimeNewProcessEvent(attrs[0], eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewQueueEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewQueueEvent)
*/
public void handleEvent(IProxyRuntimeNewQueueEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 2) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1);
if (eMgr != null) {
fireRuntimeNewQueueEvent(new RuntimeNewQueueEvent(attrs[0], eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNodeChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNodeChangeEvent)
*/
public void handleEvent(IProxyRuntimeNodeChangeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0);
if (eMgr != null) {
fireRuntimeNodeChangeEvent(new RuntimeNodeChangeEvent(eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeProcessChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeProcessChangeEvent)
*/
public void handleEvent(IProxyRuntimeProcessChangeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0);
if (eMgr != null) {
fireRuntimeProcessChangeEvent(new RuntimeProcessChangeEvent(eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeQueueChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeQueueChangeEvent)
*/
public void handleEvent(IProxyRuntimeQueueChangeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0);
if (eMgr != null) {
fireRuntimeQueueChangeEvent(new RuntimeQueueChangeEvent(eMgr));
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeConnectedStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeConnectedStateEvent)
*/
public void handleEvent(IProxyRuntimeConnectedStateEvent e) {
fireRuntimeConnectedStateEvent(new RuntimeConnectedStateEvent());
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeEventListener#handleProxyRuntimeRemoveAllEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveAllEvent)
*/
public void handleEvent(IProxyRuntimeRemoveAllEvent e) {
fireRuntimeRemoveAllEvent(new RuntimeRemoveAllEvent());
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveJobEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveJobEvent)
*/
public void handleEvent(IProxyRuntimeRemoveJobEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
fireRuntimeRemoveJobEvent(new RuntimeRemoveJobEvent(new RangeSet(attrs[0])));
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveMachineEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveMachineEvent)
*/
public void handleEvent(IProxyRuntimeRemoveMachineEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
fireRuntimeRemoveMachineEvent(new RuntimeRemoveMachineEvent(new RangeSet(attrs[0])));
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveNodeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveNodeEvent)
*/
public void handleEvent(IProxyRuntimeRemoveNodeEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
fireRuntimeRemoveNodeEvent(new RuntimeRemoveNodeEvent(new RangeSet(attrs[0])));
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveProcessEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveProcessEvent)
*/
public void handleEvent(IProxyRuntimeRemoveProcessEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
fireRuntimeRemoveProcessEvent(new RuntimeRemoveProcessEvent(new RangeSet(attrs[0])));
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveQueueEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveQueueEvent)
*/
public void handleEvent(IProxyRuntimeRemoveQueueEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length < 1) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments"));
return;
}
fireRuntimeRemoveQueueEvent(new RuntimeRemoveQueueEvent(new RangeSet(attrs[0])));
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRunningStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRunningStateEvent)
*/
public void handleEvent(IProxyRuntimeRunningStateEvent e) {
fireRuntimeRunningStateEvent(new RuntimeRunningStateEvent());
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeShutdownStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeShutdownStateEvent)
*/
public void handleEvent(IProxyRuntimeShutdownStateEvent e) {
fireRuntimeShutdownStateEvent(new RuntimeShutdownStateEvent());
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeStartupErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeStartupErrorEvent)
*/
public void handleEvent(
IProxyRuntimeStartupErrorEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length > 0) {
AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1);
IntegerAttribute codeAttr = mgr.getAttribute(ErrorAttributes.getCodeAttributeDefinition());
StringAttribute msgAttr = mgr.getAttribute(ErrorAttributes.getMsgAttributeDefinition());
if (codeAttr == null || msgAttr == null) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "StartupErrorEvent: missing attibutes"));
} else {
fireRuntimeStartupErrorEvent(new RuntimeStartupErrorEvent(codeAttr.getValue(), msgAttr.getValue()));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "StartupErrorEvent: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeSubmitJobErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeSubmitJobErrorEvent)
*/
public void handleEvent(
IProxyRuntimeSubmitJobErrorEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length > 0) {
AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1);
IntegerAttribute codeAttr = (IntegerAttribute) mgr.getAttribute(ErrorAttributes.getCodeAttributeDefinition());
StringAttribute msgAttr = (StringAttribute) mgr.getAttribute(ErrorAttributes.getMsgAttributeDefinition());
StringAttribute jobSubIdAttr = (StringAttribute) mgr.getAttribute(JobAttributes.getSubIdAttributeDefinition());
if (codeAttr == null || msgAttr == null || jobSubIdAttr == null) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "SubmitJobErrorEvent: missing attibutes"));
} else {
fireRuntimeSubmitJobErrorEvent(new RuntimeSubmitJobErrorEvent(codeAttr.getValue(), msgAttr.getValue(), jobSubIdAttr.getValue()));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "SubmitJobErrorEvent: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeTerminateJobErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeTerminateJobErrorEvent)
*/
public void handleEvent(
IProxyRuntimeTerminateJobErrorEvent e) {
String[] attrs = e.getAttributes();
if (attrs.length > 0) {
AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1);
IntegerAttribute codeAttr = (IntegerAttribute) mgr.getAttribute(ErrorAttributes.getCodeAttributeDefinition());
StringAttribute msgAttr = (StringAttribute) mgr.getAttribute(ErrorAttributes.getMsgAttributeDefinition());
StringAttribute jobIdAttr = (StringAttribute) mgr.getAttribute(ElementAttributes.getIdAttributeDefinition());
if (codeAttr == null || msgAttr == null || jobIdAttr == null) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "TerminateJobErrorEvent: missing attibutes"));
} else {
fireRuntimeTerminateJobErrorEvent(new RuntimeTerminateJobErrorEvent(codeAttr.getValue(), msgAttr.getValue(), jobIdAttr.getValue()));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "TerminateJobErrorEvent: could not parse message"));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.IRuntimeSystem#shutdown()
*/
public void shutdown() {
proxy.shutdown();
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.IRuntimeSystem#startup()
*/
public void startup() throws CoreException {
proxy.startup();
}
public String submitJob(AttributeManager attrMgr) throws CoreException {
try {
/*
* Add the job submission ID to the attributes. This is done here to force the
* use of the ID.
*/
String id = getJobSubmissionID();
StringAttribute jobSubAttr = JobAttributes.getSubIdAttributeDefinition().create(id);
attrMgr.addAttribute(jobSubAttr);
proxy.submitJob(attrMgr.toStringArray());
jobSubs.put(id, attrMgr);
return id;
} catch(IOException e) {
throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR,
"Control system is shut down, proxy exception. The proxy may have crashed or been killed.", null));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.IControlSystem#terminateJob(org.eclipse.ptp.core.elements.IPJob)
*/
public void terminateJob(IPJob job) throws CoreException {
if(job == null) {
System.err.println("ERROR: Tried to abort a null job.");
return;
}
try {
proxy.terminateJob(job.getID());
} catch(IOException e) {
throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR,
"Control system is shut down, proxy exception. The proxy may have crashed or been killed.", null));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.IMonitoringSystem#startEvents()
*/
public void startEvents() throws CoreException {
try {
proxy.startEvents();
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR,
e.getMessage(), e));
}
}
/* (non-Javadoc)
* @see org.eclipse.ptp.rtsystem.IMonitoringSystem#stopEvents()
*/
public void stopEvents() throws CoreException {
try {
proxy.stopEvents();
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR,
e.getMessage(), e));
}
}
/**
* @param kvs
* @param start
* @param end
* @return
*/
private AttributeManager getAttributeManager(String[] kvs, int start, int end) {
AttributeManager mgr = new AttributeManager();
for (int i = start; i <= end; i++) {
String[] kv = kvs[i].split("=");
if (kv.length == 2) {
try {
IAttributeDefinition<?,?,?> attrDef = attrDefManager.getAttributeDefinition(kv[0]);
if(attrDef != null) {
IAttribute<?,?,?> attr = attrDef.create(kv[1]);
mgr.addAttribute(attr);
} else {
System.out.println("AbstractProxyRuntimSystem: unknown attribute definition");
}
} catch (IllegalValueException e1) {
System.out.println("AbstractProxyRuntimSystem: invalid attribute for definition");
}
}
}
return mgr;
}
/**
* @param attrs
* @param pos
* @return
*/
private ElementAttributeManager getElementAttributeManager(String[] attrs, int pos) {
ElementAttributeManager eMgr = new ElementAttributeManager();
try {
int numRanges = Integer.parseInt(attrs[pos++]);
for (int i = 0; i < numRanges; i++) {
if (pos >= attrs.length) {
return null;
}
RangeSet ids = new RangeSet(attrs[pos++]);
int numAttrs = Integer.parseInt(attrs[pos++]);
int start = pos;
int end = pos + numAttrs - 1;
if (end >= attrs.length) {
return null;
}
eMgr.setAttributeManager(ids, getAttributeManager(attrs, start, end));
pos = end + 1;
}
} catch (NumberFormatException e1) {
return null;
}
return eMgr;
}
/**
* Parse and extract an attribute definition.
*
* On entry, we know that end < attrs.length and end - start >= ATTR_MIN_LEN
*
*/
private IAttributeDefinition<?,?,?> parseAttributeDefinition(String[] attrs, int start, int end) {
int pos = start;
IAttributeDefinition<?,?,?> attrDef = null;
String attrId = attrs[pos++];
String attrType = attrs[pos++];
String attrName = attrs[pos++];
String attrDesc = attrs[pos++];
String attrDefault = attrs[pos++];
if (attrType.equals("BOOLEAN")) {
try {
Boolean defVal = Boolean.parseBoolean(attrDefault);
attrDef = attrDefManager.createBooleanAttributeDefinition(attrId, attrName, attrDesc, defVal);
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attrs to double"));
}
} else if (attrType.equals("DATE")) {
- if (end - pos >= 2) {
+ if (end - pos > 2) {
try {
int dateStyle = toDateStyle(attrs[pos++]);
int timeStyle = toDateStyle(attrs[pos++]);
Locale locale = toLocale(attrs[pos++]);
DateFormat fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
Date defVal = fmt.parse(attrDefault);
- if (end - pos >= 1) {
+ if (end - pos > 1) {
Date min = fmt.parse(attrs[pos++]);
Date max = fmt.parse(attrs[pos++]);
attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, defVal, fmt, min, max);
} else {
attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, defVal, fmt);
}
} catch (ParseException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not parse date"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: missing date format"));
}
} else if (attrType.equals("DOUBLE")) {
try {
Double defVal = Double.parseDouble(attrDefault);
- if (end - pos >= 1) {
+ if (end - pos > 1) {
Double min = Double.parseDouble(attrs[pos++]);
Double max = Double.parseDouble(attrs[pos++]);
attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, defVal, min, max);
} else {
attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, defVal);
}
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to double"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("ENUMERATED")) {
- if (pos != end) {
- ArrayList<String> values = new ArrayList<String>();
- while (pos < end) {
- values.add(attrs[pos++]);
- }
- try {
- attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName,
- attrDesc, attrDefault, values.toArray(new String[values.size()]));
- } catch (IllegalValueException ex) {
- fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
- }
- } else {
- fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: no enumerated values"));
+ ArrayList<String> values = new ArrayList<String>();
+ while (pos <= end) {
+ values.add(attrs[pos++]);
+ }
+ try {
+ attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName,
+ attrDesc, attrDefault, values.toArray(new String[values.size()]));
+ } catch (IllegalValueException ex) {
+ fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("INTEGER")) {
try {
Integer defVal = Integer.parseInt(attrDefault);
- if (end - pos >= 1) {
+ if (end - pos > 1) {
Integer min = Integer.parseInt(attrs[pos++]);
Integer max = Integer.parseInt(attrs[pos++]);
attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, defVal, min, max);
} else {
attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, defVal);
}
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to integer"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("STRING")) {
attrDef = attrDefManager.createStringAttributeDefinition(attrId, attrName, attrDesc, attrDefault);
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: unknown attribute type"));
}
return attrDef;
}
/**
* @param val
* @return
*/
private int toDateStyle(String val) {
if (val.equals("SHORT")) {
return DateFormat.SHORT;
} else if (val.equals("MEDIUM")) {
return DateFormat.MEDIUM;
} else if (val.equals("LONG")) {
return DateFormat.LONG;
} else if (val.equals("FULL")) {
return DateFormat.FULL;
} else {
return DateFormat.DEFAULT;
}
}
/**
* @param val
* @return
*/
private Locale toLocale(String val) {
if (val.equals("CANADA")) {
return Locale.CANADA;
} else if (val.equals("CHINA")) {
return Locale.CHINA;
} else if (val.equals("FRANCE")) {
return Locale.FRANCE;
} else if (val.equals("GERMANY")) {
return Locale.GERMANY;
} else if (val.equals("ITALY")) {
return Locale.ITALY;
} else if (val.equals("JAPAN")) {
return Locale.JAPAN;
} else if (val.equals("TAIWAN")) {
return Locale.TAIWAN;
} else if (val.equals("UK")) {
return Locale.UK;
} else if (val.equals("US")) {
return Locale.US;
} else {
return Locale.US;
}
}
private String getJobSubmissionID() {
long time = System.currentTimeMillis();
return "JOB_" + Long.toString(time) + Integer.toString(jobSubIdCount++);
}
}
| false | true | private IAttributeDefinition<?,?,?> parseAttributeDefinition(String[] attrs, int start, int end) {
int pos = start;
IAttributeDefinition<?,?,?> attrDef = null;
String attrId = attrs[pos++];
String attrType = attrs[pos++];
String attrName = attrs[pos++];
String attrDesc = attrs[pos++];
String attrDefault = attrs[pos++];
if (attrType.equals("BOOLEAN")) {
try {
Boolean defVal = Boolean.parseBoolean(attrDefault);
attrDef = attrDefManager.createBooleanAttributeDefinition(attrId, attrName, attrDesc, defVal);
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attrs to double"));
}
} else if (attrType.equals("DATE")) {
if (end - pos >= 2) {
try {
int dateStyle = toDateStyle(attrs[pos++]);
int timeStyle = toDateStyle(attrs[pos++]);
Locale locale = toLocale(attrs[pos++]);
DateFormat fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
Date defVal = fmt.parse(attrDefault);
if (end - pos >= 1) {
Date min = fmt.parse(attrs[pos++]);
Date max = fmt.parse(attrs[pos++]);
attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, defVal, fmt, min, max);
} else {
attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, defVal, fmt);
}
} catch (ParseException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not parse date"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: missing date format"));
}
} else if (attrType.equals("DOUBLE")) {
try {
Double defVal = Double.parseDouble(attrDefault);
if (end - pos >= 1) {
Double min = Double.parseDouble(attrs[pos++]);
Double max = Double.parseDouble(attrs[pos++]);
attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, defVal, min, max);
} else {
attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, defVal);
}
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to double"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("ENUMERATED")) {
if (pos != end) {
ArrayList<String> values = new ArrayList<String>();
while (pos < end) {
values.add(attrs[pos++]);
}
try {
attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName,
attrDesc, attrDefault, values.toArray(new String[values.size()]));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: no enumerated values"));
}
} else if (attrType.equals("INTEGER")) {
try {
Integer defVal = Integer.parseInt(attrDefault);
if (end - pos >= 1) {
Integer min = Integer.parseInt(attrs[pos++]);
Integer max = Integer.parseInt(attrs[pos++]);
attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, defVal, min, max);
} else {
attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, defVal);
}
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to integer"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("STRING")) {
attrDef = attrDefManager.createStringAttributeDefinition(attrId, attrName, attrDesc, attrDefault);
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: unknown attribute type"));
}
return attrDef;
}
| private IAttributeDefinition<?,?,?> parseAttributeDefinition(String[] attrs, int start, int end) {
int pos = start;
IAttributeDefinition<?,?,?> attrDef = null;
String attrId = attrs[pos++];
String attrType = attrs[pos++];
String attrName = attrs[pos++];
String attrDesc = attrs[pos++];
String attrDefault = attrs[pos++];
if (attrType.equals("BOOLEAN")) {
try {
Boolean defVal = Boolean.parseBoolean(attrDefault);
attrDef = attrDefManager.createBooleanAttributeDefinition(attrId, attrName, attrDesc, defVal);
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attrs to double"));
}
} else if (attrType.equals("DATE")) {
if (end - pos > 2) {
try {
int dateStyle = toDateStyle(attrs[pos++]);
int timeStyle = toDateStyle(attrs[pos++]);
Locale locale = toLocale(attrs[pos++]);
DateFormat fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
Date defVal = fmt.parse(attrDefault);
if (end - pos > 1) {
Date min = fmt.parse(attrs[pos++]);
Date max = fmt.parse(attrs[pos++]);
attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, defVal, fmt, min, max);
} else {
attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, defVal, fmt);
}
} catch (ParseException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not parse date"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: missing date format"));
}
} else if (attrType.equals("DOUBLE")) {
try {
Double defVal = Double.parseDouble(attrDefault);
if (end - pos > 1) {
Double min = Double.parseDouble(attrs[pos++]);
Double max = Double.parseDouble(attrs[pos++]);
attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, defVal, min, max);
} else {
attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, defVal);
}
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to double"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("ENUMERATED")) {
ArrayList<String> values = new ArrayList<String>();
while (pos <= end) {
values.add(attrs[pos++]);
}
try {
attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName,
attrDesc, attrDefault, values.toArray(new String[values.size()]));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("INTEGER")) {
try {
Integer defVal = Integer.parseInt(attrDefault);
if (end - pos > 1) {
Integer min = Integer.parseInt(attrs[pos++]);
Integer max = Integer.parseInt(attrs[pos++]);
attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, defVal, min, max);
} else {
attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, defVal);
}
} catch (NumberFormatException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to integer"));
} catch (IllegalValueException ex) {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition"));
}
} else if (attrType.equals("STRING")) {
attrDef = attrDefManager.createStringAttributeDefinition(attrId, attrName, attrDesc, attrDefault);
} else {
fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: unknown attribute type"));
}
return attrDef;
}
|
diff --git a/ps3mediaserver/net/pms/newgui/FoldTab.java b/ps3mediaserver/net/pms/newgui/FoldTab.java
index 4615a678..2a421a6a 100644
--- a/ps3mediaserver/net/pms/newgui/FoldTab.java
+++ b/ps3mediaserver/net/pms/newgui/FoldTab.java
@@ -1,574 +1,574 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* 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 net.pms.newgui;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.util.KeyedComboBoxModel;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
public class FoldTab {
public static final String ALL_DRIVES = Messages.getString("FoldTab.0"); //$NON-NLS-1$
private JList FList;
private DefaultListModel df;
private JCheckBox hidevideosettings ;
private JCheckBox hideextensions ;
private JCheckBox hideengines ;
private JButton but5;
private JTextField seekpos;
private JCheckBox tncheckBox;
private JCheckBox mplayer_thumb;
//private JCheckBox disablefakesize;
private JCheckBox cacheenable;
private JCheckBox archive;
private JComboBox sortmethod;
private JComboBox audiothumbnail;
private JTextField defaultThumbFolder;
private JCheckBox iphoto;
private JCheckBox itunes;
public DefaultListModel getDf() {
return df;
}
private final PmsConfiguration configuration;
FoldTab(PmsConfiguration configuration) {
this.configuration = configuration;
}
private void updateModel() {
if (df.size() == 1 && df.getElementAt(0).equals(ALL_DRIVES)) {
PMS.getConfiguration().setFolders(""); //$NON-NLS-1$
} else {
StringBuffer sb = new StringBuffer();
for(int i=0;i<df.size();i++) {
if (i> 0)
sb.append(","); //$NON-NLS-1$
sb.append(df.getElementAt(i));
}
PMS.getConfiguration().setFolders(sb.toString());
}
PMS.get().getFrame().setReloadable(true);
}
public JComponent build() {
FormLayout layout = new FormLayout(
"left:pref, 50dlu, pref, 150dlu, pref, 25dlu, pref, 0:grow", //$NON-NLS-1$
"p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 15dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 15dlu, fill:default:grow"); //$NON-NLS-1$
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
df = new DefaultListModel();
if (PMS.getConfiguration().getFolders() != null && PMS.getConfiguration().getFolders().length() > 0) {
try {
File f [] = PMS.get().loadFoldersConf(PMS.getConfiguration().getFolders());
for(File file:f) {
df.addElement(file.getAbsolutePath());
}
if (f == null || f.length == 0) {
df.addElement(ALL_DRIVES);
}
} catch (IOException e1) {
PMS.error(null, e1);
}
} else
df.addElement(ALL_DRIVES);
FList = new JList();
FList.setModel(df);
JScrollPane pane = new JScrollPane(FList);
JComponent cmp = builder.addSeparator(Messages.getString("FoldTab.13"), cc.xyw(1, 1, 8)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
tncheckBox = new JCheckBox(Messages.getString("NetworkTab.2")); //$NON-NLS-1$
tncheckBox.setContentAreaFilled(false);
tncheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setThumbnailsEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (PMS.getConfiguration().getThumbnailsEnabled())
tncheckBox.setSelected(true);
builder.add(tncheckBox, cc.xyw(1, 3, 3));
seekpos = new JTextField("" + configuration.getThumbnailSeekPos()); //$NON-NLS-1$
seekpos.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(seekpos.getText());
configuration.setThumbnailSeekPos(ab);
} catch (NumberFormatException nfe) {
}
}
});
builder.addLabel(Messages.getString("NetworkTab.16"), cc.xyw(4, 3, 3)); //$NON-NLS-1$
builder.add(seekpos, cc.xyw(6, 3, 2));
mplayer_thumb = new JCheckBox(Messages.getString("FoldTab.14")); //$NON-NLS-1$
mplayer_thumb.setContentAreaFilled(false);
mplayer_thumb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setUseMplayerForVideoThumbs((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (PMS.getConfiguration().isUseMplayerForVideoThumbs())
mplayer_thumb.setSelected(true);
builder.add(mplayer_thumb, cc.xyw(1, 5, 5));
final KeyedComboBoxModel thumbKCBM = new KeyedComboBoxModel(new Object[] { "0", "1", "2" }, new Object[] { Messages.getString("FoldTab.15"), Messages.getString("FoldTab.23"), Messages.getString("FoldTab.24") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
audiothumbnail = new JComboBox(thumbKCBM);
audiothumbnail.setEditable(false);
thumbKCBM.setSelectedKey("" + configuration.getAudioThumbnailMethod()); //$NON-NLS-1$
audiothumbnail.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setAudioThumbnailMethod(Integer.parseInt((String) thumbKCBM.getSelectedKey()));
PMS.get().getFrame().setReloadable(true);
} catch (NumberFormatException nfe) {}
}
}
});
builder.addLabel(Messages.getString("FoldTab.26"), cc.xyw(1,7,3)); //$NON-NLS-1$
builder.add(audiothumbnail, cc.xyw(4, 7,4));
builder.addLabel(Messages.getString("FoldTab.27"), cc.xyw(1, 9, 3)); //$NON-NLS-1$
defaultThumbFolder = new JTextField(configuration.getAlternateThumbFolder());
defaultThumbFolder.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateThumbFolder(defaultThumbFolder.getText());
}
});
builder.add(defaultThumbFolder, cc.xyw(4, 9, 3));
JButton select = new JButton("..."); //$NON-NLS-1$
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28")); //$NON-NLS-1$
if(returnVal == JFileChooser.APPROVE_OPTION) {
defaultThumbFolder.setText(chooser.getSelectedFile().getAbsolutePath());
PMS.get().getFrame().setReloadable(true);
configuration.setAlternateThumbFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(select, cc.xyw(7, 9, 1));
cmp = builder.addSeparator(Messages.getString("NetworkTab.15"), cc.xyw(1, 11, 8)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
hidevideosettings = new JCheckBox(Messages.getString("FoldTab.6")); //$NON-NLS-1$
hidevideosettings.setContentAreaFilled(false);
if (PMS.getConfiguration().getHideVideoSettings())
hidevideosettings.setSelected(true);
hidevideosettings.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideVideoSettings((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
archive = new JCheckBox(Messages.getString("NetworkTab.1")); //$NON-NLS-1$
archive.setContentAreaFilled(false);
archive.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setArchiveBrowsing(e.getStateChange() == ItemEvent.SELECTED);
if (PMS.get().getFrame() != null)
PMS.get().getFrame().setReloadable(true);
}
});
if (PMS.getConfiguration().isArchiveBrowsing())
archive.setSelected(true);
builder.add(archive, cc.xyw(1, 13, 3));
/*disablefakesize = new JCheckBox(Messages.getString("FoldTab.11")); //$NON-NLS-1$
disablefakesize.setContentAreaFilled(false);
if (PMS.getConfiguration().isDisableFakeSize())
disablefakesize.setSelected(true);
disablefakesize.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setDisableFakeSize((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(disablefakesize, cc.xyw(1, 7, 7));
*/
final JButton cachereset = new JButton(Messages.getString("NetworkTab.18")); //$NON-NLS-1$
cacheenable = new JCheckBox(Messages.getString("NetworkTab.17")); //$NON-NLS-1$
cacheenable.setContentAreaFilled(false);
cacheenable.setSelected(PMS.getConfiguration().getUseCache());
cacheenable.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setUseCache((e.getStateChange() == ItemEvent.SELECTED));
cachereset.setEnabled(PMS.getConfiguration().getUseCache());
PMS.get().getFrame().setReloadable(true);
if ((LooksFrame) PMS.get().getFrame() != null)
((LooksFrame) PMS.get().getFrame()).getFt().setScanLibraryEnabled(PMS.getConfiguration().getUseCache());
}
});
//cacheenable.setEnabled(false);
builder.add(cacheenable, cc.xy(1, 19));
cachereset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("NetworkTab.13") + //$NON-NLS-1$
Messages.getString("NetworkTab.19"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().init(true);
}
}
});
builder.add(cachereset, cc.xyw(4, 19, 4));
cachereset.setEnabled(PMS.getConfiguration().getUseCache());
builder.add(hidevideosettings, cc.xyw(4, 13, 3));
hideextensions = new JCheckBox(Messages.getString("FoldTab.5")); //$NON-NLS-1$
hideextensions.setContentAreaFilled(false);
if (PMS.getConfiguration().isHideExtensions())
hideextensions.setSelected(true);
hideextensions.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideExtensions((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(hideextensions, cc.xyw(1, 15, 3));
hideengines = new JCheckBox(Messages.getString("FoldTab.8")); //$NON-NLS-1$
hideengines.setContentAreaFilled(false);
if (PMS.getConfiguration().isHideEngineNames())
hideengines.setSelected(true);
hideengines.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideEngineNames((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(hideengines, cc.xyw(4, 15, 3));
itunes = new JCheckBox(Messages.getString("FoldTab.30")); //$NON-NLS-1$
itunes.setContentAreaFilled(false);
if (PMS.getConfiguration().getItunesEnabled())
itunes.setSelected(true);
if (!Platform.isMac())
- iphoto.setEnabled(false);
+ itunes.setEnabled(false);
itunes.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setItunesEnabled((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(itunes, cc.xyw(1, 17, 3));
iphoto = new JCheckBox(Messages.getString("FoldTab.29")); //$NON-NLS-1$
iphoto.setContentAreaFilled(false);
if (PMS.getConfiguration().getIphotoEnabled())
iphoto.setSelected(true);
if (!Platform.isMac())
iphoto.setEnabled(false);
iphoto.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setIphotoEnabled((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(iphoto, cc.xyw(4, 17, 3));
final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(new Object[] { "0", "1" }, new Object[] { Messages.getString("FoldTab.15"), Messages.getString("FoldTab.16") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
sortmethod = new JComboBox(kcbm);
sortmethod.setEditable(false);
kcbm.setSelectedKey("" + configuration.getSortMethod()); //$NON-NLS-1$
sortmethod.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setSortMethod(Integer.parseInt((String) kcbm.getSelectedKey()));
PMS.get().getFrame().setReloadable(true);
} catch (NumberFormatException nfe) {}
}
}
});
builder.addLabel(Messages.getString("FoldTab.18"), cc.xyw(1,21,3)); //$NON-NLS-1$
builder.add(sortmethod, cc.xyw(4, 21,4));
FormLayout layoutFolders = new FormLayout(
"left:pref, left:pref, pref, pref, pref, 0:grow", //$NON-NLS-1$
"p, 3dlu, p, 3dlu, fill:default:grow"); //$NON-NLS-1$
PanelBuilder builderFolder = new PanelBuilder(layoutFolders);
builderFolder.setOpaque(true);
cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"), cc.xyw(1, 1,6)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
JButton but = new JButton(LooksFrame.readImageIcon("folder_new-32.png")); //$NON-NLS-1$
//but.setBorder(BorderFactory.createEmptyBorder());
but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.9")); //$NON-NLS-1$
int returnVal = chooser.showOpenDialog((Component) e.getSource());
if(returnVal == JFileChooser.APPROVE_OPTION) {
((DefaultListModel) FList.getModel()).add(FList.getModel().getSize(),chooser.getSelectedFile().getAbsolutePath());
if (FList.getModel().getElementAt(0).equals(ALL_DRIVES))
((DefaultListModel) FList.getModel()).remove(0);
updateModel();
}
}
});
builderFolder.add(but, cc.xy(1, 3));
JButton but2 = new JButton(LooksFrame.readImageIcon("button_cancel-32.png")); //$NON-NLS-1$
//but2.setBorder(BorderFactory.createEtchedBorder());
but2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (FList.getSelectedIndex() > -1) {
((DefaultListModel) FList.getModel()).remove(FList.getSelectedIndex());
if (FList.getModel().getSize() == 0)
((DefaultListModel) FList.getModel()).add(0, ALL_DRIVES);
updateModel();
}
}
});
builderFolder.add(but2, cc.xy(2, 3));
JButton but3 = new JButton(LooksFrame.readImageIcon("kdevelop_down-32.png")); //$NON-NLS-1$
but3.setToolTipText(Messages.getString("FoldTab.12")); //$NON-NLS-1$
// but3.setBorder(BorderFactory.createEmptyBorder());
but3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for(int i=0;i<model.size()-1;i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i+1));
model.set(i+1, value);
FList.setSelectedIndex(i+1);
updateModel();
break;
}
}
}
});
builderFolder.add(but3, cc.xy(3, 3));
JButton but4 = new JButton(LooksFrame.readImageIcon("up-32.png")); //$NON-NLS-1$
but4.setToolTipText(Messages.getString("FoldTab.12")); //$NON-NLS-1$
// but4.setBorder(BorderFactory.createEmptyBorder());
but4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for(int i=1;i<model.size();i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i-1));
model.set(i-1, value);
FList.setSelectedIndex(i-1);
updateModel();
break;
}
}
}
});
builderFolder.add(but4, cc.xy(4, 3));
but5 = new JButton(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
but5.setToolTipText(Messages.getString("FoldTab.2")); //$NON-NLS-1$
//but5.setBorder(BorderFactory.createEmptyBorder());
but5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (PMS.getConfiguration().getUseCache()) {
if (!PMS.get().getDatabase().isScanLibraryRunning()) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.3") + //$NON-NLS-1$
Messages.getString("FoldTab.4"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().scanLibrary();
but5.setIcon(LooksFrame.readImageIcon("viewmagfit-32.png")); //$NON-NLS-1$
}
} else {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.10"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().stopScanLibrary();
PMS.get().getFrame().setStatusLine(null);
but5.setIcon(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
}
}
}
}
});
builderFolder.add(but5, cc.xy(5, 3));
but5.setEnabled(PMS.getConfiguration().getUseCache());
builderFolder.add(pane, cc.xyw(1, 5,6));
builder.add(builderFolder.getPanel(), cc.xyw(1, 25, 8));
return builder.getPanel();
}
public void setScanLibraryEnabled(boolean enabled) {
but5.setEnabled(enabled);
but5.setIcon(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
}
}
| true | true | public JComponent build() {
FormLayout layout = new FormLayout(
"left:pref, 50dlu, pref, 150dlu, pref, 25dlu, pref, 0:grow", //$NON-NLS-1$
"p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 15dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 15dlu, fill:default:grow"); //$NON-NLS-1$
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
df = new DefaultListModel();
if (PMS.getConfiguration().getFolders() != null && PMS.getConfiguration().getFolders().length() > 0) {
try {
File f [] = PMS.get().loadFoldersConf(PMS.getConfiguration().getFolders());
for(File file:f) {
df.addElement(file.getAbsolutePath());
}
if (f == null || f.length == 0) {
df.addElement(ALL_DRIVES);
}
} catch (IOException e1) {
PMS.error(null, e1);
}
} else
df.addElement(ALL_DRIVES);
FList = new JList();
FList.setModel(df);
JScrollPane pane = new JScrollPane(FList);
JComponent cmp = builder.addSeparator(Messages.getString("FoldTab.13"), cc.xyw(1, 1, 8)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
tncheckBox = new JCheckBox(Messages.getString("NetworkTab.2")); //$NON-NLS-1$
tncheckBox.setContentAreaFilled(false);
tncheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setThumbnailsEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (PMS.getConfiguration().getThumbnailsEnabled())
tncheckBox.setSelected(true);
builder.add(tncheckBox, cc.xyw(1, 3, 3));
seekpos = new JTextField("" + configuration.getThumbnailSeekPos()); //$NON-NLS-1$
seekpos.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(seekpos.getText());
configuration.setThumbnailSeekPos(ab);
} catch (NumberFormatException nfe) {
}
}
});
builder.addLabel(Messages.getString("NetworkTab.16"), cc.xyw(4, 3, 3)); //$NON-NLS-1$
builder.add(seekpos, cc.xyw(6, 3, 2));
mplayer_thumb = new JCheckBox(Messages.getString("FoldTab.14")); //$NON-NLS-1$
mplayer_thumb.setContentAreaFilled(false);
mplayer_thumb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setUseMplayerForVideoThumbs((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (PMS.getConfiguration().isUseMplayerForVideoThumbs())
mplayer_thumb.setSelected(true);
builder.add(mplayer_thumb, cc.xyw(1, 5, 5));
final KeyedComboBoxModel thumbKCBM = new KeyedComboBoxModel(new Object[] { "0", "1", "2" }, new Object[] { Messages.getString("FoldTab.15"), Messages.getString("FoldTab.23"), Messages.getString("FoldTab.24") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
audiothumbnail = new JComboBox(thumbKCBM);
audiothumbnail.setEditable(false);
thumbKCBM.setSelectedKey("" + configuration.getAudioThumbnailMethod()); //$NON-NLS-1$
audiothumbnail.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setAudioThumbnailMethod(Integer.parseInt((String) thumbKCBM.getSelectedKey()));
PMS.get().getFrame().setReloadable(true);
} catch (NumberFormatException nfe) {}
}
}
});
builder.addLabel(Messages.getString("FoldTab.26"), cc.xyw(1,7,3)); //$NON-NLS-1$
builder.add(audiothumbnail, cc.xyw(4, 7,4));
builder.addLabel(Messages.getString("FoldTab.27"), cc.xyw(1, 9, 3)); //$NON-NLS-1$
defaultThumbFolder = new JTextField(configuration.getAlternateThumbFolder());
defaultThumbFolder.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateThumbFolder(defaultThumbFolder.getText());
}
});
builder.add(defaultThumbFolder, cc.xyw(4, 9, 3));
JButton select = new JButton("..."); //$NON-NLS-1$
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28")); //$NON-NLS-1$
if(returnVal == JFileChooser.APPROVE_OPTION) {
defaultThumbFolder.setText(chooser.getSelectedFile().getAbsolutePath());
PMS.get().getFrame().setReloadable(true);
configuration.setAlternateThumbFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(select, cc.xyw(7, 9, 1));
cmp = builder.addSeparator(Messages.getString("NetworkTab.15"), cc.xyw(1, 11, 8)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
hidevideosettings = new JCheckBox(Messages.getString("FoldTab.6")); //$NON-NLS-1$
hidevideosettings.setContentAreaFilled(false);
if (PMS.getConfiguration().getHideVideoSettings())
hidevideosettings.setSelected(true);
hidevideosettings.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideVideoSettings((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
archive = new JCheckBox(Messages.getString("NetworkTab.1")); //$NON-NLS-1$
archive.setContentAreaFilled(false);
archive.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setArchiveBrowsing(e.getStateChange() == ItemEvent.SELECTED);
if (PMS.get().getFrame() != null)
PMS.get().getFrame().setReloadable(true);
}
});
if (PMS.getConfiguration().isArchiveBrowsing())
archive.setSelected(true);
builder.add(archive, cc.xyw(1, 13, 3));
/*disablefakesize = new JCheckBox(Messages.getString("FoldTab.11")); //$NON-NLS-1$
disablefakesize.setContentAreaFilled(false);
if (PMS.getConfiguration().isDisableFakeSize())
disablefakesize.setSelected(true);
disablefakesize.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setDisableFakeSize((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(disablefakesize, cc.xyw(1, 7, 7));
*/
final JButton cachereset = new JButton(Messages.getString("NetworkTab.18")); //$NON-NLS-1$
cacheenable = new JCheckBox(Messages.getString("NetworkTab.17")); //$NON-NLS-1$
cacheenable.setContentAreaFilled(false);
cacheenable.setSelected(PMS.getConfiguration().getUseCache());
cacheenable.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setUseCache((e.getStateChange() == ItemEvent.SELECTED));
cachereset.setEnabled(PMS.getConfiguration().getUseCache());
PMS.get().getFrame().setReloadable(true);
if ((LooksFrame) PMS.get().getFrame() != null)
((LooksFrame) PMS.get().getFrame()).getFt().setScanLibraryEnabled(PMS.getConfiguration().getUseCache());
}
});
//cacheenable.setEnabled(false);
builder.add(cacheenable, cc.xy(1, 19));
cachereset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("NetworkTab.13") + //$NON-NLS-1$
Messages.getString("NetworkTab.19"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().init(true);
}
}
});
builder.add(cachereset, cc.xyw(4, 19, 4));
cachereset.setEnabled(PMS.getConfiguration().getUseCache());
builder.add(hidevideosettings, cc.xyw(4, 13, 3));
hideextensions = new JCheckBox(Messages.getString("FoldTab.5")); //$NON-NLS-1$
hideextensions.setContentAreaFilled(false);
if (PMS.getConfiguration().isHideExtensions())
hideextensions.setSelected(true);
hideextensions.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideExtensions((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(hideextensions, cc.xyw(1, 15, 3));
hideengines = new JCheckBox(Messages.getString("FoldTab.8")); //$NON-NLS-1$
hideengines.setContentAreaFilled(false);
if (PMS.getConfiguration().isHideEngineNames())
hideengines.setSelected(true);
hideengines.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideEngineNames((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(hideengines, cc.xyw(4, 15, 3));
itunes = new JCheckBox(Messages.getString("FoldTab.30")); //$NON-NLS-1$
itunes.setContentAreaFilled(false);
if (PMS.getConfiguration().getItunesEnabled())
itunes.setSelected(true);
if (!Platform.isMac())
iphoto.setEnabled(false);
itunes.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setItunesEnabled((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(itunes, cc.xyw(1, 17, 3));
iphoto = new JCheckBox(Messages.getString("FoldTab.29")); //$NON-NLS-1$
iphoto.setContentAreaFilled(false);
if (PMS.getConfiguration().getIphotoEnabled())
iphoto.setSelected(true);
if (!Platform.isMac())
iphoto.setEnabled(false);
iphoto.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setIphotoEnabled((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(iphoto, cc.xyw(4, 17, 3));
final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(new Object[] { "0", "1" }, new Object[] { Messages.getString("FoldTab.15"), Messages.getString("FoldTab.16") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
sortmethod = new JComboBox(kcbm);
sortmethod.setEditable(false);
kcbm.setSelectedKey("" + configuration.getSortMethod()); //$NON-NLS-1$
sortmethod.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setSortMethod(Integer.parseInt((String) kcbm.getSelectedKey()));
PMS.get().getFrame().setReloadable(true);
} catch (NumberFormatException nfe) {}
}
}
});
builder.addLabel(Messages.getString("FoldTab.18"), cc.xyw(1,21,3)); //$NON-NLS-1$
builder.add(sortmethod, cc.xyw(4, 21,4));
FormLayout layoutFolders = new FormLayout(
"left:pref, left:pref, pref, pref, pref, 0:grow", //$NON-NLS-1$
"p, 3dlu, p, 3dlu, fill:default:grow"); //$NON-NLS-1$
PanelBuilder builderFolder = new PanelBuilder(layoutFolders);
builderFolder.setOpaque(true);
cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"), cc.xyw(1, 1,6)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
JButton but = new JButton(LooksFrame.readImageIcon("folder_new-32.png")); //$NON-NLS-1$
//but.setBorder(BorderFactory.createEmptyBorder());
but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.9")); //$NON-NLS-1$
int returnVal = chooser.showOpenDialog((Component) e.getSource());
if(returnVal == JFileChooser.APPROVE_OPTION) {
((DefaultListModel) FList.getModel()).add(FList.getModel().getSize(),chooser.getSelectedFile().getAbsolutePath());
if (FList.getModel().getElementAt(0).equals(ALL_DRIVES))
((DefaultListModel) FList.getModel()).remove(0);
updateModel();
}
}
});
builderFolder.add(but, cc.xy(1, 3));
JButton but2 = new JButton(LooksFrame.readImageIcon("button_cancel-32.png")); //$NON-NLS-1$
//but2.setBorder(BorderFactory.createEtchedBorder());
but2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (FList.getSelectedIndex() > -1) {
((DefaultListModel) FList.getModel()).remove(FList.getSelectedIndex());
if (FList.getModel().getSize() == 0)
((DefaultListModel) FList.getModel()).add(0, ALL_DRIVES);
updateModel();
}
}
});
builderFolder.add(but2, cc.xy(2, 3));
JButton but3 = new JButton(LooksFrame.readImageIcon("kdevelop_down-32.png")); //$NON-NLS-1$
but3.setToolTipText(Messages.getString("FoldTab.12")); //$NON-NLS-1$
// but3.setBorder(BorderFactory.createEmptyBorder());
but3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for(int i=0;i<model.size()-1;i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i+1));
model.set(i+1, value);
FList.setSelectedIndex(i+1);
updateModel();
break;
}
}
}
});
builderFolder.add(but3, cc.xy(3, 3));
JButton but4 = new JButton(LooksFrame.readImageIcon("up-32.png")); //$NON-NLS-1$
but4.setToolTipText(Messages.getString("FoldTab.12")); //$NON-NLS-1$
// but4.setBorder(BorderFactory.createEmptyBorder());
but4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for(int i=1;i<model.size();i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i-1));
model.set(i-1, value);
FList.setSelectedIndex(i-1);
updateModel();
break;
}
}
}
});
builderFolder.add(but4, cc.xy(4, 3));
but5 = new JButton(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
but5.setToolTipText(Messages.getString("FoldTab.2")); //$NON-NLS-1$
//but5.setBorder(BorderFactory.createEmptyBorder());
but5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (PMS.getConfiguration().getUseCache()) {
if (!PMS.get().getDatabase().isScanLibraryRunning()) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.3") + //$NON-NLS-1$
Messages.getString("FoldTab.4"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().scanLibrary();
but5.setIcon(LooksFrame.readImageIcon("viewmagfit-32.png")); //$NON-NLS-1$
}
} else {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.10"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().stopScanLibrary();
PMS.get().getFrame().setStatusLine(null);
but5.setIcon(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
}
}
}
}
});
builderFolder.add(but5, cc.xy(5, 3));
but5.setEnabled(PMS.getConfiguration().getUseCache());
builderFolder.add(pane, cc.xyw(1, 5,6));
builder.add(builderFolder.getPanel(), cc.xyw(1, 25, 8));
return builder.getPanel();
}
| public JComponent build() {
FormLayout layout = new FormLayout(
"left:pref, 50dlu, pref, 150dlu, pref, 25dlu, pref, 0:grow", //$NON-NLS-1$
"p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 15dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 15dlu, fill:default:grow"); //$NON-NLS-1$
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
df = new DefaultListModel();
if (PMS.getConfiguration().getFolders() != null && PMS.getConfiguration().getFolders().length() > 0) {
try {
File f [] = PMS.get().loadFoldersConf(PMS.getConfiguration().getFolders());
for(File file:f) {
df.addElement(file.getAbsolutePath());
}
if (f == null || f.length == 0) {
df.addElement(ALL_DRIVES);
}
} catch (IOException e1) {
PMS.error(null, e1);
}
} else
df.addElement(ALL_DRIVES);
FList = new JList();
FList.setModel(df);
JScrollPane pane = new JScrollPane(FList);
JComponent cmp = builder.addSeparator(Messages.getString("FoldTab.13"), cc.xyw(1, 1, 8)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
tncheckBox = new JCheckBox(Messages.getString("NetworkTab.2")); //$NON-NLS-1$
tncheckBox.setContentAreaFilled(false);
tncheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setThumbnailsEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (PMS.getConfiguration().getThumbnailsEnabled())
tncheckBox.setSelected(true);
builder.add(tncheckBox, cc.xyw(1, 3, 3));
seekpos = new JTextField("" + configuration.getThumbnailSeekPos()); //$NON-NLS-1$
seekpos.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(seekpos.getText());
configuration.setThumbnailSeekPos(ab);
} catch (NumberFormatException nfe) {
}
}
});
builder.addLabel(Messages.getString("NetworkTab.16"), cc.xyw(4, 3, 3)); //$NON-NLS-1$
builder.add(seekpos, cc.xyw(6, 3, 2));
mplayer_thumb = new JCheckBox(Messages.getString("FoldTab.14")); //$NON-NLS-1$
mplayer_thumb.setContentAreaFilled(false);
mplayer_thumb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setUseMplayerForVideoThumbs((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (PMS.getConfiguration().isUseMplayerForVideoThumbs())
mplayer_thumb.setSelected(true);
builder.add(mplayer_thumb, cc.xyw(1, 5, 5));
final KeyedComboBoxModel thumbKCBM = new KeyedComboBoxModel(new Object[] { "0", "1", "2" }, new Object[] { Messages.getString("FoldTab.15"), Messages.getString("FoldTab.23"), Messages.getString("FoldTab.24") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
audiothumbnail = new JComboBox(thumbKCBM);
audiothumbnail.setEditable(false);
thumbKCBM.setSelectedKey("" + configuration.getAudioThumbnailMethod()); //$NON-NLS-1$
audiothumbnail.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setAudioThumbnailMethod(Integer.parseInt((String) thumbKCBM.getSelectedKey()));
PMS.get().getFrame().setReloadable(true);
} catch (NumberFormatException nfe) {}
}
}
});
builder.addLabel(Messages.getString("FoldTab.26"), cc.xyw(1,7,3)); //$NON-NLS-1$
builder.add(audiothumbnail, cc.xyw(4, 7,4));
builder.addLabel(Messages.getString("FoldTab.27"), cc.xyw(1, 9, 3)); //$NON-NLS-1$
defaultThumbFolder = new JTextField(configuration.getAlternateThumbFolder());
defaultThumbFolder.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateThumbFolder(defaultThumbFolder.getText());
}
});
builder.add(defaultThumbFolder, cc.xyw(4, 9, 3));
JButton select = new JButton("..."); //$NON-NLS-1$
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28")); //$NON-NLS-1$
if(returnVal == JFileChooser.APPROVE_OPTION) {
defaultThumbFolder.setText(chooser.getSelectedFile().getAbsolutePath());
PMS.get().getFrame().setReloadable(true);
configuration.setAlternateThumbFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(select, cc.xyw(7, 9, 1));
cmp = builder.addSeparator(Messages.getString("NetworkTab.15"), cc.xyw(1, 11, 8)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
hidevideosettings = new JCheckBox(Messages.getString("FoldTab.6")); //$NON-NLS-1$
hidevideosettings.setContentAreaFilled(false);
if (PMS.getConfiguration().getHideVideoSettings())
hidevideosettings.setSelected(true);
hidevideosettings.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideVideoSettings((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
archive = new JCheckBox(Messages.getString("NetworkTab.1")); //$NON-NLS-1$
archive.setContentAreaFilled(false);
archive.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setArchiveBrowsing(e.getStateChange() == ItemEvent.SELECTED);
if (PMS.get().getFrame() != null)
PMS.get().getFrame().setReloadable(true);
}
});
if (PMS.getConfiguration().isArchiveBrowsing())
archive.setSelected(true);
builder.add(archive, cc.xyw(1, 13, 3));
/*disablefakesize = new JCheckBox(Messages.getString("FoldTab.11")); //$NON-NLS-1$
disablefakesize.setContentAreaFilled(false);
if (PMS.getConfiguration().isDisableFakeSize())
disablefakesize.setSelected(true);
disablefakesize.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setDisableFakeSize((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(disablefakesize, cc.xyw(1, 7, 7));
*/
final JButton cachereset = new JButton(Messages.getString("NetworkTab.18")); //$NON-NLS-1$
cacheenable = new JCheckBox(Messages.getString("NetworkTab.17")); //$NON-NLS-1$
cacheenable.setContentAreaFilled(false);
cacheenable.setSelected(PMS.getConfiguration().getUseCache());
cacheenable.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setUseCache((e.getStateChange() == ItemEvent.SELECTED));
cachereset.setEnabled(PMS.getConfiguration().getUseCache());
PMS.get().getFrame().setReloadable(true);
if ((LooksFrame) PMS.get().getFrame() != null)
((LooksFrame) PMS.get().getFrame()).getFt().setScanLibraryEnabled(PMS.getConfiguration().getUseCache());
}
});
//cacheenable.setEnabled(false);
builder.add(cacheenable, cc.xy(1, 19));
cachereset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("NetworkTab.13") + //$NON-NLS-1$
Messages.getString("NetworkTab.19"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().init(true);
}
}
});
builder.add(cachereset, cc.xyw(4, 19, 4));
cachereset.setEnabled(PMS.getConfiguration().getUseCache());
builder.add(hidevideosettings, cc.xyw(4, 13, 3));
hideextensions = new JCheckBox(Messages.getString("FoldTab.5")); //$NON-NLS-1$
hideextensions.setContentAreaFilled(false);
if (PMS.getConfiguration().isHideExtensions())
hideextensions.setSelected(true);
hideextensions.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideExtensions((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(hideextensions, cc.xyw(1, 15, 3));
hideengines = new JCheckBox(Messages.getString("FoldTab.8")); //$NON-NLS-1$
hideengines.setContentAreaFilled(false);
if (PMS.getConfiguration().isHideEngineNames())
hideengines.setSelected(true);
hideengines.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setHideEngineNames((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(hideengines, cc.xyw(4, 15, 3));
itunes = new JCheckBox(Messages.getString("FoldTab.30")); //$NON-NLS-1$
itunes.setContentAreaFilled(false);
if (PMS.getConfiguration().getItunesEnabled())
itunes.setSelected(true);
if (!Platform.isMac())
itunes.setEnabled(false);
itunes.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setItunesEnabled((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(itunes, cc.xyw(1, 17, 3));
iphoto = new JCheckBox(Messages.getString("FoldTab.29")); //$NON-NLS-1$
iphoto.setContentAreaFilled(false);
if (PMS.getConfiguration().getIphotoEnabled())
iphoto.setSelected(true);
if (!Platform.isMac())
iphoto.setEnabled(false);
iphoto.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setIphotoEnabled((e.getStateChange() == ItemEvent.SELECTED));
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(iphoto, cc.xyw(4, 17, 3));
final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(new Object[] { "0", "1" }, new Object[] { Messages.getString("FoldTab.15"), Messages.getString("FoldTab.16") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
sortmethod = new JComboBox(kcbm);
sortmethod.setEditable(false);
kcbm.setSelectedKey("" + configuration.getSortMethod()); //$NON-NLS-1$
sortmethod.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setSortMethod(Integer.parseInt((String) kcbm.getSelectedKey()));
PMS.get().getFrame().setReloadable(true);
} catch (NumberFormatException nfe) {}
}
}
});
builder.addLabel(Messages.getString("FoldTab.18"), cc.xyw(1,21,3)); //$NON-NLS-1$
builder.add(sortmethod, cc.xyw(4, 21,4));
FormLayout layoutFolders = new FormLayout(
"left:pref, left:pref, pref, pref, pref, 0:grow", //$NON-NLS-1$
"p, 3dlu, p, 3dlu, fill:default:grow"); //$NON-NLS-1$
PanelBuilder builderFolder = new PanelBuilder(layoutFolders);
builderFolder.setOpaque(true);
cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"), cc.xyw(1, 1,6)); //$NON-NLS-1$
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
JButton but = new JButton(LooksFrame.readImageIcon("folder_new-32.png")); //$NON-NLS-1$
//but.setBorder(BorderFactory.createEmptyBorder());
but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.9")); //$NON-NLS-1$
int returnVal = chooser.showOpenDialog((Component) e.getSource());
if(returnVal == JFileChooser.APPROVE_OPTION) {
((DefaultListModel) FList.getModel()).add(FList.getModel().getSize(),chooser.getSelectedFile().getAbsolutePath());
if (FList.getModel().getElementAt(0).equals(ALL_DRIVES))
((DefaultListModel) FList.getModel()).remove(0);
updateModel();
}
}
});
builderFolder.add(but, cc.xy(1, 3));
JButton but2 = new JButton(LooksFrame.readImageIcon("button_cancel-32.png")); //$NON-NLS-1$
//but2.setBorder(BorderFactory.createEtchedBorder());
but2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (FList.getSelectedIndex() > -1) {
((DefaultListModel) FList.getModel()).remove(FList.getSelectedIndex());
if (FList.getModel().getSize() == 0)
((DefaultListModel) FList.getModel()).add(0, ALL_DRIVES);
updateModel();
}
}
});
builderFolder.add(but2, cc.xy(2, 3));
JButton but3 = new JButton(LooksFrame.readImageIcon("kdevelop_down-32.png")); //$NON-NLS-1$
but3.setToolTipText(Messages.getString("FoldTab.12")); //$NON-NLS-1$
// but3.setBorder(BorderFactory.createEmptyBorder());
but3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for(int i=0;i<model.size()-1;i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i+1));
model.set(i+1, value);
FList.setSelectedIndex(i+1);
updateModel();
break;
}
}
}
});
builderFolder.add(but3, cc.xy(3, 3));
JButton but4 = new JButton(LooksFrame.readImageIcon("up-32.png")); //$NON-NLS-1$
but4.setToolTipText(Messages.getString("FoldTab.12")); //$NON-NLS-1$
// but4.setBorder(BorderFactory.createEmptyBorder());
but4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for(int i=1;i<model.size();i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i-1));
model.set(i-1, value);
FList.setSelectedIndex(i-1);
updateModel();
break;
}
}
}
});
builderFolder.add(but4, cc.xy(4, 3));
but5 = new JButton(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
but5.setToolTipText(Messages.getString("FoldTab.2")); //$NON-NLS-1$
//but5.setBorder(BorderFactory.createEmptyBorder());
but5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (PMS.getConfiguration().getUseCache()) {
if (!PMS.get().getDatabase().isScanLibraryRunning()) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.3") + //$NON-NLS-1$
Messages.getString("FoldTab.4"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().scanLibrary();
but5.setIcon(LooksFrame.readImageIcon("viewmagfit-32.png")); //$NON-NLS-1$
}
} else {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.10"), //$NON-NLS-1$
"Question", //$NON-NLS-1$
JOptionPane.YES_NO_OPTION
);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().stopScanLibrary();
PMS.get().getFrame().setStatusLine(null);
but5.setIcon(LooksFrame.readImageIcon("search-32.png")); //$NON-NLS-1$
}
}
}
}
});
builderFolder.add(but5, cc.xy(5, 3));
but5.setEnabled(PMS.getConfiguration().getUseCache());
builderFolder.add(pane, cc.xyw(1, 5,6));
builder.add(builderFolder.getPanel(), cc.xyw(1, 25, 8));
return builder.getPanel();
}
|
diff --git a/GPSLogger/src/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java b/GPSLogger/src/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java
index 51afe6bd..e86cd33c 100644
--- a/GPSLogger/src/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java
+++ b/GPSLogger/src/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java
@@ -1,309 +1,309 @@
/*
* This file is part of GPSLogger for Android.
*
* GPSLogger for Android 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.
*
* GPSLogger for Android 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 GPSLogger for Android. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mendhak.gpslogger.loggers;
import android.location.Location;
import com.mendhak.gpslogger.common.RejectionHandler;
import com.mendhak.gpslogger.common.Utilities;
import java.io.*;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class Gpx10FileLogger implements IFileLogger
{
protected final static Object lock = new Object();
private final static ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(128), new RejectionHandler());
private File gpxFile = null;
private final boolean addNewTrackSegment;
private final int satelliteCount;
protected final String name = "GPX";
Gpx10FileLogger(File gpxFile, boolean addNewTrackSegment, int satelliteCount)
{
this.gpxFile = gpxFile;
this.addNewTrackSegment = addNewTrackSegment;
this.satelliteCount = satelliteCount;
}
public void Write(Location loc) throws Exception
{
String dateTimeString = Utilities.GetIsoDateTime(new Date(loc.getTime()));
Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(dateTimeString, gpxFile, loc, addNewTrackSegment, satelliteCount);
Utilities.LogDebug(String.format("There are currently %s tasks waiting on the GPX10 EXECUTOR.", EXECUTOR.getQueue().size()));
EXECUTOR.execute(writeHandler);
}
public void Annotate(String description, Location loc) throws Exception
{
String dateTimeString = Utilities.GetIsoDateTime(new Date(loc.getTime()));
Gpx10AnnotateHandler annotateHandler = new Gpx10AnnotateHandler(description, gpxFile, loc, dateTimeString);
Utilities.LogDebug(String.format("There are currently %s tasks waiting on the GPX10 EXECUTOR.", EXECUTOR.getQueue().size()));
EXECUTOR.execute(annotateHandler);
}
@Override
public String getName()
{
return name;
}
}
class Gpx10AnnotateHandler implements Runnable
{
String description;
File gpxFile;
Location loc;
String dateTimeString;
public Gpx10AnnotateHandler(String description, File gpxFile, Location loc, String dateTimeString)
{
this.description = description;
this.gpxFile = gpxFile;
this.loc = loc;
this.dateTimeString = dateTimeString;
}
@Override
public void run()
{
synchronized (Gpx10FileLogger.lock)
{
if (!gpxFile.exists())
{
return;
}
if (!gpxFile.exists())
{
return;
}
- int startPosition = 323;
+ int startPosition = 336;
String wpt = GetWaypointXml(loc, dateTimeString, description);
try
{
//Write to a temp file, delete original file, move temp to original
File gpxTempFile = new File(gpxFile.getAbsolutePath() + ".tmp");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(gpxFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(gpxTempFile));
int written = 0;
int readSize;
byte[] buffer = new byte[startPosition];
while ((readSize = bis.read(buffer)) > 0)
{
bos.write(buffer, 0, readSize);
written += readSize;
System.out.println(written);
if (written == startPosition)
{
bos.write(wpt.getBytes());
buffer = new byte[20480];
}
}
bis.close();
bos.close();
gpxFile.delete();
gpxTempFile.renameTo(gpxFile);
Utilities.LogDebug("Finished annotation to GPX10 File");
}
catch (Exception e)
{
Utilities.LogError("Gpx10FileLogger.Annotate", e);
}
}
}
private String GetWaypointXml(Location loc, String dateTimeString, String description)
{
StringBuilder waypoint = new StringBuilder();
waypoint.append("\n<wpt lat=\"")
.append(String.valueOf(loc.getLatitude()))
.append("\" lon=\"")
.append(String.valueOf(loc.getLongitude()))
.append("\">");
if (loc.hasAltitude())
{
waypoint.append("<ele>").append(String.valueOf(loc.getAltitude())).append("</ele>");
}
waypoint.append("<time>").append(dateTimeString).append("</time>");
waypoint.append("<name>").append(description).append("</name>");
waypoint.append("<src>").append(loc.getProvider()).append("</src>");
waypoint.append("</wpt>\n");
return waypoint.toString();
}
}
class Gpx10WriteHandler implements Runnable
{
String dateTimeString;
Location loc;
private File gpxFile = null;
private boolean addNewTrackSegment;
private int satelliteCount;
public Gpx10WriteHandler(String dateTimeString, File gpxFile, Location loc, boolean addNewTrackSegment, int satelliteCount)
{
this.dateTimeString = dateTimeString;
this.addNewTrackSegment = addNewTrackSegment;
this.gpxFile = gpxFile;
this.loc = loc;
this.satelliteCount = satelliteCount;
}
@Override
public void run()
{
synchronized (Gpx10FileLogger.lock)
{
try
{
if (!gpxFile.exists())
{
gpxFile.createNewFile();
FileOutputStream initialWriter = new FileOutputStream(gpxFile, true);
BufferedOutputStream initialOutput = new BufferedOutputStream(initialWriter);
StringBuilder initialXml = new StringBuilder();
initialXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
initialXml.append("<gpx version=\"1.0\" creator=\"GPSLogger - http://gpslogger.mendhak.com/\" ");
initialXml.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
initialXml.append("xmlns=\"http://www.topografix.com/GPX/1/0\" ");
initialXml.append("xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 ");
initialXml.append("http://www.topografix.com/GPX/1/0/gpx.xsd\">");
initialXml.append("<time>").append(dateTimeString).append("</time>").append("<trk></trk></gpx>");
initialOutput.write(initialXml.toString().getBytes());
initialOutput.flush();
initialOutput.close();
//New file, so new segment.
addNewTrackSegment = true;
}
int offsetFromEnd = (addNewTrackSegment) ? 12 : 21;
long startPosition = gpxFile.length() - offsetFromEnd;
String trackPoint = GetTrackPointXml(loc, dateTimeString);
RandomAccessFile raf = new RandomAccessFile(gpxFile, "rw");
raf.seek(startPosition);
raf.write(trackPoint.getBytes());
raf.close();
Utilities.LogDebug("Finished writing to GPX10 file");
}
catch (Exception e)
{
Utilities.LogError("Gpx10FileLogger.Write", e);
}
}
}
private String GetTrackPointXml(Location loc, String dateTimeString)
{
StringBuilder track = new StringBuilder();
if (addNewTrackSegment)
{
track.append("<trkseg>");
}
track.append("<trkpt lat=\"")
.append(String.valueOf(loc.getLatitude()))
.append("\" lon=\"")
.append(String.valueOf(loc.getLongitude()))
.append("\">");
if (loc.hasAltitude())
{
track.append("<ele>").append(String.valueOf(loc.getAltitude())).append("</ele>");
}
track.append("<time>").append(dateTimeString).append("</time>");
if (loc.hasBearing())
{
track.append("<course>").append(String.valueOf(loc.getBearing())).append("</course>");
}
if (loc.hasSpeed())
{
track.append("<speed>").append(String.valueOf(loc.getSpeed())).append("</speed>");
}
track.append("<src>").append(loc.getProvider()).append("</src>");
if (satelliteCount > 0)
{
track.append("<sat>").append(String.valueOf(satelliteCount)).append("</sat>");
}
if (loc.hasAccuracy() && loc.getAccuracy() > 0)
{
// Accuracy divided by 5 or 6 for approximate HDOP
track.append("<hdop>").append(String.valueOf(loc.getAccuracy() / 5)).append("</hdop>");
}
track.append("</trkpt>\n");
track.append("</trkseg></trk></gpx>");
return track.toString();
}
}
| true | true | public void run()
{
synchronized (Gpx10FileLogger.lock)
{
if (!gpxFile.exists())
{
return;
}
if (!gpxFile.exists())
{
return;
}
int startPosition = 323;
String wpt = GetWaypointXml(loc, dateTimeString, description);
try
{
//Write to a temp file, delete original file, move temp to original
File gpxTempFile = new File(gpxFile.getAbsolutePath() + ".tmp");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(gpxFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(gpxTempFile));
int written = 0;
int readSize;
byte[] buffer = new byte[startPosition];
while ((readSize = bis.read(buffer)) > 0)
{
bos.write(buffer, 0, readSize);
written += readSize;
System.out.println(written);
if (written == startPosition)
{
bos.write(wpt.getBytes());
buffer = new byte[20480];
}
}
bis.close();
bos.close();
gpxFile.delete();
gpxTempFile.renameTo(gpxFile);
Utilities.LogDebug("Finished annotation to GPX10 File");
}
catch (Exception e)
{
Utilities.LogError("Gpx10FileLogger.Annotate", e);
}
}
}
| public void run()
{
synchronized (Gpx10FileLogger.lock)
{
if (!gpxFile.exists())
{
return;
}
if (!gpxFile.exists())
{
return;
}
int startPosition = 336;
String wpt = GetWaypointXml(loc, dateTimeString, description);
try
{
//Write to a temp file, delete original file, move temp to original
File gpxTempFile = new File(gpxFile.getAbsolutePath() + ".tmp");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(gpxFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(gpxTempFile));
int written = 0;
int readSize;
byte[] buffer = new byte[startPosition];
while ((readSize = bis.read(buffer)) > 0)
{
bos.write(buffer, 0, readSize);
written += readSize;
System.out.println(written);
if (written == startPosition)
{
bos.write(wpt.getBytes());
buffer = new byte[20480];
}
}
bis.close();
bos.close();
gpxFile.delete();
gpxTempFile.renameTo(gpxFile);
Utilities.LogDebug("Finished annotation to GPX10 File");
}
catch (Exception e)
{
Utilities.LogError("Gpx10FileLogger.Annotate", e);
}
}
}
|
diff --git a/src/common/basiccomponents/tile/TileEntityBatteryBox.java b/src/common/basiccomponents/tile/TileEntityBatteryBox.java
index 16a7c8a..793aeb4 100644
--- a/src/common/basiccomponents/tile/TileEntityBatteryBox.java
+++ b/src/common/basiccomponents/tile/TileEntityBatteryBox.java
@@ -1,673 +1,673 @@
package basiccomponents.tile;
import ic2.api.Direction;
import ic2.api.ElectricItem;
import ic2.api.EnergyNet;
import ic2.api.IElectricItem;
import ic2.api.IEnergySink;
import ic2.api.IEnergySource;
import ic2.api.IEnergyStorage;
import java.util.List;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.INetworkManager;
import net.minecraft.src.ItemStack;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NBTTagList;
import net.minecraft.src.Packet;
import net.minecraft.src.Packet250CustomPayload;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.ISidedInventory;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.core.electricity.ElectricInfo;
import universalelectricity.core.electricity.ElectricityManager;
import universalelectricity.core.implement.IConductor;
import universalelectricity.core.implement.IElectricityReceiver;
import universalelectricity.core.implement.IItemElectric;
import universalelectricity.core.implement.IJouleStorage;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.implement.IRedstoneProvider;
import universalelectricity.prefab.network.IPacketReceiver;
import universalelectricity.prefab.network.PacketManager;
import universalelectricity.prefab.tile.TileEntityElectricityReceiver;
import basiccomponents.BCLoader;
import basiccomponents.block.BlockBasicMachine;
import buildcraft.api.power.IPowerProvider;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerFramework;
import buildcraft.api.power.PowerProvider;
import com.google.common.io.ByteArrayDataInput;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.LanguageRegistry;
import dan200.computer.api.IComputerAccess;
import dan200.computer.api.IPeripheral;
public class TileEntityBatteryBox extends TileEntityElectricityReceiver implements IEnergySink, IEnergySource, IEnergyStorage, IPowerReceptor, IJouleStorage, IPacketReceiver, IRedstoneProvider, IInventory, ISidedInventory, IPeripheral
{
private double joules = 0;
private ItemStack[] containingItems = new ItemStack[2];
private boolean isFull = false;
private int playersUsing = 0;
public IPowerProvider powerProvider;
public TileEntityBatteryBox()
{
super();
this.setPowerProvider(null);
}
@Override
public double wattRequest()
{
if (!this.isDisabled()) { return ElectricInfo.getWatts(this.getMaxJoules()) - ElectricInfo.getWatts(this.joules); }
return 0;
}
@Override
public boolean canReceiveFromSide(ForgeDirection side)
{
return side == ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite();
}
@Override
public boolean canConnect(ForgeDirection side)
{
return canReceiveFromSide(side) || side == ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
}
@Override
public void onReceive(Object sender, double amps, double voltage, ForgeDirection side)
{
if (!this.isDisabled())
{
this.setJoules(this.joules + ElectricInfo.getJoules(amps, voltage, 1));
}
}
@Override
public void initiate()
{
if (Loader.isModLoaded("IC2"))
{
try
{
if (Class.forName("ic2.common.EnergyNet").getMethod("getForWorld", World.class) != null)
{
EnergyNet.getForWorld(worldObj).addTileEntity(this);
FMLLog.fine("Added battery box to IC2 energy net.");
}
else
{
FMLLog.severe("Failed to register battery box to IC2 energy net.");
}
}
catch (Exception e)
{
FMLLog.severe("Failed to register battery box to IC2 energy net.");
}
}
}
@Override
public void updateEntity()
{
super.updateEntity();
if (!this.isDisabled())
{
/**
* Receive Electricity
*/
if (this.powerProvider != null)
{
double receivedElectricity = this.powerProvider.useEnergy(50, 50, true) * UniversalElectricity.BC3_RATIO;
this.setJoules(this.joules + receivedElectricity);
}
/*
* The top slot is for recharging items. Check if the item is a electric item. If so,
* recharge it.
*/
if (this.containingItems[0] != null && this.joules > 0)
{
if (this.containingItems[0].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[0].getItem();
- double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules() * 0.005, this.getVoltage()), this.joules);
+ double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules(this.containingItems[0]) * 0.005, this.getVoltage()), this.joules);
double joules = electricItem.onReceive(ampsToGive, this.getVoltage(), this.containingItems[0]);
this.setJoules(this.joules - (ElectricInfo.getJoules(ampsToGive, this.getVoltage(), 1) - joules));
}
else if (this.containingItems[0].getItem() instanceof IElectricItem)
{
double sent = ElectricItem.charge(containingItems[0], (int) (joules * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules - sent);
}
}
// Power redstone if the battery box is full
boolean isFullThisCheck = false;
if (this.joules >= this.getMaxJoules())
{
isFullThisCheck = true;
}
if (this.isFull != isFullThisCheck)
{
this.isFull = isFullThisCheck;
this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType().blockID);
}
/**
* Output Electricity
*/
/**
* The bottom slot is for decharging. Check if the item is a electric item. If so,
* decharge it.
*/
if (this.containingItems[1] != null && this.joules < this.getMaxJoules())
{
if (this.containingItems[1].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[1].getItem();
if (electricItem.canProduceElectricity())
{
- double joulesReceived = electricItem.onUse(electricItem.getMaxJoules() * 0.005, this.containingItems[1]);
+ double joulesReceived = electricItem.onUse(electricItem.getMaxJoules(this.containingItems[1]) * 0.005, this.containingItems[1]);
this.setJoules(this.joules + joulesReceived);
}
}
else if (containingItems[1].getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem) containingItems[1].getItem();
if (item.canProvideEnergy())
{
double gain = ElectricItem.discharge(containingItems[1], (int) ((int) (getMaxJoules() - joules) * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules + gain);
}
}
}
if (this.joules > 0)
{
ForgeDirection outputDirection = ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
TileEntity tileEntity = Vector3.getTileEntityFromSide(this.worldObj, Vector3.get(this), outputDirection);
if (tileEntity != null)
{
TileEntity connector = Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), outputDirection);
// Output UE electricity
if (connector instanceof IConductor)
{
double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getNetwork());
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
if (!this.worldObj.isRemote)
{
ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, this.getVoltage());
}
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
}
else
{
// Output IC2/Buildcraft energy
if (tileEntity instanceof IConductor)
{
if (this.joules * UniversalElectricity.TO_IC2_RATIO >= 32)
{
this.setJoules(this.joules - (32 - EnergyNet.getForWorld(worldObj).emitEnergyFrom(this, 32)) * UniversalElectricity.IC2_RATIO);
}
}
else if (this.isPoweredTile(tileEntity))
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
double BCjoulesNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived()) * UniversalElectricity.BC3_RATIO;
float transferJoules = (float) Math.max(Math.min(Math.min(BCjoulesNeeded, this.joules), 80000), 0);
receptor.getPowerProvider().receiveEnergy((float) (transferJoules * UniversalElectricity.TO_BC_RATIO), ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite());
this.setJoules(this.joules - transferJoules);
}
}
}
else
{
Vector3 outputPosition = Vector3.get(this);
outputPosition.modifyPositionFromSide(outputDirection);
List<Entity> entities = outputPosition.getEntitiesWithin(worldObj, Entity.class);
for (Entity entity : entities)
{
if (entity instanceof IElectricityReceiver)
{
IElectricityReceiver electricEntity = ((IElectricityReceiver) entity);
double joulesNeeded = electricEntity.wattRequest();
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
ElectricityManager.instance.produceElectricity(this, entity, transferAmps, this.getVoltage(), outputDirection);
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
break;
}
}
}
}
}
this.setJoules(this.joules - 0.00005);
if (!this.worldObj.isRemote)
{
if (this.ticks % 3 == 0 && this.playersUsing > 0)
{
PacketManager.sendPacketToClients(getDescriptionPacket(), this.worldObj, Vector3.get(this), 12);
}
}
}
@Override
public Packet getDescriptionPacket()
{
return PacketManager.getPacket(BCLoader.CHANNEL, this, this.joules, this.disabledTicks);
}
@Override
public void handlePacketData(INetworkManager network, int type, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
try
{
this.joules = dataStream.readDouble();
this.disabledTicks = dataStream.readInt();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void openChest()
{
this.playersUsing++;
}
@Override
public void closeChest()
{
this.playersUsing--;
}
/**
* Reads a tile entity from NBT.
*/
@Override
public void readFromNBT(NBTTagCompound par1NBTTagCompound)
{
super.readFromNBT(par1NBTTagCompound);
this.joules = par1NBTTagCompound.getDouble("electricityStored");
NBTTagList var2 = par1NBTTagCompound.getTagList("Items");
this.containingItems = new ItemStack[this.getSizeInventory()];
for (int var3 = 0; var3 < var2.tagCount(); ++var3)
{
NBTTagCompound var4 = (NBTTagCompound) var2.tagAt(var3);
byte var5 = var4.getByte("Slot");
if (var5 >= 0 && var5 < this.containingItems.length)
{
this.containingItems[var5] = ItemStack.loadItemStackFromNBT(var4);
}
}
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound par1NBTTagCompound)
{
super.writeToNBT(par1NBTTagCompound);
par1NBTTagCompound.setDouble("electricityStored", this.joules);
NBTTagList var2 = new NBTTagList();
for (int var3 = 0; var3 < this.containingItems.length; ++var3)
{
if (this.containingItems[var3] != null)
{
NBTTagCompound var4 = new NBTTagCompound();
var4.setByte("Slot", (byte) var3);
this.containingItems[var3].writeToNBT(var4);
var2.appendTag(var4);
}
}
par1NBTTagCompound.setTag("Items", var2);
}
@Override
public int getStartInventorySide(ForgeDirection side)
{
if (side == side.DOWN) { return 1; }
if (side == side.UP) { return 1; }
return 0;
}
@Override
public int getSizeInventorySide(ForgeDirection side)
{
return 1;
}
@Override
public int getSizeInventory()
{
return this.containingItems.length;
}
@Override
public ItemStack getStackInSlot(int par1)
{
return this.containingItems[par1];
}
@Override
public ItemStack decrStackSize(int par1, int par2)
{
if (this.containingItems[par1] != null)
{
ItemStack var3;
if (this.containingItems[par1].stackSize <= par2)
{
var3 = this.containingItems[par1];
this.containingItems[par1] = null;
return var3;
}
else
{
var3 = this.containingItems[par1].splitStack(par2);
if (this.containingItems[par1].stackSize == 0)
{
this.containingItems[par1] = null;
}
return var3;
}
}
else
{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int par1)
{
if (this.containingItems[par1] != null)
{
ItemStack var2 = this.containingItems[par1];
this.containingItems[par1] = null;
return var2;
}
else
{
return null;
}
}
@Override
public void setInventorySlotContents(int par1, ItemStack par2ItemStack)
{
this.containingItems[par1] = par2ItemStack;
if (par2ItemStack != null && par2ItemStack.stackSize > this.getInventoryStackLimit())
{
par2ItemStack.stackSize = this.getInventoryStackLimit();
}
}
@Override
public String getInvName()
{
return LanguageRegistry.instance().getStringLocalization("tile.bcMachine.1.name");
}
@Override
public int getInventoryStackLimit()
{
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer par1EntityPlayer)
{
return this.worldObj.getBlockTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : par1EntityPlayer.getDistanceSq(this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D) <= 64.0D;
}
@Override
public boolean isPoweringTo(ForgeDirection side)
{
return this.isFull;
}
@Override
public boolean isIndirectlyPoweringTo(ForgeDirection side)
{
return isPoweringTo(side);
}
@Override
public double getJoules(Object... data)
{
return this.joules;
}
@Override
public void setJoules(double joules, Object... data)
{
this.joules = Math.max(Math.min(joules, this.getMaxJoules()), 0);
}
@Override
public double getMaxJoules(Object... data)
{
return 3000000;
}
/**
* BUILDCRAFT FUNCTIONS
*/
/**
* Is this tile entity a BC tile?
*/
public boolean isPoweredTile(TileEntity tileEntity)
{
if (tileEntity instanceof IPowerReceptor)
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
IPowerProvider provider = receptor.getPowerProvider();
return provider != null && provider.getClass().getSuperclass().equals(PowerProvider.class);
}
return false;
}
@Override
public void setPowerProvider(IPowerProvider provider)
{
if (provider == null)
{
if (PowerFramework.currentFramework != null)
{
powerProvider = PowerFramework.currentFramework.createPowerProvider();
powerProvider.configure(20, 25, 25, 25, (int) (this.getMaxJoules() * UniversalElectricity.BC3_RATIO));
}
}
else
{
this.powerProvider = provider;
}
}
@Override
public IPowerProvider getPowerProvider()
{
return this.powerProvider;
}
@Override
public void doWork()
{
}
@Override
public int powerRequest()
{
return (int) Math.ceil((this.getMaxJoules() - this.joules) * UniversalElectricity.BC3_RATIO);
}
/**
* INDUSTRIALCRAFT FUNCTIONS
*/
public int getStored()
{
return (int) (this.joules * UniversalElectricity.IC2_RATIO);
}
@Override
public boolean isAddedToEnergyNet()
{
return this.ticks > 0;
}
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, Direction direction)
{
return canReceiveFromSide(direction.toForgeDirection());
}
@Override
public boolean emitsEnergyTo(TileEntity receiver, Direction direction)
{
return direction.toForgeDirection() == ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
}
@Override
public int getCapacity()
{
return (int) (this.getMaxJoules() / UniversalElectricity.IC2_RATIO);
}
@Override
public int getOutput()
{
return 32;
}
@Override
public int getMaxEnergyOutput()
{
return 32;
}
@Override
public boolean demandsEnergy()
{
if (!this.isDisabled() && UniversalElectricity.IC2_RATIO > 0) { return this.joules < getMaxJoules(); }
return false;
}
@Override
public int injectEnergy(Direction directionFrom, int euAmount)
{
if (!this.isDisabled())
{
double inputElectricity = euAmount * UniversalElectricity.IC2_RATIO;
double rejectedElectricity = Math.max(inputElectricity - (this.getMaxJoules() - this.joules), 0);
this.setJoules(joules + inputElectricity);
return (int) (rejectedElectricity * UniversalElectricity.TO_IC2_RATIO);
}
return euAmount;
}
/**
* COMPUTERCRAFT FUNCTIONS
*/
@Override
public String getType()
{
return "BatteryBox";
}
@Override
public String[] getMethodNames()
{
return new String[]
{ "getVoltage", "getWattage", "isFull" };
}
@Override
public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception
{
final int getVoltage = 0;
final int getWattage = 1;
final int isFull = 2;
switch (method)
{
case getVoltage:
return new Object[]
{ getVoltage() };
case getWattage:
return new Object[]
{ ElectricInfo.getWatts(joules) };
case isFull:
return new Object[]
{ isFull };
default:
throw new Exception("Function unimplemented");
}
}
@Override
public boolean canAttachToSide(int side)
{
return true;
}
@Override
public void attach(IComputerAccess computer, String computerSide)
{
}
@Override
public void detach(IComputerAccess computer)
{
}
}
| false | true | public void updateEntity()
{
super.updateEntity();
if (!this.isDisabled())
{
/**
* Receive Electricity
*/
if (this.powerProvider != null)
{
double receivedElectricity = this.powerProvider.useEnergy(50, 50, true) * UniversalElectricity.BC3_RATIO;
this.setJoules(this.joules + receivedElectricity);
}
/*
* The top slot is for recharging items. Check if the item is a electric item. If so,
* recharge it.
*/
if (this.containingItems[0] != null && this.joules > 0)
{
if (this.containingItems[0].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[0].getItem();
double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules() * 0.005, this.getVoltage()), this.joules);
double joules = electricItem.onReceive(ampsToGive, this.getVoltage(), this.containingItems[0]);
this.setJoules(this.joules - (ElectricInfo.getJoules(ampsToGive, this.getVoltage(), 1) - joules));
}
else if (this.containingItems[0].getItem() instanceof IElectricItem)
{
double sent = ElectricItem.charge(containingItems[0], (int) (joules * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules - sent);
}
}
// Power redstone if the battery box is full
boolean isFullThisCheck = false;
if (this.joules >= this.getMaxJoules())
{
isFullThisCheck = true;
}
if (this.isFull != isFullThisCheck)
{
this.isFull = isFullThisCheck;
this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType().blockID);
}
/**
* Output Electricity
*/
/**
* The bottom slot is for decharging. Check if the item is a electric item. If so,
* decharge it.
*/
if (this.containingItems[1] != null && this.joules < this.getMaxJoules())
{
if (this.containingItems[1].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[1].getItem();
if (electricItem.canProduceElectricity())
{
double joulesReceived = electricItem.onUse(electricItem.getMaxJoules() * 0.005, this.containingItems[1]);
this.setJoules(this.joules + joulesReceived);
}
}
else if (containingItems[1].getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem) containingItems[1].getItem();
if (item.canProvideEnergy())
{
double gain = ElectricItem.discharge(containingItems[1], (int) ((int) (getMaxJoules() - joules) * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules + gain);
}
}
}
if (this.joules > 0)
{
ForgeDirection outputDirection = ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
TileEntity tileEntity = Vector3.getTileEntityFromSide(this.worldObj, Vector3.get(this), outputDirection);
if (tileEntity != null)
{
TileEntity connector = Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), outputDirection);
// Output UE electricity
if (connector instanceof IConductor)
{
double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getNetwork());
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
if (!this.worldObj.isRemote)
{
ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, this.getVoltage());
}
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
}
else
{
// Output IC2/Buildcraft energy
if (tileEntity instanceof IConductor)
{
if (this.joules * UniversalElectricity.TO_IC2_RATIO >= 32)
{
this.setJoules(this.joules - (32 - EnergyNet.getForWorld(worldObj).emitEnergyFrom(this, 32)) * UniversalElectricity.IC2_RATIO);
}
}
else if (this.isPoweredTile(tileEntity))
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
double BCjoulesNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived()) * UniversalElectricity.BC3_RATIO;
float transferJoules = (float) Math.max(Math.min(Math.min(BCjoulesNeeded, this.joules), 80000), 0);
receptor.getPowerProvider().receiveEnergy((float) (transferJoules * UniversalElectricity.TO_BC_RATIO), ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite());
this.setJoules(this.joules - transferJoules);
}
}
}
else
{
Vector3 outputPosition = Vector3.get(this);
outputPosition.modifyPositionFromSide(outputDirection);
List<Entity> entities = outputPosition.getEntitiesWithin(worldObj, Entity.class);
for (Entity entity : entities)
{
if (entity instanceof IElectricityReceiver)
{
IElectricityReceiver electricEntity = ((IElectricityReceiver) entity);
double joulesNeeded = electricEntity.wattRequest();
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
ElectricityManager.instance.produceElectricity(this, entity, transferAmps, this.getVoltage(), outputDirection);
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
break;
}
}
}
}
}
this.setJoules(this.joules - 0.00005);
if (!this.worldObj.isRemote)
{
if (this.ticks % 3 == 0 && this.playersUsing > 0)
{
PacketManager.sendPacketToClients(getDescriptionPacket(), this.worldObj, Vector3.get(this), 12);
}
}
}
| public void updateEntity()
{
super.updateEntity();
if (!this.isDisabled())
{
/**
* Receive Electricity
*/
if (this.powerProvider != null)
{
double receivedElectricity = this.powerProvider.useEnergy(50, 50, true) * UniversalElectricity.BC3_RATIO;
this.setJoules(this.joules + receivedElectricity);
}
/*
* The top slot is for recharging items. Check if the item is a electric item. If so,
* recharge it.
*/
if (this.containingItems[0] != null && this.joules > 0)
{
if (this.containingItems[0].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[0].getItem();
double ampsToGive = Math.min(ElectricInfo.getAmps(electricItem.getMaxJoules(this.containingItems[0]) * 0.005, this.getVoltage()), this.joules);
double joules = electricItem.onReceive(ampsToGive, this.getVoltage(), this.containingItems[0]);
this.setJoules(this.joules - (ElectricInfo.getJoules(ampsToGive, this.getVoltage(), 1) - joules));
}
else if (this.containingItems[0].getItem() instanceof IElectricItem)
{
double sent = ElectricItem.charge(containingItems[0], (int) (joules * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules - sent);
}
}
// Power redstone if the battery box is full
boolean isFullThisCheck = false;
if (this.joules >= this.getMaxJoules())
{
isFullThisCheck = true;
}
if (this.isFull != isFullThisCheck)
{
this.isFull = isFullThisCheck;
this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType().blockID);
}
/**
* Output Electricity
*/
/**
* The bottom slot is for decharging. Check if the item is a electric item. If so,
* decharge it.
*/
if (this.containingItems[1] != null && this.joules < this.getMaxJoules())
{
if (this.containingItems[1].getItem() instanceof IItemElectric)
{
IItemElectric electricItem = (IItemElectric) this.containingItems[1].getItem();
if (electricItem.canProduceElectricity())
{
double joulesReceived = electricItem.onUse(electricItem.getMaxJoules(this.containingItems[1]) * 0.005, this.containingItems[1]);
this.setJoules(this.joules + joulesReceived);
}
}
else if (containingItems[1].getItem() instanceof IElectricItem)
{
IElectricItem item = (IElectricItem) containingItems[1].getItem();
if (item.canProvideEnergy())
{
double gain = ElectricItem.discharge(containingItems[1], (int) ((int) (getMaxJoules() - joules) * UniversalElectricity.TO_IC2_RATIO), 3, false, false) * UniversalElectricity.IC2_RATIO;
this.setJoules(joules + gain);
}
}
}
if (this.joules > 0)
{
ForgeDirection outputDirection = ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2);
TileEntity tileEntity = Vector3.getTileEntityFromSide(this.worldObj, Vector3.get(this), outputDirection);
if (tileEntity != null)
{
TileEntity connector = Vector3.getConnectorFromSide(this.worldObj, Vector3.get(this), outputDirection);
// Output UE electricity
if (connector instanceof IConductor)
{
double joulesNeeded = ElectricityManager.instance.getElectricityRequired(((IConductor) connector).getNetwork());
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
if (!this.worldObj.isRemote)
{
ElectricityManager.instance.produceElectricity(this, (IConductor) connector, transferAmps, this.getVoltage());
}
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
}
else
{
// Output IC2/Buildcraft energy
if (tileEntity instanceof IConductor)
{
if (this.joules * UniversalElectricity.TO_IC2_RATIO >= 32)
{
this.setJoules(this.joules - (32 - EnergyNet.getForWorld(worldObj).emitEnergyFrom(this, 32)) * UniversalElectricity.IC2_RATIO);
}
}
else if (this.isPoweredTile(tileEntity))
{
IPowerReceptor receptor = (IPowerReceptor) tileEntity;
double BCjoulesNeeded = Math.min(receptor.getPowerProvider().getMinEnergyReceived(), receptor.getPowerProvider().getMaxEnergyReceived()) * UniversalElectricity.BC3_RATIO;
float transferJoules = (float) Math.max(Math.min(Math.min(BCjoulesNeeded, this.joules), 80000), 0);
receptor.getPowerProvider().receiveEnergy((float) (transferJoules * UniversalElectricity.TO_BC_RATIO), ForgeDirection.getOrientation(this.getBlockMetadata() - BlockBasicMachine.BATTERY_BOX_METADATA + 2).getOpposite());
this.setJoules(this.joules - transferJoules);
}
}
}
else
{
Vector3 outputPosition = Vector3.get(this);
outputPosition.modifyPositionFromSide(outputDirection);
List<Entity> entities = outputPosition.getEntitiesWithin(worldObj, Entity.class);
for (Entity entity : entities)
{
if (entity instanceof IElectricityReceiver)
{
IElectricityReceiver electricEntity = ((IElectricityReceiver) entity);
double joulesNeeded = electricEntity.wattRequest();
double transferAmps = Math.max(Math.min(Math.min(ElectricInfo.getAmps(joulesNeeded, this.getVoltage()), ElectricInfo.getAmps(this.joules, this.getVoltage())), 80), 0);
ElectricityManager.instance.produceElectricity(this, entity, transferAmps, this.getVoltage(), outputDirection);
this.setJoules(this.joules - ElectricInfo.getJoules(transferAmps, this.getVoltage()));
break;
}
}
}
}
}
this.setJoules(this.joules - 0.00005);
if (!this.worldObj.isRemote)
{
if (this.ticks % 3 == 0 && this.playersUsing > 0)
{
PacketManager.sendPacketToClients(getDescriptionPacket(), this.worldObj, Vector3.get(this), 12);
}
}
}
|
diff --git a/src/com/android/phone/MSimNotificationMgr.java b/src/com/android/phone/MSimNotificationMgr.java
index 805b8e0b..4d12433a 100644
--- a/src/com/android/phone/MSimNotificationMgr.java
+++ b/src/com/android/phone/MSimNotificationMgr.java
@@ -1,261 +1,265 @@
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemProperties;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.telephony.Phone;
import static com.android.internal.telephony.MSimConstants.SUBSCRIPTION_KEY;
/**
* NotificationManager-related utility code for the Phone app.
*
* This is a singleton object which acts as the interface to the
* framework's NotificationManager, and is used to display status bar
* icons and control other status bar-related behavior.
*
* @see PhoneApp.notificationMgr
*/
public class MSimNotificationMgr extends NotificationMgr {
private static final String LOG_TAG = "MSimNotificationMgr";
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
static final int VOICEMAIL_NOTIFICATION_SUB2 = 20;
static final int CALL_FORWARD_NOTIFICATION_SUB2 = 21;
/**
* Private constructor (this is a singleton).
* @see init()
*/
private MSimNotificationMgr(PhoneApp app) {
super(app);
}
/**
* Initialize the singleton NotificationMgr instance.
*
* This is only done once, at startup, from PhoneApp.onCreate().
* From then on, the NotificationMgr instance is available via the
* PhoneApp's public "notificationMgr" field, which is why there's no
* getInstance() method here.
*/
/* package */ static MSimNotificationMgr init(PhoneApp app) {
synchronized (MSimNotificationMgr.class) {
if (sInstance == null) {
sInstance = new MSimNotificationMgr(app);
// Update the notifications that need to be touched at startup.
sInstance.updateNotificationsAtStartup();
} else {
Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
}
return (MSimNotificationMgr) sInstance;
}
}
/**
* Updates the message waiting indicator (voicemail) notification.
*
* @param visible true if there are messages waiting
*/
/* package */
void updateMwi(boolean visible, Phone phone) {
if (DBG) log("updateMwi(): " + visible);
int subscription = phone.getSubscription();
if (visible) {
int resId = android.R.drawable.stat_notify_voicemail;
- int[] iconId = {android.R.drawable.stat_notify_voicemail,
- android.R.drawable.stat_notify_voicemail};
+ int[] iconId = {android.R.drawable.stat_notify_voicemail_sub1,
+ android.R.drawable.stat_notify_voicemail_sub2};
// This Notification can get a lot fancier once we have more
// information about the current voicemail messages.
// (For example, the current voicemail system can't tell
// us the caller-id or timestamp of a message, or tell us the
// message count.)
// But for now, the UI is ultra-simple: if the MWI indication
// is supposed to be visible, just show a single generic
// notification.
String notificationTitle = mContext.getString(R.string.notification_voicemail_title);
String vmNumber = phone.getVoiceMailNumber();
if (DBG) log("- got vm number: '" + vmNumber + "'"
+ " on Subscription: " + subscription);
resId = iconId[subscription];
// Watch out: vmNumber may be null, for two possible reasons:
//
// (1) This phone really has no voicemail number
//
// (2) This phone *does* have a voicemail number, but
// the SIM isn't ready yet.
//
// Case (2) *does* happen in practice if you have voicemail
// messages when the device first boots: we get an MWI
// notification as soon as we register on the network, but the
// SIM hasn't finished loading yet.
//
// So handle case (2) by retrying the lookup after a short
// delay.
if ((vmNumber == null) && !phone.getIccRecordsLoaded()) {
if (DBG) log("- Null vm number: SIM records not loaded (yet)...");
// TODO: rather than retrying after an arbitrary delay, it
// would be cleaner to instead just wait for a
// SIM_RECORDS_LOADED notification.
// (Unfortunately right now there's no convenient way to
// get that notification in phone app code. We'd first
// want to add a call like registerForSimRecordsLoaded()
// to Phone.java and GSMPhone.java, and *then* we could
// listen for that in the CallNotifier class.)
// Limit the number of retries (in case the SIM is broken
// or missing and can *never* load successfully.)
if (mVmNumberRetriesRemaining-- > 0) {
if (DBG) log(" - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec...");
((MSimCallNotifier)PhoneApp.getInstance().notifier).sendMwiChangedDelayed(
VM_NUMBER_RETRY_DELAY_MILLIS, phone);
return;
} else {
Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after "
+ MAX_VM_NUMBER_RETRIES + " retries; giving up.");
// ...and continue with vmNumber==null, just as if the
// phone had no VM number set up in the first place.
}
}
if (TelephonyCapabilities.supportsVoiceMessageCount(phone)) {
int vmCount = phone.getVoiceMessageCount();
String titleFormat = mContext.getString(
R.string.notification_voicemail_title_count);
notificationTitle = String.format(titleFormat, vmCount);
}
String notificationText;
if (TextUtils.isEmpty(vmNumber)) {
notificationText = mContext.getString(
R.string.notification_voicemail_no_vm_number);
} else {
notificationText = String.format(
mContext.getString(R.string.notification_voicemail_text_format),
PhoneNumberUtils.formatNumber(vmNumber));
}
Intent intent = new Intent(Intent.ACTION_CALL,
Uri.fromParts("voicemail", "", null));
intent.putExtra(SUBSCRIPTION_KEY, subscription);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Notification notification = new Notification(
resId, // icon
null, // tickerText
System.currentTimeMillis() // Show the time the MWI notification came in,
// since we don't know the actual time of the
// most recent voicemail message
);
notification.setLatestEventInfo(
mContext, // context
notificationTitle, // contentTitle
notificationText, // contentText
pendingIntent // contentIntent
);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_NO_CLEAR;
configureLedNotification(notification);
+ int notificationId = (subscription == 0) ? VOICEMAIL_NOTIFICATION
+ : VOICEMAIL_NOTIFICATION_SUB2;
mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification);
} else {
- mNotificationManager.cancel(VOICEMAIL_NOTIFICATION);
+ int notificationId = (subscription == 0) ? VOICEMAIL_NOTIFICATION
+ : VOICEMAIL_NOTIFICATION_SUB2;
+ mNotificationManager.cancel(notificationId);
}
}
/**
* Updates the message call forwarding indicator notification.
*
* @param visible true if there are messages waiting
*/
/* package */ void updateCfi(boolean visible, int subscription) {
if (DBG) log("updateCfi(): " + visible + "sub = " + subscription);
int [] callfwdIcon = {R.drawable.stat_sys_phone_call_forward_sub1,
R.drawable.stat_sys_phone_call_forward_sub2};
int notificationId = (subscription == 0) ? CALL_FORWARD_NOTIFICATION :
CALL_FORWARD_NOTIFICATION_SUB2;
if (visible) {
// If Unconditional Call Forwarding (forward all calls) for VOICE
// is enabled, just show a notification. We'll default to expanded
// view for now, so the there is less confusion about the icon. If
// it is deemed too weird to have CF indications as expanded views,
// then we'll flip the flag back.
// TODO: We may want to take a look to see if the notification can
// display the target to forward calls to. This will require some
// effort though, since there are multiple layers of messages that
// will need to propagate that information.
int resId = callfwdIcon[subscription];
Notification notification;
final boolean showExpandedNotification = true;
if (showExpandedNotification) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.android.phone",
"com.android.phone.CallFeaturesSetting");
notification = new Notification(
resId, // icon
null, // tickerText
0); // The "timestamp" of this notification is meaningless;
// we only care about whether CFI is currently on or not.
notification.setLatestEventInfo(
mContext, // context
mContext.getString(R.string.labelCF), // expandedTitle
mContext.getString(R.string.sum_cfu_enabled_indicator), // expandedText
PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent
} else {
notification = new Notification(
resId, // icon
null, // tickerText
System.currentTimeMillis() // when
);
}
notification.flags |= Notification.FLAG_ONGOING_EVENT; // also implies FLAG_NO_CLEAR
mNotificationManager.notify(
notificationId,
notification);
} else {
mNotificationManager.cancel(notificationId);
}
}
private void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| false | true | void updateMwi(boolean visible, Phone phone) {
if (DBG) log("updateMwi(): " + visible);
int subscription = phone.getSubscription();
if (visible) {
int resId = android.R.drawable.stat_notify_voicemail;
int[] iconId = {android.R.drawable.stat_notify_voicemail,
android.R.drawable.stat_notify_voicemail};
// This Notification can get a lot fancier once we have more
// information about the current voicemail messages.
// (For example, the current voicemail system can't tell
// us the caller-id or timestamp of a message, or tell us the
// message count.)
// But for now, the UI is ultra-simple: if the MWI indication
// is supposed to be visible, just show a single generic
// notification.
String notificationTitle = mContext.getString(R.string.notification_voicemail_title);
String vmNumber = phone.getVoiceMailNumber();
if (DBG) log("- got vm number: '" + vmNumber + "'"
+ " on Subscription: " + subscription);
resId = iconId[subscription];
// Watch out: vmNumber may be null, for two possible reasons:
//
// (1) This phone really has no voicemail number
//
// (2) This phone *does* have a voicemail number, but
// the SIM isn't ready yet.
//
// Case (2) *does* happen in practice if you have voicemail
// messages when the device first boots: we get an MWI
// notification as soon as we register on the network, but the
// SIM hasn't finished loading yet.
//
// So handle case (2) by retrying the lookup after a short
// delay.
if ((vmNumber == null) && !phone.getIccRecordsLoaded()) {
if (DBG) log("- Null vm number: SIM records not loaded (yet)...");
// TODO: rather than retrying after an arbitrary delay, it
// would be cleaner to instead just wait for a
// SIM_RECORDS_LOADED notification.
// (Unfortunately right now there's no convenient way to
// get that notification in phone app code. We'd first
// want to add a call like registerForSimRecordsLoaded()
// to Phone.java and GSMPhone.java, and *then* we could
// listen for that in the CallNotifier class.)
// Limit the number of retries (in case the SIM is broken
// or missing and can *never* load successfully.)
if (mVmNumberRetriesRemaining-- > 0) {
if (DBG) log(" - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec...");
((MSimCallNotifier)PhoneApp.getInstance().notifier).sendMwiChangedDelayed(
VM_NUMBER_RETRY_DELAY_MILLIS, phone);
return;
} else {
Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after "
+ MAX_VM_NUMBER_RETRIES + " retries; giving up.");
// ...and continue with vmNumber==null, just as if the
// phone had no VM number set up in the first place.
}
}
if (TelephonyCapabilities.supportsVoiceMessageCount(phone)) {
int vmCount = phone.getVoiceMessageCount();
String titleFormat = mContext.getString(
R.string.notification_voicemail_title_count);
notificationTitle = String.format(titleFormat, vmCount);
}
String notificationText;
if (TextUtils.isEmpty(vmNumber)) {
notificationText = mContext.getString(
R.string.notification_voicemail_no_vm_number);
} else {
notificationText = String.format(
mContext.getString(R.string.notification_voicemail_text_format),
PhoneNumberUtils.formatNumber(vmNumber));
}
Intent intent = new Intent(Intent.ACTION_CALL,
Uri.fromParts("voicemail", "", null));
intent.putExtra(SUBSCRIPTION_KEY, subscription);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Notification notification = new Notification(
resId, // icon
null, // tickerText
System.currentTimeMillis() // Show the time the MWI notification came in,
// since we don't know the actual time of the
// most recent voicemail message
);
notification.setLatestEventInfo(
mContext, // context
notificationTitle, // contentTitle
notificationText, // contentText
pendingIntent // contentIntent
);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_NO_CLEAR;
configureLedNotification(notification);
mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification);
} else {
mNotificationManager.cancel(VOICEMAIL_NOTIFICATION);
}
}
| void updateMwi(boolean visible, Phone phone) {
if (DBG) log("updateMwi(): " + visible);
int subscription = phone.getSubscription();
if (visible) {
int resId = android.R.drawable.stat_notify_voicemail;
int[] iconId = {android.R.drawable.stat_notify_voicemail_sub1,
android.R.drawable.stat_notify_voicemail_sub2};
// This Notification can get a lot fancier once we have more
// information about the current voicemail messages.
// (For example, the current voicemail system can't tell
// us the caller-id or timestamp of a message, or tell us the
// message count.)
// But for now, the UI is ultra-simple: if the MWI indication
// is supposed to be visible, just show a single generic
// notification.
String notificationTitle = mContext.getString(R.string.notification_voicemail_title);
String vmNumber = phone.getVoiceMailNumber();
if (DBG) log("- got vm number: '" + vmNumber + "'"
+ " on Subscription: " + subscription);
resId = iconId[subscription];
// Watch out: vmNumber may be null, for two possible reasons:
//
// (1) This phone really has no voicemail number
//
// (2) This phone *does* have a voicemail number, but
// the SIM isn't ready yet.
//
// Case (2) *does* happen in practice if you have voicemail
// messages when the device first boots: we get an MWI
// notification as soon as we register on the network, but the
// SIM hasn't finished loading yet.
//
// So handle case (2) by retrying the lookup after a short
// delay.
if ((vmNumber == null) && !phone.getIccRecordsLoaded()) {
if (DBG) log("- Null vm number: SIM records not loaded (yet)...");
// TODO: rather than retrying after an arbitrary delay, it
// would be cleaner to instead just wait for a
// SIM_RECORDS_LOADED notification.
// (Unfortunately right now there's no convenient way to
// get that notification in phone app code. We'd first
// want to add a call like registerForSimRecordsLoaded()
// to Phone.java and GSMPhone.java, and *then* we could
// listen for that in the CallNotifier class.)
// Limit the number of retries (in case the SIM is broken
// or missing and can *never* load successfully.)
if (mVmNumberRetriesRemaining-- > 0) {
if (DBG) log(" - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec...");
((MSimCallNotifier)PhoneApp.getInstance().notifier).sendMwiChangedDelayed(
VM_NUMBER_RETRY_DELAY_MILLIS, phone);
return;
} else {
Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after "
+ MAX_VM_NUMBER_RETRIES + " retries; giving up.");
// ...and continue with vmNumber==null, just as if the
// phone had no VM number set up in the first place.
}
}
if (TelephonyCapabilities.supportsVoiceMessageCount(phone)) {
int vmCount = phone.getVoiceMessageCount();
String titleFormat = mContext.getString(
R.string.notification_voicemail_title_count);
notificationTitle = String.format(titleFormat, vmCount);
}
String notificationText;
if (TextUtils.isEmpty(vmNumber)) {
notificationText = mContext.getString(
R.string.notification_voicemail_no_vm_number);
} else {
notificationText = String.format(
mContext.getString(R.string.notification_voicemail_text_format),
PhoneNumberUtils.formatNumber(vmNumber));
}
Intent intent = new Intent(Intent.ACTION_CALL,
Uri.fromParts("voicemail", "", null));
intent.putExtra(SUBSCRIPTION_KEY, subscription);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Notification notification = new Notification(
resId, // icon
null, // tickerText
System.currentTimeMillis() // Show the time the MWI notification came in,
// since we don't know the actual time of the
// most recent voicemail message
);
notification.setLatestEventInfo(
mContext, // context
notificationTitle, // contentTitle
notificationText, // contentText
pendingIntent // contentIntent
);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_NO_CLEAR;
configureLedNotification(notification);
int notificationId = (subscription == 0) ? VOICEMAIL_NOTIFICATION
: VOICEMAIL_NOTIFICATION_SUB2;
mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification);
} else {
int notificationId = (subscription == 0) ? VOICEMAIL_NOTIFICATION
: VOICEMAIL_NOTIFICATION_SUB2;
mNotificationManager.cancel(notificationId);
}
}
|
diff --git a/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java b/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java
index 3d39bc6..56a8dd0 100755
--- a/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java
+++ b/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java
@@ -1,98 +1,99 @@
package com.evervolv.EVParts.Preferences;
import com.evervolv.EVParts.R;
import com.evervolv.EVParts.R.bool;
import com.evervolv.EVParts.R.xml;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.EditTextPreference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.widget.Toast;
import android.util.Log;
import android.provider.Settings;
public class LockscreenPrefs extends PreferenceActivity implements OnPreferenceChangeListener {
private static final String CARRIER_CAP = "pref_carrier_caption";
private static final String LOCKSCREEN_ROTARY_LOCK = "pref_use_rotary_lockscreen";
private static final String TRACKBALL_UNLOCK_PREF = "pref_trackball_unlock";
private static final String GENERAL_CATEGORY = "pref_lockscreen_general_category";
private EditTextPreference mCarrierCaption;
private CheckBoxPreference mUseRotaryLockPref;
private CheckBoxPreference mTrackballUnlockPref;
private static final String TAG = "EVParts";
private static final boolean DEBUG = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.lockscreen_prefs);
PreferenceScreen prefSet = getPreferenceScreen();
/* Rotary lockscreen */
mUseRotaryLockPref = (CheckBoxPreference)prefSet.findPreference(LOCKSCREEN_ROTARY_LOCK);
mUseRotaryLockPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.USE_ROTARY_LOCKSCREEN, 1) == 1);
/* Carrier caption */
mCarrierCaption = (EditTextPreference)prefSet.findPreference(CARRIER_CAP);
mCarrierCaption.setOnPreferenceChangeListener(this);
/* Trackball Unlock */
mTrackballUnlockPref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_UNLOCK_PREF);
mTrackballUnlockPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1);
PreferenceCategory generalCategory = (PreferenceCategory) prefSet
.findPreference(GENERAL_CATEGORY);
if (!getResources().getBoolean(R.bool.has_trackball)) {
+ if (DEBUG) Log.d(TAG, "does not have trackball!");
generalCategory.removePreference(mTrackballUnlockPref);
}
}
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
boolean value;
if (preference == mUseRotaryLockPref) {
value = mUseRotaryLockPref.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.USE_ROTARY_LOCKSCREEN, value ? 1 : 0);
//Temporary hack to fix Phone FC's when swapping styles.
ActivityManager am = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
am.forceStopPackage("com.android.phone");
} else if (preference == mTrackballUnlockPref) {
value = mTrackballUnlockPref.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.TRACKBALL_UNLOCK_SCREEN,
value ? 1 : 0);
return true;
}
return true;
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
if (preference == mCarrierCaption) {
Settings.System.putString(getContentResolver(),Settings.System.CARRIER_CAP, objValue.toString());
//Didn't i say i was learning?
ActivityManager am = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
am.forceStopPackage("com.android.phone");
}
return true;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.lockscreen_prefs);
PreferenceScreen prefSet = getPreferenceScreen();
/* Rotary lockscreen */
mUseRotaryLockPref = (CheckBoxPreference)prefSet.findPreference(LOCKSCREEN_ROTARY_LOCK);
mUseRotaryLockPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.USE_ROTARY_LOCKSCREEN, 1) == 1);
/* Carrier caption */
mCarrierCaption = (EditTextPreference)prefSet.findPreference(CARRIER_CAP);
mCarrierCaption.setOnPreferenceChangeListener(this);
/* Trackball Unlock */
mTrackballUnlockPref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_UNLOCK_PREF);
mTrackballUnlockPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1);
PreferenceCategory generalCategory = (PreferenceCategory) prefSet
.findPreference(GENERAL_CATEGORY);
if (!getResources().getBoolean(R.bool.has_trackball)) {
generalCategory.removePreference(mTrackballUnlockPref);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.lockscreen_prefs);
PreferenceScreen prefSet = getPreferenceScreen();
/* Rotary lockscreen */
mUseRotaryLockPref = (CheckBoxPreference)prefSet.findPreference(LOCKSCREEN_ROTARY_LOCK);
mUseRotaryLockPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.USE_ROTARY_LOCKSCREEN, 1) == 1);
/* Carrier caption */
mCarrierCaption = (EditTextPreference)prefSet.findPreference(CARRIER_CAP);
mCarrierCaption.setOnPreferenceChangeListener(this);
/* Trackball Unlock */
mTrackballUnlockPref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_UNLOCK_PREF);
mTrackballUnlockPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1);
PreferenceCategory generalCategory = (PreferenceCategory) prefSet
.findPreference(GENERAL_CATEGORY);
if (!getResources().getBoolean(R.bool.has_trackball)) {
if (DEBUG) Log.d(TAG, "does not have trackball!");
generalCategory.removePreference(mTrackballUnlockPref);
}
}
|
diff --git a/modules/quercus/src/com/caucho/quercus/lib/json/JsonDecoder.java b/modules/quercus/src/com/caucho/quercus/lib/json/JsonDecoder.java
index ad3a42239..04292009c 100644
--- a/modules/quercus/src/com/caucho/quercus/lib/json/JsonDecoder.java
+++ b/modules/quercus/src/com/caucho/quercus/lib/json/JsonDecoder.java
@@ -1,537 +1,540 @@
/*
* Copyright (c) 1998-2008 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 Nam Nguyen
*/
package com.caucho.quercus.lib.json;
import com.caucho.quercus.env.*;
import com.caucho.util.L10N;
class JsonDecoder {
private static final L10N L = new L10N(JsonDecoder.class);
private StringValue _str;
private int _len;
private int _offset;
private boolean _isAssociative;
public Value jsonDecode(Env env,
StringValue s,
boolean assoc)
{
_str = s;
_len = _str.length();
_offset = 0;
_isAssociative = assoc;
Value val = jsonDecodeImpl(env, true);
// Should now be at end of string or have only white spaces left.
skipWhitespace();
if (_offset < _len)
return errorReturn(env, "expected no more input");
return val;
}
/**
* Entry point to decode a JSON value.
*
* @return decoded PHP value
*/
private Value jsonDecodeImpl(Env env, boolean isTop)
{
skipWhitespace();
if (_len <= _offset)
return errorReturn(env);
char ch = _str.charAt(_offset);
switch (ch) {
case '"': { // "string"
_offset++;
return decodeString(env, true);
}
case 'T':
case 't': {
if (isTop && _offset + 4 < _len)
return decodeString(env, false);
else if (_offset + 3 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
- if (ch2 == 'r' || ch2 == 'R'
- && ch3 == 'u' || ch3 == 'U'
- && ch4 == 'e' || ch4 == 'E') {
+ if ((ch2 == 'r' || ch2 == 'R')
+ && (ch3 == 'u' || ch3 == 'U')
+ && (ch4 == 'e' || ch4 == 'E')) {
if (_offset + 4 < _len
&& (ch = _str.charAt(_offset + 4)) != ','
&& ch != ']'
+ && ch != '}'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'true'");
else {
_offset += 4;
return BooleanValue.TRUE;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'true'");
}
case 'F':
case 'f': { // false
if (isTop && _offset + 5 < _len)
return decodeString(env, false);
else if (_offset + 4 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
char ch5 = _str.charAt(_offset + 4);
- if (ch2 == 'a' || ch2 == 'A'
- && ch3 == 'l' || ch3 == 'L'
- && ch4 == 's' || ch4 == 'S'
- && ch5 == 'e' || ch5 == 'E') {
+ if ((ch2 == 'a' || ch2 == 'A')
+ && (ch3 == 'l' || ch3 == 'L')
+ && (ch4 == 's' || ch4 == 'S')
+ && (ch5 == 'e' || ch5 == 'E')) {
if (_offset + 5 < _len
&& (ch = _str.charAt(_offset + 5)) != ','
&& ch != ']'
+ && ch != '}'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'false'");
else {
_offset += 5;
return BooleanValue.FALSE;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'false'");
}
case 'N':
case 'n': {
if (isTop && _offset + 4 < _len)
return decodeString(env, false);
else if (_offset + 3 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
- if (ch2 == 'u' || ch2 == 'U'
- && ch3 == 'l' || ch3 == 'L'
- && ch4 == 'l' || ch4 == 'L') {
+ if ((ch2 == 'u' || ch2 == 'U')
+ && (ch3 == 'l' || ch3 == 'L')
+ && (ch4 == 'l' || ch4 == 'L')) {
if (_offset + 4 < _len
&& (ch = _str.charAt(_offset + 4)) != ','
&& ch != ']'
+ && ch != '}'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'null'");
else {
_offset += 4;
return NullValue.NULL;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'null'");
}
case '[': { // ["foo", "bar", "baz"]
return decodeArray(env);
}
case '{': {
return decodeObject(env);
}
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return decodeNumber(env);
default:
return errorReturn(env);
}
}
/**
* Checks to see if there is a valid number per JSON Internet Draft.
*/
private Value decodeNumber(Env env)
{
int startOffset = _offset;
long value = 0;
int sign = 1;
char ch;
// (-)?
if ((ch = _str.charAt(_offset)) == '-') {
sign = -1;
_offset++;
}
if (_len <= _offset)
return errorReturn(env, "expected 1-9");
ch = _str.charAt(_offset++);
// (0) | ([1-9] [0-9]*)
if (ch == '0') {
}
else if ('1' <= ch && ch <= '9') {
value = ch - '0';
while (_offset < _len
&& '0' <= (ch = _str.charAt(_offset)) && ch <= '9') {
_offset++;
value = 10 * value + ch - '0';
}
}
boolean isDouble = false;
// ((decimalPoint) [0-9]+)?
if (_offset < _len && (ch = _str.charAt(_offset)) == '.') {
_offset++;
isDouble = true;
while (_offset < _len
&& '0' <= (ch = _str.charAt(_offset)) && ch <= '9') {
_offset++;
}
}
// ((e | E) (+ | -)? [0-9]+)
if (_offset < _len && (ch = _str.charAt(_offset)) == 'e' || ch == 'E') {
_offset++;
isDouble = true;
if (_offset < _len && (ch = _str.charAt(_offset)) == '+' || ch == '-') {
_offset++;
}
while (_offset < _len
&& '0' <= (ch = _str.charAt(_offset)) && ch <= '9') {
_offset++;
}
/*
if (_offset < _len)
return errorReturn(env,
L.l("expected 0-9 exponent at '{0}'", (char) ch));
*/
}
if (isDouble) {
String strValue
= _str.stringSubstring(startOffset, _offset);
return DoubleValue.create(Double.parseDouble(strValue));
}
else
return LongValue.create(sign * value);
}
/**
* Returns a non-associative PHP array.
*/
private Value decodeArray(Env env)
{
ArrayValueImpl array = new ArrayValueImpl();
_offset++;
while (true) {
skipWhitespace();
if (_offset >= _len)
return errorReturn(env, "expected either ',' or ']'");
if (_str.charAt(_offset) == ']') {
_offset++;
break;
}
array.append(jsonDecodeImpl(env, false));
skipWhitespace();
if (_offset >= _len)
return errorReturn(env, "expected either ',' or ']'");
char ch = _str.charAt(_offset++);
if (ch == ',') {
}
else if (ch == ']')
break;
else
return errorReturn(env, "expected either ',' or ']'");
}
return array;
}
private Value decodeObject(Env env)
{
if (_isAssociative)
return decodeObjectToArray(env);
else
return decodeObjectToObject(env);
}
/**
* Returns a PHP associative array of JSON object.
*/
private Value decodeObjectToArray(Env env)
{
ArrayValue array = new ArrayValueImpl();
_offset++;
while (true) {
skipWhitespace();
if (_offset >= _len || _str.charAt(_offset) == '}') {
_offset++;
break;
}
Value name = jsonDecodeImpl(env, false);
skipWhitespace();
if (_offset >= _len || _str.charAt(_offset++) != ':')
return errorReturn(env, "expected ':'");
array.append(name, jsonDecodeImpl(env, false));
skipWhitespace();
char ch;
if (_offset >= _len)
return errorReturn(env, "expected either ',' or '}'");
else if ((ch = _str.charAt(_offset++)) == ',') {
}
else if (ch == '}')
break;
else
return errorReturn(env, "expected either ',' or '}'");
}
return array;
}
/**
* Returns a PHP stdObject of JSON object.
*/
private Value decodeObjectToObject(Env env)
{
ObjectValue object = env.createObject();
_offset++;
while (true) {
skipWhitespace();
if (_len <= _offset || _str.charAt(_offset) == '}') {
_offset++;
break;
}
Value name = jsonDecodeImpl(env, false);
skipWhitespace();
if (_len <= _offset || _str.charAt(_offset++) != ':')
return errorReturn(env, "expected ':'");
object.putField(env, name.toString(), jsonDecodeImpl(env, false));
skipWhitespace();
char ch;
if (_offset >= _len)
return errorReturn(env, "expected either ',' or '}'");
else if ((ch = _str.charAt(_offset++)) == ',') {
}
else if (ch == '}')
break;
else
return errorReturn(env, "expected either ',' or '}'");
}
return object;
}
/**
* Returns a PHP string.
*/
private Value decodeString(Env env, boolean isQuoted)
{
StringValue sb = env.createUnicodeBuilder();
while (_offset < _len) {
char ch = _str.charAt(_offset++);
switch (ch) {
// Escaped Characters
case '\\':
if (_offset >= _len)
return errorReturn(env, "invalid escape character");
ch = _str.charAt(_offset++);
switch (ch) {
case '"':
sb.append('"');
break;
case '\\':
sb.append('\\');
break;
case '/':
sb.append('/');
break;
case 'b':
sb.append('\b');
break;
case 'f':
sb.append('\f');
break;
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'u':
case 'U':
int hex = 0;
for (int i = 0; _offset < _len && i < 4; i++) {
hex = hex << 4;
ch = _str.charAt(_offset++);
if ('0' <= ch && ch <= '9')
hex += ch - '0';
else if (ch >= 'a' && ch <= 'f')
hex += ch - 'a' + 10;
else if (ch >= 'A' && ch <= 'F')
hex += ch - 'A' + 10;
else
return errorReturn(env, "invalid escaped hex character");
}
if (hex < 0x80)
sb.append((char)hex);
else if (hex < 0x800) {
sb.append((char) (0xc0 + (hex >> 6)));
sb.append((char) (0x80 + (hex & 0x3f)));
}
else {
sb.append((char) (0xe0 + (hex >> 12)));
sb.append((char) (0x80 + ((hex >> 6) & 0x3f)));
sb.append((char) (0x80 + (hex & 0x3f)));
}
}
break;
case '"':
return sb;
default:
sb.append(ch);
}
}
if (isQuoted)
return errorReturn(env, "error decoding string");
else
return sb;
}
private Value errorReturn(Env env)
{
return errorReturn(env, null);
}
private Value errorReturn(Env env, String message)
{
int end = Math.min(_len, _offset + 1);
String token = _str.substring(_offset, end).toString();
if (message != null)
env.warning(L.l("error parsing '{0}': {1}", token, message));
else
env.warning(L.l("error parsing '{0}'", token));
return NullValue.NULL;
}
private void skipWhitespace()
{
while (_offset < _len) {
char ch = _str.charAt(_offset);
if (ch == ' ' ||
ch == '\n' ||
ch == '\r' ||
ch == '\t')
_offset++;
else
break;
}
}
}
| false | true | private Value jsonDecodeImpl(Env env, boolean isTop)
{
skipWhitespace();
if (_len <= _offset)
return errorReturn(env);
char ch = _str.charAt(_offset);
switch (ch) {
case '"': { // "string"
_offset++;
return decodeString(env, true);
}
case 'T':
case 't': {
if (isTop && _offset + 4 < _len)
return decodeString(env, false);
else if (_offset + 3 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
if (ch2 == 'r' || ch2 == 'R'
&& ch3 == 'u' || ch3 == 'U'
&& ch4 == 'e' || ch4 == 'E') {
if (_offset + 4 < _len
&& (ch = _str.charAt(_offset + 4)) != ','
&& ch != ']'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'true'");
else {
_offset += 4;
return BooleanValue.TRUE;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'true'");
}
case 'F':
case 'f': { // false
if (isTop && _offset + 5 < _len)
return decodeString(env, false);
else if (_offset + 4 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
char ch5 = _str.charAt(_offset + 4);
if (ch2 == 'a' || ch2 == 'A'
&& ch3 == 'l' || ch3 == 'L'
&& ch4 == 's' || ch4 == 'S'
&& ch5 == 'e' || ch5 == 'E') {
if (_offset + 5 < _len
&& (ch = _str.charAt(_offset + 5)) != ','
&& ch != ']'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'false'");
else {
_offset += 5;
return BooleanValue.FALSE;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'false'");
}
case 'N':
case 'n': {
if (isTop && _offset + 4 < _len)
return decodeString(env, false);
else if (_offset + 3 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
if (ch2 == 'u' || ch2 == 'U'
&& ch3 == 'l' || ch3 == 'L'
&& ch4 == 'l' || ch4 == 'L') {
if (_offset + 4 < _len
&& (ch = _str.charAt(_offset + 4)) != ','
&& ch != ']'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'null'");
else {
_offset += 4;
return NullValue.NULL;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'null'");
}
case '[': { // ["foo", "bar", "baz"]
return decodeArray(env);
}
case '{': {
return decodeObject(env);
}
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return decodeNumber(env);
default:
return errorReturn(env);
}
| private Value jsonDecodeImpl(Env env, boolean isTop)
{
skipWhitespace();
if (_len <= _offset)
return errorReturn(env);
char ch = _str.charAt(_offset);
switch (ch) {
case '"': { // "string"
_offset++;
return decodeString(env, true);
}
case 'T':
case 't': {
if (isTop && _offset + 4 < _len)
return decodeString(env, false);
else if (_offset + 3 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
if ((ch2 == 'r' || ch2 == 'R')
&& (ch3 == 'u' || ch3 == 'U')
&& (ch4 == 'e' || ch4 == 'E')) {
if (_offset + 4 < _len
&& (ch = _str.charAt(_offset + 4)) != ','
&& ch != ']'
&& ch != '}'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'true'");
else {
_offset += 4;
return BooleanValue.TRUE;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'true'");
}
case 'F':
case 'f': { // false
if (isTop && _offset + 5 < _len)
return decodeString(env, false);
else if (_offset + 4 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
char ch5 = _str.charAt(_offset + 4);
if ((ch2 == 'a' || ch2 == 'A')
&& (ch3 == 'l' || ch3 == 'L')
&& (ch4 == 's' || ch4 == 'S')
&& (ch5 == 'e' || ch5 == 'E')) {
if (_offset + 5 < _len
&& (ch = _str.charAt(_offset + 5)) != ','
&& ch != ']'
&& ch != '}'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'false'");
else {
_offset += 5;
return BooleanValue.FALSE;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'false'");
}
case 'N':
case 'n': {
if (isTop && _offset + 4 < _len)
return decodeString(env, false);
else if (_offset + 3 < _len) {
char ch2 = _str.charAt(_offset + 1);
char ch3 = _str.charAt(_offset + 2);
char ch4 = _str.charAt(_offset + 3);
if ((ch2 == 'u' || ch2 == 'U')
&& (ch3 == 'l' || ch3 == 'L')
&& (ch4 == 'l' || ch4 == 'L')) {
if (_offset + 4 < _len
&& (ch = _str.charAt(_offset + 4)) != ','
&& ch != ']'
&& ch != '}'
&& ! Character.isWhitespace(ch))
return errorReturn(env, "malformed 'null'");
else {
_offset += 4;
return NullValue.NULL;
}
}
}
if (isTop)
return decodeString(env, false);
else
return errorReturn(env, "expected 'null'");
}
case '[': { // ["foo", "bar", "baz"]
return decodeArray(env);
}
case '{': {
return decodeObject(env);
}
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return decodeNumber(env);
default:
return errorReturn(env);
}
|
diff --git a/src/org/cchmc/bmi/snpomics/SimpleVariant.java b/src/org/cchmc/bmi/snpomics/SimpleVariant.java
index eb4f69a..8cef3c5 100644
--- a/src/org/cchmc/bmi/snpomics/SimpleVariant.java
+++ b/src/org/cchmc/bmi/snpomics/SimpleVariant.java
@@ -1,34 +1,34 @@
package org.cchmc.bmi.snpomics;
/**
* <p>A SimpleVariant is, well, the simplest representation of a variant. There is only
* one alternate allele, there are no annotations, etc.</p>
* <p>This record is normalized - that is, the ref and alt alleles are as short
* as possible to represent the variation (but at least one nucleotide), and the position
* is the correct span of the ref allele</p>
* <p>Note that a SimpleVariant is also immutable</p>
* @author dexzb9
*
*/
public class SimpleVariant {
public SimpleVariant(GenomicSpan pos, String refAllele, String altAllele) {
position = pos.clone();
ref = refAllele;
alt = altAllele;
//Normalize!
while (ref.length() > 1 && alt.length() > 1 &&
ref.charAt(0) == alt.charAt(0)) {
ref = ref.substring(1);
alt = alt.substring(1);
- pos.setStart(pos.getStart()+1);
+ position.setStart(position.getStart()+1);
}
}
private GenomicSpan position;
private String ref;
private String alt;
public GenomicSpan getPosition() { return position.clone(); }
public String getRef() { return ref; }
public String getAlt() { return alt; }
}
| true | true | public SimpleVariant(GenomicSpan pos, String refAllele, String altAllele) {
position = pos.clone();
ref = refAllele;
alt = altAllele;
//Normalize!
while (ref.length() > 1 && alt.length() > 1 &&
ref.charAt(0) == alt.charAt(0)) {
ref = ref.substring(1);
alt = alt.substring(1);
pos.setStart(pos.getStart()+1);
}
}
| public SimpleVariant(GenomicSpan pos, String refAllele, String altAllele) {
position = pos.clone();
ref = refAllele;
alt = altAllele;
//Normalize!
while (ref.length() > 1 && alt.length() > 1 &&
ref.charAt(0) == alt.charAt(0)) {
ref = ref.substring(1);
alt = alt.substring(1);
position.setStart(position.getStart()+1);
}
}
|
diff --git a/src/com/rb/sqlitefirst/MainActivity.java b/src/com/rb/sqlitefirst/MainActivity.java
index 0b778e8..a03bf0d 100644
--- a/src/com/rb/sqlitefirst/MainActivity.java
+++ b/src/com/rb/sqlitefirst/MainActivity.java
@@ -1,77 +1,78 @@
package com.rb.sqlitefirst;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class MainActivity extends ListActivity {
private CommentsDataSource dataSource;
private EditText commentString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSource = new CommentsDataSource(this);
dataSource.open();
commentString = (EditText)findViewById(R.id.edit_comment);
List<Comment> values = dataSource.getAllComments();
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>
(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
public void onClick(View view){
@SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch(view.getId()){
case R.id.button_add:
if(commentString.getText() != null){
String strComment = commentString.getText().toString();
comment = dataSource.createComment(strComment);
adapter.add(comment);
+ commentString.setText("");
}
break;
case R.id.button_delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(0);
dataSource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
dataSource.open();
super.onResume();
}
@Override
protected void onPause() {
dataSource.close();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true | true | public void onClick(View view){
@SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch(view.getId()){
case R.id.button_add:
if(commentString.getText() != null){
String strComment = commentString.getText().toString();
comment = dataSource.createComment(strComment);
adapter.add(comment);
}
break;
case R.id.button_delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(0);
dataSource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
| public void onClick(View view){
@SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch(view.getId()){
case R.id.button_add:
if(commentString.getText() != null){
String strComment = commentString.getText().toString();
comment = dataSource.createComment(strComment);
adapter.add(comment);
commentString.setText("");
}
break;
case R.id.button_delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(0);
dataSource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
|
diff --git a/src/core/org/pathvisio/model/CurvedConnectorShape.java b/src/core/org/pathvisio/model/CurvedConnectorShape.java
index f0bcae31..0b9391d7 100644
--- a/src/core/org/pathvisio/model/CurvedConnectorShape.java
+++ b/src/core/org/pathvisio/model/CurvedConnectorShape.java
@@ -1,221 +1,221 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio.model;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
/**
* Implements a curved connector that draws curved lines between
* the segments.
* @author thomas
*
*/
public class CurvedConnectorShape extends ElbowConnectorShape {
Segment[] elbowSegments; //The original segments of the elbow connector
CurvedSegment[] curvedSegments; //The elbow segment with bezier points
//Higher resolution approximation of the curve
//Used for calculating the anchor position
Segment[] curveHigh;
//Lower resolution approximation of the curve
//Used for calculating the arrow heads
Segment[] curveLow;
protected Shape calculateShape() {
return calculateShape(elbowSegments);
}
public Shape calculateShape(Segment[] segments) {
GeneralPath path = new GeneralPath();
CurvedSegment[] curvedSegments = calculateCurvedSegments(segments);
path.moveTo(
- curvedSegments[0].getMStart().getX(),
- curvedSegments[0].getMStart().getY()
+ (float)curvedSegments[0].getMStart().getX(),
+ (float)curvedSegments[0].getMStart().getY()
);
Segment first = segments[0];
path.moveTo(
(float)first.getMStart().getX(),
(float)first.getMStart().getY()
);
for(int i = 0; i < curvedSegments.length; i++) {
CurvedSegment cs = curvedSegments[i];
path.curveTo(
- cs.getC1().getX(),
- cs.getC1().getY(),
- cs.getC2().getX(),
- cs.getC2().getY(),
- cs.getMEnd().getX(),
- cs.getMEnd().getY()
+ (float)cs.getC1().getX(),
+ (float)cs.getC1().getY(),
+ (float)cs.getC2().getX(),
+ (float)cs.getC2().getY(),
+ (float)cs.getMEnd().getX(),
+ (float)cs.getMEnd().getY()
);
}
// //Custom curve calculation (for testing)
// Segment[] curve = calculateCurve(NRSTEP_LOW);
// path.moveTo(curve[0].getMStart().getX(), curve[0].getMStart().getY());
// for(int i = 0; i < curve.length; i++) {
// path.lineTo(curve[i].getMEnd().getX(), curve[i].getMEnd().getY());
// }
return path;
}
/**
* Also calculates curvedSegments and curve
* @see calculateCurvedSegments
* @see calculateCurve
*/
protected Segment[] calculateSegments(ConnectorRestrictions restrictions,
WayPoint[] waypoints) {
elbowSegments = super.calculateSegments(restrictions, waypoints);
//Also calculate curved segments
curvedSegments = calculateCurvedSegments(elbowSegments);
curveHigh = calculateCurve(NRSTEP_HIGH);
curveLow = calculateCurve(NRSTEP_LOW);
return curveHigh;
}
/**
* Based on the given elbow segments, calculate a new segment
* and control points for each bezier curve.
*/
protected CurvedSegment[] calculateCurvedSegments(Segment[] segments) {
CurvedSegment[] curvedSegments = new CurvedSegment[segments.length - 1];
Segment first = segments[0];
Segment last = segments[segments.length - 1];
Point2D prev = first.getMStart();
for(int i = 1; i < segments.length - 1; i++) {
Segment s = segments[i];
Point2D center = s.getMCenter();
Point2D start = s.getMStart();
curvedSegments[i - 1] = new CurvedSegment(
prev,
center,
prev,
start
);
prev = s.getMCenter();
}
curvedSegments[curvedSegments.length - 1] = new CurvedSegment(
prev,
last.getMEnd(),
last.getMStart(),
last.getMEnd()
);
return curvedSegments;
}
static final int NRSTEP_LOW = 3; //Number of steps for lowres curve
static final int NRSTEP_HIGH = 10; //Number of steps for highres curve
/**
* Calculates the bezier curve, using NRSTEP segments for each
* curvedSegment.
* @see calculateCurvedSegments
* @return An array with the curve broken down into small segments
*/
protected Segment[] calculateCurve(int nrStep) {
curveHigh = new Segment[nrStep * curvedSegments.length];
for(int i = 0; i < curvedSegments.length; i++) {
CurvedSegment cs = curvedSegments[i];
Point2D prev = cs.getMStart();
for(int j = 0; j < nrStep; j++) {
double t = (j + 1) * 1.0/nrStep;
double xe = bezier(
cs.getMStart().getX(),
cs.getC1().getX(),
cs.getC2().getX(),
cs.getMEnd().getX(),
t
);
double ye = bezier(
cs.getMStart().getY(),
cs.getC1().getY(),
cs.getC2().getY(),
cs.getMEnd().getY(),
t
);
curveHigh[i * nrStep + j] =
new Segment(prev, new Point2D.Double(xe, ye));
prev = new Point2D.Double(xe, ye);
}
}
return curveHigh;
}
/**
* Function for the cubic bezier curve
* @param p0 The start coordinate
* @param p1 The first helper coordinate
* @param p2 The second helper coordinate
* @param p3 The end coordinate
* @param t The relative position in the curve (0 <= t <= 1)
* @return The coordinate on the curve for t
*/
private double bezier(double p0, double p1, double p2, double p3, double t) {
return (pow((1-t), 3))*p0 + 3*t*pow((1-t),2)*p1 +
3*pow(t, 2)*(1-t)*p2 + pow(t, 3)*p3;
}
private double pow(double a, double b) {
return Math.pow(a, b);
}
/**
* Segment for curved connector, also stores bezier control points
* @author thomas
*/
private class CurvedSegment extends Segment {
private Point2D c1;
private Point2D c2;
public CurvedSegment(Point2D start, Point2D end, Point2D c1, Point2D c2) {
super(start, end);
this.c1 = c1;
this.c2 = c2;
}
public Point2D getC1() {
return c1;
}
public Point2D getC2() {
return c2;
}
}
public Point2D fromLineCoordinate(double l) {
return super.fromLineCoordinate(l, curveLow);
}
protected WayPoint[] wayPointsToCenter(WayPoint[] waypoints,
Segment[] segments) {
return super.wayPointsToCenter(waypoints, elbowSegments);
}
}
| false | true | public Shape calculateShape(Segment[] segments) {
GeneralPath path = new GeneralPath();
CurvedSegment[] curvedSegments = calculateCurvedSegments(segments);
path.moveTo(
curvedSegments[0].getMStart().getX(),
curvedSegments[0].getMStart().getY()
);
Segment first = segments[0];
path.moveTo(
(float)first.getMStart().getX(),
(float)first.getMStart().getY()
);
for(int i = 0; i < curvedSegments.length; i++) {
CurvedSegment cs = curvedSegments[i];
path.curveTo(
cs.getC1().getX(),
cs.getC1().getY(),
cs.getC2().getX(),
cs.getC2().getY(),
cs.getMEnd().getX(),
cs.getMEnd().getY()
);
}
// //Custom curve calculation (for testing)
// Segment[] curve = calculateCurve(NRSTEP_LOW);
// path.moveTo(curve[0].getMStart().getX(), curve[0].getMStart().getY());
// for(int i = 0; i < curve.length; i++) {
// path.lineTo(curve[i].getMEnd().getX(), curve[i].getMEnd().getY());
// }
return path;
}
| public Shape calculateShape(Segment[] segments) {
GeneralPath path = new GeneralPath();
CurvedSegment[] curvedSegments = calculateCurvedSegments(segments);
path.moveTo(
(float)curvedSegments[0].getMStart().getX(),
(float)curvedSegments[0].getMStart().getY()
);
Segment first = segments[0];
path.moveTo(
(float)first.getMStart().getX(),
(float)first.getMStart().getY()
);
for(int i = 0; i < curvedSegments.length; i++) {
CurvedSegment cs = curvedSegments[i];
path.curveTo(
(float)cs.getC1().getX(),
(float)cs.getC1().getY(),
(float)cs.getC2().getX(),
(float)cs.getC2().getY(),
(float)cs.getMEnd().getX(),
(float)cs.getMEnd().getY()
);
}
// //Custom curve calculation (for testing)
// Segment[] curve = calculateCurve(NRSTEP_LOW);
// path.moveTo(curve[0].getMStart().getX(), curve[0].getMStart().getY());
// for(int i = 0; i < curve.length; i++) {
// path.lineTo(curve[i].getMEnd().getX(), curve[i].getMEnd().getY());
// }
return path;
}
|
diff --git a/src/org/jacorb/orb/util/FixIOR.java b/src/org/jacorb/orb/util/FixIOR.java
index 77a07b1b..667f452c 100644
--- a/src/org/jacorb/orb/util/FixIOR.java
+++ b/src/org/jacorb/orb/util/FixIOR.java
@@ -1,143 +1,145 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2002 Gerald Brose.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.orb.util;
import org.jacorb.orb.connection.CodeSet;
import org.jacorb.orb.ParsedIOR;
import org.jacorb.orb.*;
import org.omg.IOP.*;
import org.omg.GIOP.*;
import org.omg.IIOP.*;
import org.omg.SSLIOP.*;
import org.omg.CSIIOP.*;
import org.omg.CONV_FRAME.*;
import java.io.*;
/**
* Utility class to patch host and port information into an IOR.
*
* @author Steve Osselton
*/
public class FixIOR
{
public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
- System.err.println ("IOR must be in the standard IOR URL scheme");
+ System.err.println ("IOR must be in the standard IOR URL format");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
+ is.openEncapsulatedArray ();
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
+ is.openEncapsulatedArray ();
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
private FixIOR ()
{
}
}
| false | true | public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
System.err.println ("IOR must be in the standard IOR URL scheme");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
| public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
System.err.println ("IOR must be in the standard IOR URL format");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
is.openEncapsulatedArray ();
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
is.openEncapsulatedArray ();
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
|
diff --git a/samson-core/src/main/java/samson/form/WrapForm.java b/samson-core/src/main/java/samson/form/WrapForm.java
index b2eb71c..624845c 100644
--- a/samson-core/src/main/java/samson/form/WrapForm.java
+++ b/samson-core/src/main/java/samson/form/WrapForm.java
@@ -1,149 +1,149 @@
package samson.form;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import samson.Element;
import samson.convert.ConverterException;
import samson.metadata.ElementRef;
/**
* Wrapping form.
*/
class WrapForm<T> extends AbstractForm<T> {
public WrapForm(Element parameter, T parameterValue) {
super(parameter, parameterValue);
}
// -- Form methods
@Override
public boolean hasErrors() {
return false;
}
@Override
public Set<ConverterException> getConversionErrors() {
return Collections.emptySet();
}
@Override
public Set<ConstraintViolation<T>> getConstraintViolations() {
return Collections.emptySet();
}
// -- Field methods
@Override
public Field getField(final String param) {
final ElementRef ref = getElementRef(param);
return new Field() {
@Override
public Element getElement() {
- if (ref != ElementRef.NULL_REF) {
+ if (ref != null) {
return ref.element;
}
else {
return null;
}
}
@Override
public Object getObjectValue() {
- if (ref != ElementRef.NULL_REF) {
+ if (ref != null) {
return ref.accessor.get();
}
else {
return null;
}
}
@Override
public String getValue() {
- if (ref != ElementRef.NULL_REF) {
+ if (ref != null) {
return toStringValue(ref.element, ref.accessor.get());
}
else {
return null;
}
}
@Override
public List<String> getValues() {
- if (ref != ElementRef.NULL_REF) {
+ if (ref != null) {
return toStringList(ref.element, ref.accessor.get());
}
else {
return Collections.emptyList();
}
}
@Override
public boolean isError() {
return false;
}
@Override
public ConverterException getConversionError() {
return null;
}
@Override
public Set<ConstraintViolation<?>> getConstraintViolations() {
return Collections.emptySet();
}
@Override
public Messages getMessages() {
return form.getMessages(param);
}
};
}
@Override
public Messages getMessages(final String param) {
final Messages messages = super.getMessages(param);
return new Messages() {
@Override
public String getConversionInfo() {
return messages.getConversionInfo();
}
@Override
public String getConversionError() {
return null;
}
@Override
public List<String> getValidationInfos() {
return messages.getValidationInfos();
}
@Override
public List<String> getValidationErrors() {
return Collections.emptyList();
}
@Override
public List<String> getInfos() {
return messages.getInfos();
}
@Override
public List<String> getErrors() {
return messages.getErrors();
}
};
}
}
| false | true | public Field getField(final String param) {
final ElementRef ref = getElementRef(param);
return new Field() {
@Override
public Element getElement() {
if (ref != ElementRef.NULL_REF) {
return ref.element;
}
else {
return null;
}
}
@Override
public Object getObjectValue() {
if (ref != ElementRef.NULL_REF) {
return ref.accessor.get();
}
else {
return null;
}
}
@Override
public String getValue() {
if (ref != ElementRef.NULL_REF) {
return toStringValue(ref.element, ref.accessor.get());
}
else {
return null;
}
}
@Override
public List<String> getValues() {
if (ref != ElementRef.NULL_REF) {
return toStringList(ref.element, ref.accessor.get());
}
else {
return Collections.emptyList();
}
}
@Override
public boolean isError() {
return false;
}
@Override
public ConverterException getConversionError() {
return null;
}
@Override
public Set<ConstraintViolation<?>> getConstraintViolations() {
return Collections.emptySet();
}
@Override
public Messages getMessages() {
return form.getMessages(param);
}
};
}
| public Field getField(final String param) {
final ElementRef ref = getElementRef(param);
return new Field() {
@Override
public Element getElement() {
if (ref != null) {
return ref.element;
}
else {
return null;
}
}
@Override
public Object getObjectValue() {
if (ref != null) {
return ref.accessor.get();
}
else {
return null;
}
}
@Override
public String getValue() {
if (ref != null) {
return toStringValue(ref.element, ref.accessor.get());
}
else {
return null;
}
}
@Override
public List<String> getValues() {
if (ref != null) {
return toStringList(ref.element, ref.accessor.get());
}
else {
return Collections.emptyList();
}
}
@Override
public boolean isError() {
return false;
}
@Override
public ConverterException getConversionError() {
return null;
}
@Override
public Set<ConstraintViolation<?>> getConstraintViolations() {
return Collections.emptySet();
}
@Override
public Messages getMessages() {
return form.getMessages(param);
}
};
}
|
diff --git a/core/src/test/java/org/apache/accumulo/core/security/crypto/BlockedIOStreamTest.java b/core/src/test/java/org/apache/accumulo/core/security/crypto/BlockedIOStreamTest.java
index 6fb52dd54..b344fc33f 100644
--- a/core/src/test/java/org/apache/accumulo/core/security/crypto/BlockedIOStreamTest.java
+++ b/core/src/test/java/org/apache/accumulo/core/security/crypto/BlockedIOStreamTest.java
@@ -1,118 +1,118 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.security.crypto;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Random;
import org.apache.accumulo.core.Constants;
import org.junit.Test;
public class BlockedIOStreamTest {
@Test
public void testLargeBlockIO() throws IOException {
writeRead(1024, 2048);
}
private void writeRead(int blockSize, int expectedSize) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BlockedOutputStream blockOut = new BlockedOutputStream(baos, blockSize, 1);
String contentString = "My Blocked Content String";
byte[] content = contentString.getBytes(Constants.UTF8);
blockOut.write(content);
blockOut.flush();
String contentString2 = "My Other Blocked Content String";
byte[] content2 = contentString2.getBytes(Constants.UTF8);
blockOut.write(content2);
blockOut.flush();
blockOut.close();
byte[] written = baos.toByteArray();
assertEquals(expectedSize, written.length);
ByteArrayInputStream biis = new ByteArrayInputStream(written);
BlockedInputStream blockIn = new BlockedInputStream(biis, blockSize, blockSize);
DataInputStream dIn = new DataInputStream(blockIn);
dIn.readFully(content, 0, content.length);
String readContentString = new String(content, Constants.UTF8);
assertEquals(contentString, readContentString);
dIn.readFully(content2, 0, content2.length);
String readContentString2 = new String(content2, Constants.UTF8);
assertEquals(contentString2, readContentString2);
blockIn.close();
}
@Test
public void testSmallBufferBlockedIO() throws IOException {
writeRead(16, (12 + 4) * (int) (Math.ceil(25.0/12) + Math.ceil(31.0/12)));
}
@Test
public void testSpillingOverOutputStream() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// buffer will be size 12
BlockedOutputStream blockOut = new BlockedOutputStream(baos, 16, 16);
Random r = new Random(22);
byte[] undersized = new byte[11];
byte[] perfectSized = new byte[12];
byte[] overSized = new byte[13];
byte[] perfectlyOversized = new byte[13];
byte filler = (byte) r.nextInt();
r.nextBytes(undersized);
r.nextBytes(perfectSized);
r.nextBytes(overSized);
r.nextBytes(perfectlyOversized);
// 1 block
blockOut.write(undersized);
blockOut.write(filler);
blockOut.flush();
// 2 blocks
blockOut.write(perfectSized);
blockOut.write(filler);
blockOut.flush();
// 2 blocks
blockOut.write(overSized);
blockOut.write(filler);
blockOut.flush();
// 3 blocks
blockOut.write(undersized);
blockOut.write(perfectlyOversized);
blockOut.write(filler);
blockOut.flush();
- baos.close();
+ blockOut.close();
assertEquals(16*8, baos.toByteArray().length);
}
}
| true | true | public void testSpillingOverOutputStream() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// buffer will be size 12
BlockedOutputStream blockOut = new BlockedOutputStream(baos, 16, 16);
Random r = new Random(22);
byte[] undersized = new byte[11];
byte[] perfectSized = new byte[12];
byte[] overSized = new byte[13];
byte[] perfectlyOversized = new byte[13];
byte filler = (byte) r.nextInt();
r.nextBytes(undersized);
r.nextBytes(perfectSized);
r.nextBytes(overSized);
r.nextBytes(perfectlyOversized);
// 1 block
blockOut.write(undersized);
blockOut.write(filler);
blockOut.flush();
// 2 blocks
blockOut.write(perfectSized);
blockOut.write(filler);
blockOut.flush();
// 2 blocks
blockOut.write(overSized);
blockOut.write(filler);
blockOut.flush();
// 3 blocks
blockOut.write(undersized);
blockOut.write(perfectlyOversized);
blockOut.write(filler);
blockOut.flush();
baos.close();
assertEquals(16*8, baos.toByteArray().length);
}
| public void testSpillingOverOutputStream() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// buffer will be size 12
BlockedOutputStream blockOut = new BlockedOutputStream(baos, 16, 16);
Random r = new Random(22);
byte[] undersized = new byte[11];
byte[] perfectSized = new byte[12];
byte[] overSized = new byte[13];
byte[] perfectlyOversized = new byte[13];
byte filler = (byte) r.nextInt();
r.nextBytes(undersized);
r.nextBytes(perfectSized);
r.nextBytes(overSized);
r.nextBytes(perfectlyOversized);
// 1 block
blockOut.write(undersized);
blockOut.write(filler);
blockOut.flush();
// 2 blocks
blockOut.write(perfectSized);
blockOut.write(filler);
blockOut.flush();
// 2 blocks
blockOut.write(overSized);
blockOut.write(filler);
blockOut.flush();
// 3 blocks
blockOut.write(undersized);
blockOut.write(perfectlyOversized);
blockOut.write(filler);
blockOut.flush();
blockOut.close();
assertEquals(16*8, baos.toByteArray().length);
}
|
diff --git a/omod/src/test/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentControllerTest.java b/omod/src/test/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentControllerTest.java
index 6dd8d679..7a638960 100644
--- a/omod/src/test/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentControllerTest.java
+++ b/omod/src/test/java/org/openmrs/module/emr/fragment/controller/visit/VisitDetailsFragmentControllerTest.java
@@ -1,108 +1,109 @@
package org.openmrs.module.emr.fragment.controller.visit;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.openmrs.*;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.context.UserContext;
import org.openmrs.module.emr.EmrContext;
import org.openmrs.module.emr.TestUiUtils;
import org.openmrs.ui.framework.SimpleObject;
import org.openmrs.ui.framework.UiFrameworkConstants;
import org.openmrs.ui.framework.UiUtils;
import org.openmrs.util.OpenmrsUtil;
import java.text.ParseException;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class VisitDetailsFragmentControllerTest {
@Test
public void shouldReturnEncountersForVisit() throws ParseException {
EmrContext emrContext = mock(EmrContext.class);
UserContext userContext = mock(UserContext.class);
User authenticatedUser = new User();
when(userContext.getAuthenticatedUser()).thenReturn(authenticatedUser);
when(emrContext.getUserContext()).thenReturn(userContext);
AdministrationService administrationService = mock(AdministrationService.class);
when(administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT)).thenReturn("dd.MMM.yyyy, HH:mm:ss");
Visit visit = new Visit();
Location visitLocation = new Location();
visitLocation.setName("Visit Location");
visit.setLocation(visitLocation);
visit.setStartDatetime(new Date());
visit.setStopDatetime(new Date());
Location encounterLocation = new Location();
encounterLocation.setName("Location");
EncounterType encounterType = new EncounterType();
encounterType.setName("Encounter Type");
encounterType.setUuid("abc-123-def-456");
Provider provider = new Provider();
provider.setName("Provider");
EncounterProvider encounterProvider = new EncounterProvider();
encounterProvider.setProvider(provider);
encounterProvider.setEncounterRole(new EncounterRole());
Encounter encounter = new Encounter();
encounter.setEncounterId(7);
encounter.setEncounterDatetime(new Date());
encounter.setLocation(encounterLocation);
encounter.setEncounterType(encounterType);
encounter.setEncounterProviders(new LinkedHashSet<EncounterProvider>());
encounter.getEncounterProviders().add(encounterProvider);
+ encounter.setCreator(authenticatedUser);
visit.addEncounter(encounter);
UiUtils uiUtils = new TestUiUtils(administrationService);
VisitDetailsFragmentController controller = new VisitDetailsFragmentController();
SimpleObject response = controller.getVisitDetails(administrationService, visit, uiUtils, emrContext);
List<SimpleObject> actualEncounters = (List<SimpleObject>) response.get("encounters");
SimpleObject actualEncounter = actualEncounters.get(0);
assertThat(response.get("startDatetime"), notNullValue());
assertThat(response.get("stopDatetime"), notNullValue());
assertThat((String) response.get("location"), is("Visit Location"));
assertThat(actualEncounters.size(), is(1));
assertThat((Integer) actualEncounter.get("encounterId"), is(7));
assertThat((String) actualEncounter.get("location"), is("Location"));
assertThat((SimpleObject) actualEncounter.get("encounterType"), isSimpleObjectWith("uuid", encounterType.getUuid(), "name", encounterType.getName()));
assertThat(actualEncounter.get("encounterDatetime"), notNullValue());
assertThat(actualEncounter.get("encounterDate"), notNullValue());
assertThat(actualEncounter.get("encounterTime"), notNullValue());
List<SimpleObject> actualProviders = (List<SimpleObject>) actualEncounter.get("encounterProviders");
assertThat(actualProviders.size(), is(1));
assertThat((String) actualProviders.get(0).get("provider"), is("Provider"));
}
private Matcher<SimpleObject> isSimpleObjectWith(final Object... propertiesAndValues) {
return new ArgumentMatcher<SimpleObject>() {
@Override
public boolean matches(Object o) {
SimpleObject so = (SimpleObject) o;
for (int i = 0; i < propertiesAndValues.length; i += 2) {
String property = (String) propertiesAndValues[i];
Object expectedValue = propertiesAndValues[i + 1];
if (!OpenmrsUtil.nullSafeEquals(so.get(property), expectedValue)) {
return false;
}
}
return true;
}
};
}
}
| true | true | public void shouldReturnEncountersForVisit() throws ParseException {
EmrContext emrContext = mock(EmrContext.class);
UserContext userContext = mock(UserContext.class);
User authenticatedUser = new User();
when(userContext.getAuthenticatedUser()).thenReturn(authenticatedUser);
when(emrContext.getUserContext()).thenReturn(userContext);
AdministrationService administrationService = mock(AdministrationService.class);
when(administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT)).thenReturn("dd.MMM.yyyy, HH:mm:ss");
Visit visit = new Visit();
Location visitLocation = new Location();
visitLocation.setName("Visit Location");
visit.setLocation(visitLocation);
visit.setStartDatetime(new Date());
visit.setStopDatetime(new Date());
Location encounterLocation = new Location();
encounterLocation.setName("Location");
EncounterType encounterType = new EncounterType();
encounterType.setName("Encounter Type");
encounterType.setUuid("abc-123-def-456");
Provider provider = new Provider();
provider.setName("Provider");
EncounterProvider encounterProvider = new EncounterProvider();
encounterProvider.setProvider(provider);
encounterProvider.setEncounterRole(new EncounterRole());
Encounter encounter = new Encounter();
encounter.setEncounterId(7);
encounter.setEncounterDatetime(new Date());
encounter.setLocation(encounterLocation);
encounter.setEncounterType(encounterType);
encounter.setEncounterProviders(new LinkedHashSet<EncounterProvider>());
encounter.getEncounterProviders().add(encounterProvider);
visit.addEncounter(encounter);
UiUtils uiUtils = new TestUiUtils(administrationService);
VisitDetailsFragmentController controller = new VisitDetailsFragmentController();
SimpleObject response = controller.getVisitDetails(administrationService, visit, uiUtils, emrContext);
List<SimpleObject> actualEncounters = (List<SimpleObject>) response.get("encounters");
SimpleObject actualEncounter = actualEncounters.get(0);
assertThat(response.get("startDatetime"), notNullValue());
assertThat(response.get("stopDatetime"), notNullValue());
assertThat((String) response.get("location"), is("Visit Location"));
assertThat(actualEncounters.size(), is(1));
assertThat((Integer) actualEncounter.get("encounterId"), is(7));
assertThat((String) actualEncounter.get("location"), is("Location"));
assertThat((SimpleObject) actualEncounter.get("encounterType"), isSimpleObjectWith("uuid", encounterType.getUuid(), "name", encounterType.getName()));
assertThat(actualEncounter.get("encounterDatetime"), notNullValue());
assertThat(actualEncounter.get("encounterDate"), notNullValue());
assertThat(actualEncounter.get("encounterTime"), notNullValue());
List<SimpleObject> actualProviders = (List<SimpleObject>) actualEncounter.get("encounterProviders");
assertThat(actualProviders.size(), is(1));
assertThat((String) actualProviders.get(0).get("provider"), is("Provider"));
}
| public void shouldReturnEncountersForVisit() throws ParseException {
EmrContext emrContext = mock(EmrContext.class);
UserContext userContext = mock(UserContext.class);
User authenticatedUser = new User();
when(userContext.getAuthenticatedUser()).thenReturn(authenticatedUser);
when(emrContext.getUserContext()).thenReturn(userContext);
AdministrationService administrationService = mock(AdministrationService.class);
when(administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT)).thenReturn("dd.MMM.yyyy, HH:mm:ss");
Visit visit = new Visit();
Location visitLocation = new Location();
visitLocation.setName("Visit Location");
visit.setLocation(visitLocation);
visit.setStartDatetime(new Date());
visit.setStopDatetime(new Date());
Location encounterLocation = new Location();
encounterLocation.setName("Location");
EncounterType encounterType = new EncounterType();
encounterType.setName("Encounter Type");
encounterType.setUuid("abc-123-def-456");
Provider provider = new Provider();
provider.setName("Provider");
EncounterProvider encounterProvider = new EncounterProvider();
encounterProvider.setProvider(provider);
encounterProvider.setEncounterRole(new EncounterRole());
Encounter encounter = new Encounter();
encounter.setEncounterId(7);
encounter.setEncounterDatetime(new Date());
encounter.setLocation(encounterLocation);
encounter.setEncounterType(encounterType);
encounter.setEncounterProviders(new LinkedHashSet<EncounterProvider>());
encounter.getEncounterProviders().add(encounterProvider);
encounter.setCreator(authenticatedUser);
visit.addEncounter(encounter);
UiUtils uiUtils = new TestUiUtils(administrationService);
VisitDetailsFragmentController controller = new VisitDetailsFragmentController();
SimpleObject response = controller.getVisitDetails(administrationService, visit, uiUtils, emrContext);
List<SimpleObject> actualEncounters = (List<SimpleObject>) response.get("encounters");
SimpleObject actualEncounter = actualEncounters.get(0);
assertThat(response.get("startDatetime"), notNullValue());
assertThat(response.get("stopDatetime"), notNullValue());
assertThat((String) response.get("location"), is("Visit Location"));
assertThat(actualEncounters.size(), is(1));
assertThat((Integer) actualEncounter.get("encounterId"), is(7));
assertThat((String) actualEncounter.get("location"), is("Location"));
assertThat((SimpleObject) actualEncounter.get("encounterType"), isSimpleObjectWith("uuid", encounterType.getUuid(), "name", encounterType.getName()));
assertThat(actualEncounter.get("encounterDatetime"), notNullValue());
assertThat(actualEncounter.get("encounterDate"), notNullValue());
assertThat(actualEncounter.get("encounterTime"), notNullValue());
List<SimpleObject> actualProviders = (List<SimpleObject>) actualEncounter.get("encounterProviders");
assertThat(actualProviders.size(), is(1));
assertThat((String) actualProviders.get(0).get("provider"), is("Provider"));
}
|
diff --git a/src/main/java/com/cloudera/crunch/io/seq/SeqFileTableReaderFactory.java b/src/main/java/com/cloudera/crunch/io/seq/SeqFileTableReaderFactory.java
index 52179a33..06c68063 100644
--- a/src/main/java/com/cloudera/crunch/io/seq/SeqFileTableReaderFactory.java
+++ b/src/main/java/com/cloudera/crunch/io/seq/SeqFileTableReaderFactory.java
@@ -1,93 +1,97 @@
/**
* Copyright (c) 2011, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. 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
*
* This software 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.cloudera.crunch.io.seq;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import com.cloudera.crunch.MapFn;
import com.cloudera.crunch.Pair;
import com.cloudera.crunch.io.FileReaderFactory;
import com.cloudera.crunch.type.PTableType;
import com.cloudera.crunch.type.PType;
import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
public class SeqFileTableReaderFactory<K, V> implements FileReaderFactory<Pair<K, V>> {
private static final Log LOG = LogFactory.getLog(SeqFileTableReaderFactory.class);
private final MapFn<Object, K> keyMapFn;
private final MapFn<Object, V> valueMapFn;
private final Writable key;
private final Writable value;
private final Configuration conf;
public SeqFileTableReaderFactory(PTableType<K, V> tableType, Configuration conf) {
PType<K> keyType = tableType.getKeyType();
PType<V> valueType = tableType.getValueType();
this.keyMapFn = SeqFileHelper.getInputMapFn(keyType);
this.valueMapFn = SeqFileHelper.getInputMapFn(valueType);
this.key = SeqFileHelper.newInstance(keyType, conf);
this.value = SeqFileHelper.newInstance(valueType, conf);
this.conf = conf;
}
@Override
public Iterator<Pair<K, V>> read(FileSystem fs, final Path path) {
+ keyMapFn.setConfigurationForTest(conf);
+ keyMapFn.initialize();
+ valueMapFn.setConfigurationForTest(conf);
+ valueMapFn.initialize();
try {
final SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
return new UnmodifiableIterator<Pair<K, V>>() {
boolean nextChecked = false;
boolean hasNext = false;
@Override
public boolean hasNext() {
if (nextChecked == true) {
return hasNext;
}
try {
hasNext = reader.next(key, value);
nextChecked = true;
return hasNext;
} catch (IOException e) {
LOG.info("Error reading from path: " + path, e);
return false;
}
}
@Override
public Pair<K, V> next() {
if (!nextChecked && !hasNext()) {
return null;
}
nextChecked = false;
return Pair.of(keyMapFn.map(key), valueMapFn.map(value));
}
};
} catch (IOException e) {
LOG.info("Could not read seqfile at path: " + path, e);
return Iterators.emptyIterator();
}
}
}
| true | true | public Iterator<Pair<K, V>> read(FileSystem fs, final Path path) {
try {
final SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
return new UnmodifiableIterator<Pair<K, V>>() {
boolean nextChecked = false;
boolean hasNext = false;
@Override
public boolean hasNext() {
if (nextChecked == true) {
return hasNext;
}
try {
hasNext = reader.next(key, value);
nextChecked = true;
return hasNext;
} catch (IOException e) {
LOG.info("Error reading from path: " + path, e);
return false;
}
}
@Override
public Pair<K, V> next() {
if (!nextChecked && !hasNext()) {
return null;
}
nextChecked = false;
return Pair.of(keyMapFn.map(key), valueMapFn.map(value));
}
};
} catch (IOException e) {
LOG.info("Could not read seqfile at path: " + path, e);
return Iterators.emptyIterator();
}
}
| public Iterator<Pair<K, V>> read(FileSystem fs, final Path path) {
keyMapFn.setConfigurationForTest(conf);
keyMapFn.initialize();
valueMapFn.setConfigurationForTest(conf);
valueMapFn.initialize();
try {
final SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
return new UnmodifiableIterator<Pair<K, V>>() {
boolean nextChecked = false;
boolean hasNext = false;
@Override
public boolean hasNext() {
if (nextChecked == true) {
return hasNext;
}
try {
hasNext = reader.next(key, value);
nextChecked = true;
return hasNext;
} catch (IOException e) {
LOG.info("Error reading from path: " + path, e);
return false;
}
}
@Override
public Pair<K, V> next() {
if (!nextChecked && !hasNext()) {
return null;
}
nextChecked = false;
return Pair.of(keyMapFn.map(key), valueMapFn.map(value));
}
};
} catch (IOException e) {
LOG.info("Could not read seqfile at path: " + path, e);
return Iterators.emptyIterator();
}
}
|
diff --git a/source/main/org/freecompany/redline/DumpPayload.java b/source/main/org/freecompany/redline/DumpPayload.java
index fc022a5..542a032 100644
--- a/source/main/org/freecompany/redline/DumpPayload.java
+++ b/source/main/org/freecompany/redline/DumpPayload.java
@@ -1,19 +1,19 @@
package org.freecompany.redline;
import org.freecompany.redline.header.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class DumpPayload {
public static void main( String[] args) throws Exception {
ReadableByteChannel in = Channels.newChannel( System.in);
- Format format = new Scanner().run( in);
+ Format format = new Scanner().run( new ReadableChannelWrapper( in));
FileChannel out = new FileOutputStream( args[ 0]).getChannel();
long position = 0;
long read;
while (( read = out.transferFrom( in, position, 1024)) > 0) position += read;
}
}
| true | true | public static void main( String[] args) throws Exception {
ReadableByteChannel in = Channels.newChannel( System.in);
Format format = new Scanner().run( in);
FileChannel out = new FileOutputStream( args[ 0]).getChannel();
long position = 0;
long read;
while (( read = out.transferFrom( in, position, 1024)) > 0) position += read;
}
| public static void main( String[] args) throws Exception {
ReadableByteChannel in = Channels.newChannel( System.in);
Format format = new Scanner().run( new ReadableChannelWrapper( in));
FileChannel out = new FileOutputStream( args[ 0]).getChannel();
long position = 0;
long read;
while (( read = out.transferFrom( in, position, 1024)) > 0) position += read;
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/WebViewActivity.java b/MPDroid/src/com/namelessdev/mpdroid/WebViewActivity.java
index aadadf19..387d3391 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/WebViewActivity.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/WebViewActivity.java
@@ -1,24 +1,25 @@
package com.namelessdev.mpdroid;
import android.os.Bundle;
import android.webkit.WebView;
import com.actionbarsherlock.app.SherlockActivity;
public class WebViewActivity extends SherlockActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.donate);
WebView webview = new WebView(this);
+ webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
this.setContentView(webview);
final String url = getIntent().getStringExtra("url");
if (url != null) {
webview.loadUrl(url);
} else {
// Defaut on the what's new page
webview.loadUrl("http://nlss.fr/mpdroid/donate.html");
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.donate);
WebView webview = new WebView(this);
this.setContentView(webview);
final String url = getIntent().getStringExtra("url");
if (url != null) {
webview.loadUrl(url);
} else {
// Defaut on the what's new page
webview.loadUrl("http://nlss.fr/mpdroid/donate.html");
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.donate);
WebView webview = new WebView(this);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
this.setContentView(webview);
final String url = getIntent().getStringExtra("url");
if (url != null) {
webview.loadUrl(url);
} else {
// Defaut on the what's new page
webview.loadUrl("http://nlss.fr/mpdroid/donate.html");
}
}
|
diff --git a/src/net/rptools/maptool/client/functions/TokenPropertyFunctions.java b/src/net/rptools/maptool/client/functions/TokenPropertyFunctions.java
index 8cb694b9..4e295ba9 100644
--- a/src/net/rptools/maptool/client/functions/TokenPropertyFunctions.java
+++ b/src/net/rptools/maptool/client/functions/TokenPropertyFunctions.java
@@ -1,896 +1,896 @@
package net.rptools.maptool.client.functions;
import java.awt.Image;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.MapToolVariableResolver;
import net.rptools.maptool.client.ui.zone.ZoneRenderer;
import net.rptools.maptool.language.I18N;
import net.rptools.maptool.model.GUID;
import net.rptools.maptool.model.Grid;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.TokenFootprint;
import net.rptools.maptool.model.TokenProperty;
import net.rptools.maptool.model.Zone;
import net.rptools.maptool.util.ImageManager;
import net.rptools.maptool.util.TokenUtil;
import net.rptools.parser.Parser;
import net.rptools.parser.ParserException;
import net.rptools.parser.function.AbstractFunction;
import net.sf.json.JSONArray;
public class TokenPropertyFunctions extends AbstractFunction {
private static final TokenPropertyFunctions instance =
new TokenPropertyFunctions();
private TokenPropertyFunctions() {
super(0, 4, "getPropertyNames", "getAllPropertyNames", "getPropertyNamesRaw",
"hasProperty",
"isNPC", "isPC", "setPC", "setNPC", "getLayer", "setLayer",
"getSize", "setSize", "getOwners", "isOwnedByAll", "isOwner",
"resetProperty", "getProperty", "setProperty", "isPropertyEmpty",
"getPropertyDefault", "sendToBack", "bringToFront",
"getLibProperty", "setLibProperty", "getLibPropertyNames",
"setPropertyType", "getPropertyType",
"getRawProperty", "getTokenFacing", "setTokenFacing", "removeTokenFacing",
"getMatchingProperties", "getMatchingLibProperties", "isSnapToGrid",
"setOwner");
}
public static TokenPropertyFunctions getInstance() {
return instance;
}
@Override
public Object childEvaluate(Parser parser, String functionName,
List<Object> parameters) throws ParserException {
MapToolVariableResolver resolver =
(MapToolVariableResolver) parser.getVariableResolver();
// Cached for all those putToken() calls that are needed
ZoneRenderer zoneR = MapTool.getFrame().getCurrentZoneRenderer();
Zone zone = zoneR.getZone();
/*
* String type = getPropertyType()
*/
if (functionName.equals("getPropertyType")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getPropertyType", parameters, 0);
return token.getPropertyType();
}
/*
* String empty = setPropertyType(String propTypeName)
*/
if (functionName.equals("setPropertyType")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setPropertyType", parameters, 1);
token.setPropertyType(parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token); // FJE Should this be here? Added because other places have it...?!
return "";
}
/*
* String names = getPropertyNames(String delim: ",")
*/
if (functionName.equals("getPropertyNames") || functionName.equals("getPropertyNamesRaw")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, functionName, parameters, 1);
String delim = parameters.size() > 0 ? parameters.get(0).toString() : ",";
String pattern = ".*";
return getPropertyNames(token, delim, pattern, functionName.equals("getPropertyNamesRaw"));
}
/*
* String names = getMatchingProperties(String pattern, String delim: ",", String tokenId: currentToken())
*/
if (functionName.equals("getMatchingProperties")) {
Token token = getTokenFromParam(resolver, "getMatchingProperties", parameters, 2);
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
}
else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String pattern = parameters.get(0).toString();
String delim = parameters.size() > 1 ? parameters.get(1).toString() : ",";
return getPropertyNames(token, delim, pattern, false);
}
/*
* String names = getAllPropertyNames(String propType: "", String delim: ",")
*/
if (functionName.equals("getAllPropertyNames")) {
if (parameters.size() < 1) {
return getAllPropertyNames(null, ",");
} else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
} else {
return getAllPropertyNames(parameters.get(0).toString(), parameters.size() > 1 ? parameters.get(1).toString() : ",");
}
}
/*
* Number zeroOne = hasProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("hasProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "hasProperty", parameters, 1);
return hasProperty(token, parameters.get(0).toString()) ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isNPC(String tokenId: currentToken())
*/
if (functionName.equals("isNPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isNPC", parameters, 0);
return token.getType() == Token.Type.NPC ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isPC(String tokenId: currentToken())
*/
if (functionName.equals("isPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isPC", parameters, 0);
return token.getType() == Token.Type.PC ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* String empty = setPC(String tokenId: currentToken())
*/
if (functionName.equals("setPC")) {
- if (parameters.size() != 1) {
- throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
+ if (parameters.size() > 1) {
+ throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setPC", parameters, 0);
token.setType(Token.Type.PC);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return "";
}
/*
* String empty = setNPC(String tokenId: currentToken())
*/
if (functionName.equals("setNPC")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setNPC", parameters, 0);
token.setType(Token.Type.NPC);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return "";
}
/*
* String layer = getLayer(String tokenId: currentToken())
*/
if (functionName.equals("getLayer")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getLayer", parameters, 0);
return token.getLayer().name();
}
/*
* String layer = setLayer(String layer, String tokenId: currentToken())
*/
if (functionName.equals("setLayer")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setLayer", parameters, 1);
String layer = setLayer(token, parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return layer;
}
/*
* String size = getSize(String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("getSize")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getSize", parameters, 0);
return getSize(token);
}
/*
* String size = setSize(String size, String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("setSize")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setSize", parameters, 1);
return setSize(token, parameters.get(0).toString());
}
/*
* String owners = getOwners(String delim: ",", String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("getOwners")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getOwners", parameters, 1);
return getOwners(token, parameters.size() > 0 ? parameters.get(0).toString() : ",");
}
/*
* Number zeroOne = isOwnedByAll(String tokenId: currentToken())
*/
if (functionName.equals("isOwnedByAll")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isOwnedByAll", parameters, 0);
return token.isOwnedByAll() ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isOwner(String player: self, String tokenId: currentToken())
*/
if (functionName.equals("isOwner")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isOwner", parameters, 1);
if (parameters.size() > 0) {
return token.isOwner(parameters.get(0).toString());
}
return token.isOwner(MapTool.getPlayer().getName()) ? BigDecimal.ONE : BigDecimal.ZERO ;
}
/*
* String empty = resetProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("resetProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "resetProperty", parameters, 1);
token.resetProperty(parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return "";
}
/*
* String empty = setProperty(String propName, String value, String tokenId: currentToken())
*/
if (functionName.equals("setProperty")) {
if (parameters.size() < 2) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 2, parameters.size()));
} else
if (parameters.size() > 3) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 3, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setProperty", parameters, 2);
token.setProperty(parameters.get(0).toString(), parameters.get(1).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return "";
}
/*
* {String|Number} value = getRawProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("getRawProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getRawProperty", parameters, 1);
Object val = token.getProperty(parameters.get(0).toString());
if (val == null) {
return "";
}
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString()); // XXX Localization here?
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* {String|Number} value = getProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("getProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getProperty", parameters, 1);
Object val = token.getEvaluatedProperty(parameters.get(0).toString());
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString());
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* Number zeroOne = isPropertyEmpty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("isPropertyEmpty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isPropertyEmpty", parameters, 1);
return token.getProperty(parameters.get(0).toString()) == null ? BigDecimal.ONE : BigDecimal.ZERO;
}
/* pre 1.3.b64 only took a single parameter
*
* Number zeroOne = getPropertyDefault(String propName, String propType: currentToken().getPropertyType())
*/
if (functionName.equals("getPropertyDefault")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = resolver.getTokenInContext();
String name = parameters.get(0).toString();
String propType = parameters.size() > 1 ? parameters.get(1).toString() : token.getPropertyType();
Object val = null;
List<TokenProperty> propertyList = MapTool.getCampaign().getCampaignProperties().getTokenPropertyList(propType);
if (propertyList != null) {
for (TokenProperty property : propertyList) {
if (name.equalsIgnoreCase(property.getName())) {
val = property.getDefaultValue();
break;
}
}
}
if (val == null) {
return "";
}
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString());
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* String empty = bringToFront(String tokenId: currentToken())
*/
if (functionName.equals("bringToFront")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Set<GUID> tokens = new HashSet<GUID>();
Token token = getTokenFromParam(resolver, "bringToFront", parameters, 0);
tokens.add(token.getId());
MapTool.serverCommand().bringTokensToFront(zone.getId(), tokens);
return "";
}
/*
* String empty = sendToBack(String tokenId: currentToken())
*/
if (functionName.equals("sendToBack")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Set<GUID> tokens = new HashSet<GUID>();
Token token = getTokenFromParam(resolver, "sendToBack", parameters, 0);
tokens.add(token.getId());
MapTool.serverCommand().sendTokensToBack(zone.getId(), tokens);
return "";
}
/*
* String value = getLibProperty(String propName, String tokenId: macroSource)
*/
if (functionName.equals("getLibProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
if (parameters.size() > 1) {
location = parameters.get(1).toString();
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
Object val = token.getProperty(parameters.get(0).toString());
// Attempt to convert to a number ...
try {
val = new BigDecimal(val.toString());
} catch (Exception e) {
// Ignore, use previous value of "val"
}
return val == null ? "" : val;
}
/*
* String empty = setLibProperty(String propName, String value, String tokenId: macroSource)
*/
if (functionName.equals("setLibProperty")) {
if (parameters.size() < 2) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 2, parameters.size()));
} else
if (parameters.size() > 3) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 3, parameters.size()));
}
String location;
if (parameters.size() > 2) {
location = parameters.get(2).toString();
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
token.setProperty(parameters.get(0).toString(), parameters.get(1).toString());
Zone z = MapTool.getParser().getTokenMacroLibZone(location);
MapTool.serverCommand().putToken(z.getId(), token);
return "";
}
/*
* String names = getLibPropertyNames(String tokenId: {macroSource | "*" | "this"}, String delim: ",")
*/
if (functionName.equals("getLibPropertyNames")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
if (parameters.size() > 0) {
location = parameters.get(0).toString();
if (location.equals("*") || location.equalsIgnoreCase("this")) {
location = MapTool.getParser().getMacroSource();
}
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLibToken", functionName, location));
}
String delim = parameters.size() > 1 ? parameters.get(1).toString() : ",";
return getPropertyNames(token, delim, ".*", false);
}
/*
* String names = getMatchingLibProperties(String pattern, String tokenId: {macroSource | "*" | "this"}, String delim: ",")
*/
if (functionName.equals("getMatchingLibProperties")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
String pattern = parameters.get(0).toString();
if (parameters.size() > 1) {
location = parameters.get(1).toString();
if (location.equals("*") || location.equalsIgnoreCase("this")) {
location = MapTool.getParser().getMacroSource();
}
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLibToken", functionName, location));
}
String delim = parameters.size() > 2 ? parameters.get(2).toString() : ",";
return getPropertyNames(token, delim, pattern, false);
}
/*
* Number facing = getTokenFacing(String tokenId: currentToken())
*/
if (functionName.equals("getTokenFacing")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 0);
if (token.getFacing() == null) {
return ""; // XXX Should be -1 instead of a string?
}
return BigDecimal.valueOf(token.getFacing());
}
/*
* String empty = setTokenFacing(Number facing, String tokenId: currentToken())
*/
if (functionName.equals("setTokenFacing")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
if (!(parameters.get(0) instanceof BigDecimal)) {
throw new ParserException(I18N.getText("macro.function.general.argumentTypeN", functionName,1));
}
Token token = getTokenFromParam(resolver, "setTokenFacing", parameters, 1);
token.setFacing(((BigDecimal)parameters.get(0)).intValue());
MapTool.serverCommand().putToken(zone.getId(), token);
zoneR.flushLight(); // FJE This isn't needed unless the token had a light source, right? Should we check for that?
zone.putToken(token);
return "";
}
/*
* String empty = removeTokenFacing(String tokenId: currentToken())
*/
if (functionName.equals("removeTokenFacing")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "removeTokenFacing", parameters, 0);
token.setFacing(null);
MapTool.serverCommand().putToken(zone.getId(), token);
zoneR.flushLight();
zone.putToken(token);
return "";
}
/*
* Number zeroOne = isSnapToGrid(String tokenId: currentToken())
*/
if (functionName.equals("isSnapToGrid")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 0);
return token.isSnapToGrid() ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* String empty = setOwner(String playerName | JSONArray playerNames, String tokenId: currentToken())
*/
if (functionName.equals("setOwner")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 1);
// Remove current owners
token.clearAllOwners();
if (parameters.get(0).equals("")) {
return "";
}
Object json = JSONMacroFunctions.asJSON(parameters.get(0));
if (json != null && json instanceof JSONArray) {
for (Object o : (JSONArray)json) {
token.addOwner(o.toString());
}
} else {
token.addOwner(parameters.get(0).toString());
}
return "";
}
throw new ParserException(I18N.getText("macro.function.general.unknownFunction", functionName));
}
/**
* Gets the size of the token.
* @param token The token to get the size of.
* @return the size of the token.
*/
private String getSize(Token token) {
Grid grid = MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid();
for (TokenFootprint footprint : grid.getFootprints()) {
if (token.isSnapToScale() && token.getFootprint(grid) == footprint) {
return footprint.getName();
}
}
return "";
}
/**
* Sets the size of the token.
* @param token The token to set the size of.
* @param size The size to set the token to.
* @return The new size of the token.
* @throws ParserException if the size specified is an invalid size.
*/
private String setSize(Token token, String size) throws ParserException {
ZoneRenderer renderer = MapTool.getFrame().getCurrentZoneRenderer();
Zone zone = renderer.getZone();
Grid grid = zone.getGrid();
for (TokenFootprint footprint : grid.getFootprints()) {
if (token.isSnapToScale() && footprint.getName().equalsIgnoreCase(size)) {
token.setFootprint(grid, footprint);
token.setSnapToScale(true);
renderer.flush(token);
// XXX Why is the putToken() called twice?
// MapTool.serverCommand().putToken(zone.getId(), token);
renderer.repaint();
MapTool.getFrame().updateTokenTree();
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return getSize(token);
}
}
throw new ParserException(I18N.getText("macro.function.tokenProperty.invalidSize", "setSize", size));
}
/**
* Sets the layer of the token.
* @param token The token to move to a different layer.
* @param layerName the name of the layer to move the token to.
* @return the name of the layer the token was moved to.
* @throws ParserException if the layer name is invalid.
*/
public String setLayer(Token token, String layerName) throws ParserException {
Zone.Layer layer;
if (layerName.equalsIgnoreCase(Zone.Layer.TOKEN.toString())) {
layer = Zone.Layer.TOKEN;
} else if (layerName.equalsIgnoreCase(Zone.Layer.BACKGROUND.toString())) {
layer = Zone.Layer.BACKGROUND;
} else if (layerName.equalsIgnoreCase("gm") || layerName.equalsIgnoreCase(Zone.Layer.GM.toString())) {
layer = Zone.Layer.GM;
} else if (layerName.equalsIgnoreCase(Zone.Layer.OBJECT.toString())) {
layer = Zone.Layer.OBJECT;
} else {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLayer", "setLayer", layerName));
}
token.setLayer(layer);
switch (layer) {
case BACKGROUND:
case OBJECT:
token.setShape(Token.TokenShape.TOP_DOWN);
break;
case GM:
case TOKEN:
Image image = ImageManager.getImage(token.getImageAssetId());
if (image == null || image == ImageManager.TRANSFERING_IMAGE) {
token.setShape(Token.TokenShape.TOP_DOWN);
} else {
token.setShape(TokenUtil.guessTokenType(image));
}
break;
}
return layerName;
}
/**
* Checks to see if the token has the specified property.
* @param token The token to check.
* @param name The name of the property to check.
* @return true if the token has the property.
*/
private boolean hasProperty(Token token, String name) {
Object val = token.getProperty(name);
if (val == null) {
return false;
}
if (val.toString().isEmpty()) {
return false;
}
return true;
}
/**
* Gets all the property names for the specified type.
* If type is null then all the property names for all types are returned.
* @param type The type of property.
* @param delim The list delimiter.
* @return a string list containing the property names.
* @throws ParserException
*/
private String getAllPropertyNames(String type, String delim) throws ParserException {
if (type == null || type.length() == 0 || type.equals("*")) {
Map<String, List<TokenProperty>> pmap =
MapTool.getCampaign().getCampaignProperties().getTokenTypeMap();
ArrayList<String> namesList = new ArrayList<String>();
for (Entry<String, List<TokenProperty>> entry : pmap.entrySet()) {
for (TokenProperty tp : entry.getValue()) {
namesList.add(tp.getName());
}
}
if ("json".equals(delim)) {
return JSONArray.fromObject(namesList).toString();
} else {
return StringFunctions.getInstance().join(namesList, delim);
}
} else {
List<TokenProperty> props = MapTool.getCampaign().getCampaignProperties().getTokenPropertyList(type);
if (props == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownPropType", "getAllPropertyNames", type));
}
ArrayList<String> namesList = new ArrayList<String>();
for (TokenProperty tp : props) {
namesList.add(tp.getName());
}
if ("json".equals(delim)) {
return JSONArray.fromObject(namesList).toString();
} else {
return StringFunctions.getInstance().join(namesList);
}
}
}
/**
* Creates a string list delimited by <b>delim</b> of the names of all the
* properties for a given token. Returned strings are all lowercase.
* @param token The token to get the property names for.
* @param delim The delimiter for the list.
* @param pattern The regexp pattern to match.
* @return the string list of property names.
*/
private String getPropertyNames(Token token, String delim, String pattern, boolean raw) {
List<String> namesList = new ArrayList<String>();
Pattern pat = Pattern.compile(pattern);
Set<String> propSet = (raw ? token.getPropertyNamesRaw() : token.getPropertyNames());
String[] propArray = new String[ propSet.size() ];
propSet.toArray(propArray);
Arrays.sort(propArray);
for (String name : propArray) {
Matcher m = pat.matcher(name);
if (m.matches()) {
namesList.add(name);
}
}
String[] names = new String[namesList.size()];
namesList.toArray(names);
if ("json".equals(delim)) {
return JSONArray.fromObject(names).toString();
} else {
return StringFunctions.getInstance().join(names, delim);
}
}
/**
* Gets the owners for the token.
* @param token The token to get the owners for.
* @param delim the delimiter for the list.
* @return a string list of the token owners.
*/
public String getOwners(Token token, String delim) {
String[] owners = new String[token.getOwners().size()];
token.getOwners().toArray(owners);
if ("json".endsWith(delim)) {
return JSONArray.fromObject(owners).toString();
} else {
return StringFunctions.getInstance().join(owners, delim);
}
}
/**
* Gets the token from the specified index or returns the token in context. This method
* will check the list size before trying to retrieve the token so it is safe to use
* for functions that have the token as a optional argument.
* @param res The variable resolver.
* @param functionName The function name (used for generating exception messages).
* @param param The parameters for the function.
* @param index The index to find the token at.
* @return the token.
* @throws ParserException if a token is specified but the macro is not trusted, or the
* specified token can not be found, or if no token is specified
* and no token is impersonated.
*/
private Token getTokenFromParam(MapToolVariableResolver res, String functionName, List<Object> param, int index) throws ParserException {
Token token;
if (param.size() > index) {
if (!MapTool.getParser().isMacroTrusted()) {
throw new ParserException(I18N.getText("macro.function.general.noPermOther", functionName));
}
token = FindTokenFunctions.findToken(param.get(index).toString(), null);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.general.unknownToken", functionName, param.get(index)));
}
} else {
token = res.getTokenInContext();
if (token == null) {
throw new ParserException(I18N.getText("macro.function.general.noImpersonated", functionName));
}
}
return token;
}
}
| true | true | public Object childEvaluate(Parser parser, String functionName,
List<Object> parameters) throws ParserException {
MapToolVariableResolver resolver =
(MapToolVariableResolver) parser.getVariableResolver();
// Cached for all those putToken() calls that are needed
ZoneRenderer zoneR = MapTool.getFrame().getCurrentZoneRenderer();
Zone zone = zoneR.getZone();
/*
* String type = getPropertyType()
*/
if (functionName.equals("getPropertyType")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getPropertyType", parameters, 0);
return token.getPropertyType();
}
/*
* String empty = setPropertyType(String propTypeName)
*/
if (functionName.equals("setPropertyType")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setPropertyType", parameters, 1);
token.setPropertyType(parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token); // FJE Should this be here? Added because other places have it...?!
return "";
}
/*
* String names = getPropertyNames(String delim: ",")
*/
if (functionName.equals("getPropertyNames") || functionName.equals("getPropertyNamesRaw")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, functionName, parameters, 1);
String delim = parameters.size() > 0 ? parameters.get(0).toString() : ",";
String pattern = ".*";
return getPropertyNames(token, delim, pattern, functionName.equals("getPropertyNamesRaw"));
}
/*
* String names = getMatchingProperties(String pattern, String delim: ",", String tokenId: currentToken())
*/
if (functionName.equals("getMatchingProperties")) {
Token token = getTokenFromParam(resolver, "getMatchingProperties", parameters, 2);
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
}
else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String pattern = parameters.get(0).toString();
String delim = parameters.size() > 1 ? parameters.get(1).toString() : ",";
return getPropertyNames(token, delim, pattern, false);
}
/*
* String names = getAllPropertyNames(String propType: "", String delim: ",")
*/
if (functionName.equals("getAllPropertyNames")) {
if (parameters.size() < 1) {
return getAllPropertyNames(null, ",");
} else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
} else {
return getAllPropertyNames(parameters.get(0).toString(), parameters.size() > 1 ? parameters.get(1).toString() : ",");
}
}
/*
* Number zeroOne = hasProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("hasProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "hasProperty", parameters, 1);
return hasProperty(token, parameters.get(0).toString()) ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isNPC(String tokenId: currentToken())
*/
if (functionName.equals("isNPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isNPC", parameters, 0);
return token.getType() == Token.Type.NPC ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isPC(String tokenId: currentToken())
*/
if (functionName.equals("isPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isPC", parameters, 0);
return token.getType() == Token.Type.PC ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* String empty = setPC(String tokenId: currentToken())
*/
if (functionName.equals("setPC")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setPC", parameters, 0);
token.setType(Token.Type.PC);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return "";
}
/*
* String empty = setNPC(String tokenId: currentToken())
*/
if (functionName.equals("setNPC")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setNPC", parameters, 0);
token.setType(Token.Type.NPC);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return "";
}
/*
* String layer = getLayer(String tokenId: currentToken())
*/
if (functionName.equals("getLayer")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getLayer", parameters, 0);
return token.getLayer().name();
}
/*
* String layer = setLayer(String layer, String tokenId: currentToken())
*/
if (functionName.equals("setLayer")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setLayer", parameters, 1);
String layer = setLayer(token, parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return layer;
}
/*
* String size = getSize(String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("getSize")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getSize", parameters, 0);
return getSize(token);
}
/*
* String size = setSize(String size, String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("setSize")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setSize", parameters, 1);
return setSize(token, parameters.get(0).toString());
}
/*
* String owners = getOwners(String delim: ",", String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("getOwners")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getOwners", parameters, 1);
return getOwners(token, parameters.size() > 0 ? parameters.get(0).toString() : ",");
}
/*
* Number zeroOne = isOwnedByAll(String tokenId: currentToken())
*/
if (functionName.equals("isOwnedByAll")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isOwnedByAll", parameters, 0);
return token.isOwnedByAll() ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isOwner(String player: self, String tokenId: currentToken())
*/
if (functionName.equals("isOwner")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isOwner", parameters, 1);
if (parameters.size() > 0) {
return token.isOwner(parameters.get(0).toString());
}
return token.isOwner(MapTool.getPlayer().getName()) ? BigDecimal.ONE : BigDecimal.ZERO ;
}
/*
* String empty = resetProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("resetProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "resetProperty", parameters, 1);
token.resetProperty(parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return "";
}
/*
* String empty = setProperty(String propName, String value, String tokenId: currentToken())
*/
if (functionName.equals("setProperty")) {
if (parameters.size() < 2) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 2, parameters.size()));
} else
if (parameters.size() > 3) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 3, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setProperty", parameters, 2);
token.setProperty(parameters.get(0).toString(), parameters.get(1).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return "";
}
/*
* {String|Number} value = getRawProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("getRawProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getRawProperty", parameters, 1);
Object val = token.getProperty(parameters.get(0).toString());
if (val == null) {
return "";
}
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString()); // XXX Localization here?
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* {String|Number} value = getProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("getProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getProperty", parameters, 1);
Object val = token.getEvaluatedProperty(parameters.get(0).toString());
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString());
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* Number zeroOne = isPropertyEmpty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("isPropertyEmpty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isPropertyEmpty", parameters, 1);
return token.getProperty(parameters.get(0).toString()) == null ? BigDecimal.ONE : BigDecimal.ZERO;
}
/* pre 1.3.b64 only took a single parameter
*
* Number zeroOne = getPropertyDefault(String propName, String propType: currentToken().getPropertyType())
*/
if (functionName.equals("getPropertyDefault")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = resolver.getTokenInContext();
String name = parameters.get(0).toString();
String propType = parameters.size() > 1 ? parameters.get(1).toString() : token.getPropertyType();
Object val = null;
List<TokenProperty> propertyList = MapTool.getCampaign().getCampaignProperties().getTokenPropertyList(propType);
if (propertyList != null) {
for (TokenProperty property : propertyList) {
if (name.equalsIgnoreCase(property.getName())) {
val = property.getDefaultValue();
break;
}
}
}
if (val == null) {
return "";
}
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString());
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* String empty = bringToFront(String tokenId: currentToken())
*/
if (functionName.equals("bringToFront")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Set<GUID> tokens = new HashSet<GUID>();
Token token = getTokenFromParam(resolver, "bringToFront", parameters, 0);
tokens.add(token.getId());
MapTool.serverCommand().bringTokensToFront(zone.getId(), tokens);
return "";
}
/*
* String empty = sendToBack(String tokenId: currentToken())
*/
if (functionName.equals("sendToBack")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Set<GUID> tokens = new HashSet<GUID>();
Token token = getTokenFromParam(resolver, "sendToBack", parameters, 0);
tokens.add(token.getId());
MapTool.serverCommand().sendTokensToBack(zone.getId(), tokens);
return "";
}
/*
* String value = getLibProperty(String propName, String tokenId: macroSource)
*/
if (functionName.equals("getLibProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
if (parameters.size() > 1) {
location = parameters.get(1).toString();
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
Object val = token.getProperty(parameters.get(0).toString());
// Attempt to convert to a number ...
try {
val = new BigDecimal(val.toString());
} catch (Exception e) {
// Ignore, use previous value of "val"
}
return val == null ? "" : val;
}
/*
* String empty = setLibProperty(String propName, String value, String tokenId: macroSource)
*/
if (functionName.equals("setLibProperty")) {
if (parameters.size() < 2) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 2, parameters.size()));
} else
if (parameters.size() > 3) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 3, parameters.size()));
}
String location;
if (parameters.size() > 2) {
location = parameters.get(2).toString();
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
token.setProperty(parameters.get(0).toString(), parameters.get(1).toString());
Zone z = MapTool.getParser().getTokenMacroLibZone(location);
MapTool.serverCommand().putToken(z.getId(), token);
return "";
}
/*
* String names = getLibPropertyNames(String tokenId: {macroSource | "*" | "this"}, String delim: ",")
*/
if (functionName.equals("getLibPropertyNames")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
if (parameters.size() > 0) {
location = parameters.get(0).toString();
if (location.equals("*") || location.equalsIgnoreCase("this")) {
location = MapTool.getParser().getMacroSource();
}
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLibToken", functionName, location));
}
String delim = parameters.size() > 1 ? parameters.get(1).toString() : ",";
return getPropertyNames(token, delim, ".*", false);
}
/*
* String names = getMatchingLibProperties(String pattern, String tokenId: {macroSource | "*" | "this"}, String delim: ",")
*/
if (functionName.equals("getMatchingLibProperties")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
String pattern = parameters.get(0).toString();
if (parameters.size() > 1) {
location = parameters.get(1).toString();
if (location.equals("*") || location.equalsIgnoreCase("this")) {
location = MapTool.getParser().getMacroSource();
}
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLibToken", functionName, location));
}
String delim = parameters.size() > 2 ? parameters.get(2).toString() : ",";
return getPropertyNames(token, delim, pattern, false);
}
/*
* Number facing = getTokenFacing(String tokenId: currentToken())
*/
if (functionName.equals("getTokenFacing")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 0);
if (token.getFacing() == null) {
return ""; // XXX Should be -1 instead of a string?
}
return BigDecimal.valueOf(token.getFacing());
}
/*
* String empty = setTokenFacing(Number facing, String tokenId: currentToken())
*/
if (functionName.equals("setTokenFacing")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
if (!(parameters.get(0) instanceof BigDecimal)) {
throw new ParserException(I18N.getText("macro.function.general.argumentTypeN", functionName,1));
}
Token token = getTokenFromParam(resolver, "setTokenFacing", parameters, 1);
token.setFacing(((BigDecimal)parameters.get(0)).intValue());
MapTool.serverCommand().putToken(zone.getId(), token);
zoneR.flushLight(); // FJE This isn't needed unless the token had a light source, right? Should we check for that?
zone.putToken(token);
return "";
}
/*
* String empty = removeTokenFacing(String tokenId: currentToken())
*/
if (functionName.equals("removeTokenFacing")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "removeTokenFacing", parameters, 0);
token.setFacing(null);
MapTool.serverCommand().putToken(zone.getId(), token);
zoneR.flushLight();
zone.putToken(token);
return "";
}
/*
* Number zeroOne = isSnapToGrid(String tokenId: currentToken())
*/
if (functionName.equals("isSnapToGrid")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 0);
return token.isSnapToGrid() ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* String empty = setOwner(String playerName | JSONArray playerNames, String tokenId: currentToken())
*/
if (functionName.equals("setOwner")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 1);
// Remove current owners
token.clearAllOwners();
if (parameters.get(0).equals("")) {
return "";
}
Object json = JSONMacroFunctions.asJSON(parameters.get(0));
if (json != null && json instanceof JSONArray) {
for (Object o : (JSONArray)json) {
token.addOwner(o.toString());
}
} else {
token.addOwner(parameters.get(0).toString());
}
return "";
}
throw new ParserException(I18N.getText("macro.function.general.unknownFunction", functionName));
}
| public Object childEvaluate(Parser parser, String functionName,
List<Object> parameters) throws ParserException {
MapToolVariableResolver resolver =
(MapToolVariableResolver) parser.getVariableResolver();
// Cached for all those putToken() calls that are needed
ZoneRenderer zoneR = MapTool.getFrame().getCurrentZoneRenderer();
Zone zone = zoneR.getZone();
/*
* String type = getPropertyType()
*/
if (functionName.equals("getPropertyType")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getPropertyType", parameters, 0);
return token.getPropertyType();
}
/*
* String empty = setPropertyType(String propTypeName)
*/
if (functionName.equals("setPropertyType")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setPropertyType", parameters, 1);
token.setPropertyType(parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token); // FJE Should this be here? Added because other places have it...?!
return "";
}
/*
* String names = getPropertyNames(String delim: ",")
*/
if (functionName.equals("getPropertyNames") || functionName.equals("getPropertyNamesRaw")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, functionName, parameters, 1);
String delim = parameters.size() > 0 ? parameters.get(0).toString() : ",";
String pattern = ".*";
return getPropertyNames(token, delim, pattern, functionName.equals("getPropertyNamesRaw"));
}
/*
* String names = getMatchingProperties(String pattern, String delim: ",", String tokenId: currentToken())
*/
if (functionName.equals("getMatchingProperties")) {
Token token = getTokenFromParam(resolver, "getMatchingProperties", parameters, 2);
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
}
else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String pattern = parameters.get(0).toString();
String delim = parameters.size() > 1 ? parameters.get(1).toString() : ",";
return getPropertyNames(token, delim, pattern, false);
}
/*
* String names = getAllPropertyNames(String propType: "", String delim: ",")
*/
if (functionName.equals("getAllPropertyNames")) {
if (parameters.size() < 1) {
return getAllPropertyNames(null, ",");
} else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
} else {
return getAllPropertyNames(parameters.get(0).toString(), parameters.size() > 1 ? parameters.get(1).toString() : ",");
}
}
/*
* Number zeroOne = hasProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("hasProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "hasProperty", parameters, 1);
return hasProperty(token, parameters.get(0).toString()) ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isNPC(String tokenId: currentToken())
*/
if (functionName.equals("isNPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isNPC", parameters, 0);
return token.getType() == Token.Type.NPC ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isPC(String tokenId: currentToken())
*/
if (functionName.equals("isPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isPC", parameters, 0);
return token.getType() == Token.Type.PC ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* String empty = setPC(String tokenId: currentToken())
*/
if (functionName.equals("setPC")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setPC", parameters, 0);
token.setType(Token.Type.PC);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return "";
}
/*
* String empty = setNPC(String tokenId: currentToken())
*/
if (functionName.equals("setNPC")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setNPC", parameters, 0);
token.setType(Token.Type.NPC);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return "";
}
/*
* String layer = getLayer(String tokenId: currentToken())
*/
if (functionName.equals("getLayer")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getLayer", parameters, 0);
return token.getLayer().name();
}
/*
* String layer = setLayer(String layer, String tokenId: currentToken())
*/
if (functionName.equals("setLayer")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setLayer", parameters, 1);
String layer = setLayer(token, parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
zoneR.flushLight();
MapTool.getFrame().updateTokenTree();
return layer;
}
/*
* String size = getSize(String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("getSize")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getSize", parameters, 0);
return getSize(token);
}
/*
* String size = setSize(String size, String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("setSize")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setSize", parameters, 1);
return setSize(token, parameters.get(0).toString());
}
/*
* String owners = getOwners(String delim: ",", String tokenId: currentToken())
*/
if (functionName.equalsIgnoreCase("getOwners")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getOwners", parameters, 1);
return getOwners(token, parameters.size() > 0 ? parameters.get(0).toString() : ",");
}
/*
* Number zeroOne = isOwnedByAll(String tokenId: currentToken())
*/
if (functionName.equals("isOwnedByAll")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isOwnedByAll", parameters, 0);
return token.isOwnedByAll() ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* Number zeroOne = isOwner(String player: self, String tokenId: currentToken())
*/
if (functionName.equals("isOwner")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isOwner", parameters, 1);
if (parameters.size() > 0) {
return token.isOwner(parameters.get(0).toString());
}
return token.isOwner(MapTool.getPlayer().getName()) ? BigDecimal.ONE : BigDecimal.ZERO ;
}
/*
* String empty = resetProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("resetProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "resetProperty", parameters, 1);
token.resetProperty(parameters.get(0).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return "";
}
/*
* String empty = setProperty(String propName, String value, String tokenId: currentToken())
*/
if (functionName.equals("setProperty")) {
if (parameters.size() < 2) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 2, parameters.size()));
} else
if (parameters.size() > 3) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 3, parameters.size()));
}
Token token = getTokenFromParam(resolver, "setProperty", parameters, 2);
token.setProperty(parameters.get(0).toString(), parameters.get(1).toString());
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
return "";
}
/*
* {String|Number} value = getRawProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("getRawProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getRawProperty", parameters, 1);
Object val = token.getProperty(parameters.get(0).toString());
if (val == null) {
return "";
}
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString()); // XXX Localization here?
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* {String|Number} value = getProperty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("getProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getProperty", parameters, 1);
Object val = token.getEvaluatedProperty(parameters.get(0).toString());
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString());
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* Number zeroOne = isPropertyEmpty(String propName, String tokenId: currentToken())
*/
if (functionName.equals("isPropertyEmpty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "isPropertyEmpty", parameters, 1);
return token.getProperty(parameters.get(0).toString()) == null ? BigDecimal.ONE : BigDecimal.ZERO;
}
/* pre 1.3.b64 only took a single parameter
*
* Number zeroOne = getPropertyDefault(String propName, String propType: currentToken().getPropertyType())
*/
if (functionName.equals("getPropertyDefault")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = resolver.getTokenInContext();
String name = parameters.get(0).toString();
String propType = parameters.size() > 1 ? parameters.get(1).toString() : token.getPropertyType();
Object val = null;
List<TokenProperty> propertyList = MapTool.getCampaign().getCampaignProperties().getTokenPropertyList(propType);
if (propertyList != null) {
for (TokenProperty property : propertyList) {
if (name.equalsIgnoreCase(property.getName())) {
val = property.getDefaultValue();
break;
}
}
}
if (val == null) {
return "";
}
if (val instanceof String) {
// try to convert to a number
try {
return new BigDecimal(val.toString());
} catch (Exception e) {
return val;
}
} else {
return val;
}
}
/*
* String empty = bringToFront(String tokenId: currentToken())
*/
if (functionName.equals("bringToFront")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Set<GUID> tokens = new HashSet<GUID>();
Token token = getTokenFromParam(resolver, "bringToFront", parameters, 0);
tokens.add(token.getId());
MapTool.serverCommand().bringTokensToFront(zone.getId(), tokens);
return "";
}
/*
* String empty = sendToBack(String tokenId: currentToken())
*/
if (functionName.equals("sendToBack")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Set<GUID> tokens = new HashSet<GUID>();
Token token = getTokenFromParam(resolver, "sendToBack", parameters, 0);
tokens.add(token.getId());
MapTool.serverCommand().sendTokensToBack(zone.getId(), tokens);
return "";
}
/*
* String value = getLibProperty(String propName, String tokenId: macroSource)
*/
if (functionName.equals("getLibProperty")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
if (parameters.size() > 1) {
location = parameters.get(1).toString();
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
Object val = token.getProperty(parameters.get(0).toString());
// Attempt to convert to a number ...
try {
val = new BigDecimal(val.toString());
} catch (Exception e) {
// Ignore, use previous value of "val"
}
return val == null ? "" : val;
}
/*
* String empty = setLibProperty(String propName, String value, String tokenId: macroSource)
*/
if (functionName.equals("setLibProperty")) {
if (parameters.size() < 2) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 2, parameters.size()));
} else
if (parameters.size() > 3) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 3, parameters.size()));
}
String location;
if (parameters.size() > 2) {
location = parameters.get(2).toString();
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
token.setProperty(parameters.get(0).toString(), parameters.get(1).toString());
Zone z = MapTool.getParser().getTokenMacroLibZone(location);
MapTool.serverCommand().putToken(z.getId(), token);
return "";
}
/*
* String names = getLibPropertyNames(String tokenId: {macroSource | "*" | "this"}, String delim: ",")
*/
if (functionName.equals("getLibPropertyNames")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
if (parameters.size() > 0) {
location = parameters.get(0).toString();
if (location.equals("*") || location.equalsIgnoreCase("this")) {
location = MapTool.getParser().getMacroSource();
}
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLibToken", functionName, location));
}
String delim = parameters.size() > 1 ? parameters.get(1).toString() : ",";
return getPropertyNames(token, delim, ".*", false);
}
/*
* String names = getMatchingLibProperties(String pattern, String tokenId: {macroSource | "*" | "this"}, String delim: ",")
*/
if (functionName.equals("getMatchingLibProperties")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
String location;
String pattern = parameters.get(0).toString();
if (parameters.size() > 1) {
location = parameters.get(1).toString();
if (location.equals("*") || location.equalsIgnoreCase("this")) {
location = MapTool.getParser().getMacroSource();
}
} else {
location = MapTool.getParser().getMacroSource();
}
Token token = MapTool.getParser().getTokenMacroLib(location);
if (token == null) {
throw new ParserException(I18N.getText("macro.function.tokenProperty.unknownLibToken", functionName, location));
}
String delim = parameters.size() > 2 ? parameters.get(2).toString() : ",";
return getPropertyNames(token, delim, pattern, false);
}
/*
* Number facing = getTokenFacing(String tokenId: currentToken())
*/
if (functionName.equals("getTokenFacing")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 0);
if (token.getFacing() == null) {
return ""; // XXX Should be -1 instead of a string?
}
return BigDecimal.valueOf(token.getFacing());
}
/*
* String empty = setTokenFacing(Number facing, String tokenId: currentToken())
*/
if (functionName.equals("setTokenFacing")) {
if (parameters.size() < 1) {
throw new ParserException(I18N.getText("macro.function.general.notEnoughParam", functionName, 1, parameters.size()));
} else
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
if (!(parameters.get(0) instanceof BigDecimal)) {
throw new ParserException(I18N.getText("macro.function.general.argumentTypeN", functionName,1));
}
Token token = getTokenFromParam(resolver, "setTokenFacing", parameters, 1);
token.setFacing(((BigDecimal)parameters.get(0)).intValue());
MapTool.serverCommand().putToken(zone.getId(), token);
zoneR.flushLight(); // FJE This isn't needed unless the token had a light source, right? Should we check for that?
zone.putToken(token);
return "";
}
/*
* String empty = removeTokenFacing(String tokenId: currentToken())
*/
if (functionName.equals("removeTokenFacing")) {
if (parameters.size() != 1) {
throw new ParserException(I18N.getText("macro.function.general.wrongNumParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "removeTokenFacing", parameters, 0);
token.setFacing(null);
MapTool.serverCommand().putToken(zone.getId(), token);
zoneR.flushLight();
zone.putToken(token);
return "";
}
/*
* Number zeroOne = isSnapToGrid(String tokenId: currentToken())
*/
if (functionName.equals("isSnapToGrid")) {
if (parameters.size() > 1) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 1, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 0);
return token.isSnapToGrid() ? BigDecimal.ONE : BigDecimal.ZERO;
}
/*
* String empty = setOwner(String playerName | JSONArray playerNames, String tokenId: currentToken())
*/
if (functionName.equals("setOwner")) {
if (parameters.size() > 2) {
throw new ParserException(I18N.getText("macro.function.general.tooManyParam", functionName, 2, parameters.size()));
}
Token token = getTokenFromParam(resolver, "getTokenFacing", parameters, 1);
// Remove current owners
token.clearAllOwners();
if (parameters.get(0).equals("")) {
return "";
}
Object json = JSONMacroFunctions.asJSON(parameters.get(0));
if (json != null && json instanceof JSONArray) {
for (Object o : (JSONArray)json) {
token.addOwner(o.toString());
}
} else {
token.addOwner(parameters.get(0).toString());
}
return "";
}
throw new ParserException(I18N.getText("macro.function.general.unknownFunction", functionName));
}
|
diff --git a/src/gov/nih/nci/cadsr/cdecurate/tool/DataElementConceptServlet.java b/src/gov/nih/nci/cadsr/cdecurate/tool/DataElementConceptServlet.java
index ac8f2f72..9340c592 100644
--- a/src/gov/nih/nci/cadsr/cdecurate/tool/DataElementConceptServlet.java
+++ b/src/gov/nih/nci/cadsr/cdecurate/tool/DataElementConceptServlet.java
@@ -1,2390 +1,2398 @@
package gov.nih.nci.cadsr.cdecurate.tool;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Vector;
import gov.nih.nci.cadsr.cdecurate.ui.AltNamesDefsSession;
import gov.nih.nci.cadsr.cdecurate.util.AdministeredItemUtil;
import gov.nih.nci.cadsr.cdecurate.util.DataManager;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import oracle.net.aso.e;
public class DataElementConceptServlet extends CurationServlet {
public DataElementConceptServlet() {
}
public DataElementConceptServlet(HttpServletRequest req, HttpServletResponse res,
ServletContext sc) {
super(req, res, sc);
}
public void execute(ACRequestTypes reqType) throws Exception {
switch (reqType){
case newDECFromMenu:
doOpenCreateNewPages();
break;
case newDECfromForm:
doCreateDECActions();
break;
case editDEC:
doEditDECActions();
break;
case createNewDEC:
doOpenCreateDECPage();
break;
case validateDECFromForm:
doInsertDEC();
break;
case viewDE_CONCEPT:
doOpenViewPage();
break;
}
}
/**
* The doOpenCreateNewPages method will set some session attributes then forward the request to a Create page.
* Called from 'service' method where reqType is 'newDEFromMenu', 'newDECFromMenu', 'newVDFromMenu' Sets some
* initial session attributes. Calls 'getAC.getACList' to get the Data list from the database for the selected
* context. Sets session Bean and forwards the create page for the selected component.
*
* @throws Exception
*/
private void doOpenCreateNewPages() throws Exception
{
HttpSession session = m_classReq.getSession();
clearSessionAttributes(m_classReq, m_classRes);
this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes);
String context = (String) session.getAttribute("sDefaultContext"); // from Login.jsp
DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, "nothing");
DataManager.setAttribute(session, "DDEAction", "nothing"); // reset from "CreateNewDEFComp"
DataManager.setAttribute(session, "sCDEAction", "nothing");
DataManager.setAttribute(session, "VDPageAction", "nothing");
DataManager.setAttribute(session, "DECPageAction", "nothing");
DataManager.setAttribute(session, "sDefaultContext", context);
this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes
DataManager.setAttribute(session, "originAction", "NewDECFromMenu");
DataManager.setAttribute(session, "LastMenuButtonPressed", "CreateDEC");
DEC_Bean m_DEC = new DEC_Bean();
m_DEC.setDEC_ASL_NAME("DRAFT NEW");
m_DEC.setAC_PREF_NAME_TYPE("SYS");
DataManager.setAttribute(session, "m_DEC", m_DEC);
DEC_Bean oldDEC = new DEC_Bean();
oldDEC.setDEC_ASL_NAME("DRAFT NEW");
oldDEC.setAC_PREF_NAME_TYPE("SYS");
DataManager.setAttribute(session, "oldDECBean", oldDEC);
EVS_Bean m_OC = new EVS_Bean();
DataManager.setAttribute(session, "m_OC", m_OC);
EVS_Bean m_PC = new EVS_Bean();
DataManager.setAttribute(session, "m_PC", m_PC);
EVS_Bean m_OCQ = new EVS_Bean();
DataManager.setAttribute(session, "m_OCQ", m_OCQ);
EVS_Bean m_PCQ = new EVS_Bean();
DataManager.setAttribute(session, "m_PCQ", m_PCQ);
DataManager.setAttribute(session, "selPropRow", "");
DataManager.setAttribute(session, "selPropQRow", "");
DataManager.setAttribute(session, "selObjQRow", "");
DataManager.setAttribute(session, "selObjRow", "");
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
} // end of doOpenCreateNewPages
/**
* The doCreateDECActions method handles CreateDEC or EditDEC actions of the request. Called from 'service' method
* where reqType is 'newDECfromForm' Calls 'doValidateDEC' if the action is Validate or submit. Calls
* 'doSuggestionDE' if the action is open EVS Window.
*
* @throws Exception
*/
private void doCreateDECActions() throws Exception
{
HttpSession session = m_classReq.getSession();
String sMenuAction = (String) m_classReq.getParameter("MenuAction");
if (sMenuAction != null)
DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction);
String sAction = (String) m_classReq.getParameter("pageAction");
DataManager.setAttribute(session, "DECPageAction", sAction); // store the page action in attribute
String sSubAction = (String) m_classReq.getParameter("DECAction");
DataManager.setAttribute(session, "DECAction", sSubAction);
String sOriginAction = (String) session.getAttribute("originAction");
/* if (sAction.equals("changeContext"))
doChangeContext(m_classReq, m_classRes, "dec");
else*/ if (sAction.equals("submit"))
doSubmitDEC();
else if (sAction.equals("validate"))
doValidateDEC();
else if (sAction.equals("suggestion"))
doSuggestionDE(m_classReq, m_classRes);
else if (sAction.equals("UseSelection"))
{
String nameAction = "newName";
if (sMenuAction.equals("NewDECTemplate") || sMenuAction.equals("NewDECVersion"))
nameAction = "appendName";
doDECUseSelection(nameAction);
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
return;
}
else if (sAction.equals("RemoveSelection"))
{
doRemoveBuildingBlocks();
// re work on the naming if new one
DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC");
EVS_Bean nullEVS = null;
if (!sMenuAction.equals("NewDECTemplate") && !sMenuAction.equals("NewDECVersion"))
dec = (DEC_Bean) this.getACNames(nullEVS, "Search", dec); // change only abbr pref name
else
dec = (DEC_Bean) this.getACNames(nullEVS, "Remove", dec); // need to change the long name & def also
DataManager.setAttribute(session, "m_DEC", dec);
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
return;
}
else if (sAction.equals("changeNameType"))
{
this.doChangeDECNameType();
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
else if (sAction.equals("Store Alternate Names") || sAction.equals("Store Reference Documents"))
this.doMarkACBeanForAltRef(m_classReq, m_classRes, "DataElementConcept", sAction, "createAC");
// add, edit and remove contacts
else if (sAction.equals("doContactUpd") || sAction.equals("removeContact"))
{
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
// capture all page attributes
m_setAC.setDECValueFromPage(m_classReq, m_classRes, DECBean);
DECBean.setAC_CONTACTS(this.doContactACUpdates(m_classReq, sAction));
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
else if (sAction.equals("clearBoxes"))
{
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("oldDECBean");
this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes);
String sDECID = DECBean.getDEC_DEC_IDSEQ();
Vector vList = new Vector();
// get VD's attributes from the database again
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
if (sDECID != null && !sDECID.equals(""))
serAC.doDECSearch(sDECID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "",
"", "", vList, "0");//===gf32398== added one more parameter regstatus
// forward editVD page with this bean
if (vList.size() > 0)
{
DECBean = (DEC_Bean) vList.elementAt(0);
DECBean = serAC.getDECAttributes(DECBean, sOriginAction, sMenuAction);
}
else
// new one
{
DECBean = new DEC_Bean();
DECBean.setDEC_ASL_NAME("DRAFT NEW");
DECBean.setAC_PREF_NAME_TYPE("SYS");
}
DEC_Bean pgBean = new DEC_Bean();
DataManager.setAttribute(session, "m_DEC", pgBean.cloneDEC_Bean(DECBean));
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
// open the create DE page or search result page
else if (sAction.equals("backToDE"))
{
this.clearCreateSessionAttributes(m_classReq, m_classRes);
this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes);
if (sMenuAction.equals("NewDECTemplate") || sMenuAction.equals("NewDECVersion"))
{
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Refresh", "");
ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp");
}
else if (sOriginAction.equalsIgnoreCase("CreateNewDECfromEditDE"))
ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp");
else
ForwardJSP(m_classReq, m_classRes, "/CreateDEPage.jsp");
}
}
/**
* The doEditDECActions method handles EditDEC actions of the request. Called from 'service' method where reqType is
* 'EditDEC' Calls 'ValidateDEC' if the action is Validate or submit. Calls 'doSuggestionDEC' if the action is open
* EVS Window.
*
* @throws Exception
*/
private void doEditDECActions() throws Exception
{
HttpSession session = m_classReq.getSession();
String sMenuAction = (String) m_classReq.getParameter("MenuAction");
if (sMenuAction != null)
DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction);
String sAction = (String) m_classReq.getParameter("pageAction");
DataManager.setAttribute(session, "DECPageAction", sAction); // store the page action in attribute
String sSubAction = (String) m_classReq.getParameter("DECAction");
DataManager.setAttribute(session, "DECAction", sSubAction);
String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed");
String sOriginAction = (String) session.getAttribute("originAction");
if (sAction.equals("submit"))
doSubmitDEC();
else if (sAction.equals("validate") && sOriginAction.equals("BlockEditDEC"))
doValidateDECBlockEdit();
else if (sAction.equals("validate"))
doValidateDEC();
else if (sAction.equals("suggestion"))
doSuggestionDE(m_classReq, m_classRes);
else if (sAction.equals("UseSelection"))
{
String nameAction = "appendName";
if (sOriginAction.equals("BlockEditDEC"))
nameAction = "blockName";
doDECUseSelection(nameAction);
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
return;
}
else if (sAction.equals("RemoveSelection"))
{
doRemoveBuildingBlocks();
// re work on the naming if new one
DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC");
EVS_Bean nullEVS = null;
dec = (DEC_Bean) this.getACNames(nullEVS, "Remove", dec); // need to change the long name & def also
DataManager.setAttribute(session, "m_DEC", dec);
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
return;
}
else if (sAction.equals("changeNameType"))
{
this.doChangeDECNameType();
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
}
else if (sAction.equals("Store Alternate Names") || sAction.equals("Store Reference Documents"))
this.doMarkACBeanForAltRef(m_classReq, m_classRes, "DataElementConcept", sAction, "editAC");
// add, edit and remove contacts
else if (sAction.equals("doContactUpd") || sAction.equals("removeContact"))
{
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
// capture all page attributes
m_setAC.setDECValueFromPage(m_classReq, m_classRes, DECBean);
DECBean.setAC_CONTACTS(this.doContactACUpdates(m_classReq, sAction));
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
}
else if (sAction.equals("clearBoxes"))
{
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("oldDECBean");
this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes);
String sDECID = DECBean.getDEC_DEC_IDSEQ();
Vector vList = new Vector();
// get VD's attributes from the database again
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
if (sDECID != null && !sDECID.equals(""))
serAC.doDECSearch(sDECID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "",
"", "", vList, "0");//===gf32398== added one more parameter regstatus
if (vList.size() > 0)
{
DECBean = (DEC_Bean) vList.elementAt(0);
// logger.debug("cleared name " + DECBean.getDEC_PREFERRED_NAME());
DECBean = serAC.getDECAttributes(DECBean, sOriginAction, sMenuAction);
}
DEC_Bean pgBean = new DEC_Bean();
DataManager.setAttribute(session, "m_DEC", pgBean.cloneDEC_Bean(DECBean));
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
}
// open the create DE page or search result page
else if (sAction.equals("backToDE"))
{
this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); // clear session attributes
if (sOriginAction.equalsIgnoreCase("editDECfromDE"))
ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp");
else if (sMenuAction.equalsIgnoreCase("editDEC") || sOriginAction.equalsIgnoreCase("BlockEditDEC")
|| sButtonPressed.equals("Search") || sOriginAction.equalsIgnoreCase("EditDEC"))
{
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
if (DECBean == null){
DECBean = new DEC_Bean();
}
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Refresh", "");
ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp");
}
else
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
}
}
/**
* changes the dec name type as selected
*
* @throws java.lang.Exception
*/
private void doChangeDECNameType() throws Exception
{
HttpSession session = m_classReq.getSession();
// get teh selected type from teh page
DEC_Bean pageDEC = (DEC_Bean) session.getAttribute("m_DEC");
m_setAC.setDECValueFromPage(m_classReq, m_classRes, pageDEC); // capture all other attributes
String sSysName = pageDEC.getAC_SYS_PREF_NAME();
String sAbbName = pageDEC.getAC_ABBR_PREF_NAME();
String sUsrName = pageDEC.getAC_USER_PREF_NAME();
String sNameType = (String) m_classReq.getParameter("rNameConv");
if (sNameType == null || sNameType.equals(""))
sNameType = "SYS"; // default
// logger.debug(sSysName + " name type " + sNameType);
// get the existing preferred name to make sure earlier typed one is saved in the user
String sPrefName = (String) m_classReq.getParameter("txtPreferredName");
if (sPrefName != null && !sPrefName.equals("") && !sPrefName.equals("(Generated by the System)")
&& !sPrefName.equals(sSysName) && !sPrefName.equals(sAbbName))
pageDEC.setAC_USER_PREF_NAME(sPrefName); // store typed one in de bean
// reset system generated or abbr accoring
if (sNameType.equals("SYS"))
pageDEC.setDEC_PREFERRED_NAME(sSysName);
else if (sNameType.equals("ABBR"))
pageDEC.setDEC_PREFERRED_NAME(sAbbName);
else if (sNameType.equals("USER"))
pageDEC.setDEC_PREFERRED_NAME(sUsrName);
// store the type in the bean
pageDEC.setAC_PREF_NAME_TYPE(sNameType);
// logger.debug(pageDEC.getAC_PREF_NAME_TYPE() + " pref " + pageDEC.getDEC_PREFERRED_NAME());
DataManager.setAttribute(session, "m_DEC", pageDEC);
}
/**
* Does open editDEC page action from DE page called from 'doEditDEActions' method. Calls
* 'm_setAC.setDEValueFromPage' to store the DE bean for later use Using the DEC idseq, calls 'SerAC.search_DEC'
* method to gets dec attributes to populate. stores DEC bean in session and opens editDEC page. goes back to editDE
* page if any error.
*
* @throws Exception
*/
public void doOpenEditDECPage() throws Exception
{
HttpSession session = m_classReq.getSession();
DE_Bean m_DE = (DE_Bean) session.getAttribute("m_DE");
if (m_DE == null)
m_DE = new DE_Bean();
// store the de values in the session
m_setAC.setDEValueFromPage(m_classReq, m_classRes, m_DE);
DataManager.setAttribute(session, "m_DE", m_DE);
this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes);
String sDEC_ID = null;
String sDECid[] = m_classReq.getParameterValues("selDEC");
if (sDECid != null)
sDEC_ID = sDECid[0];
// get the dec bean for this id
if (sDEC_ID != null)
{
Vector vList = new Vector();
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
serAC.doDECSearch(sDEC_ID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "",
"", vList, "0");//===gf32398== added one more parameter regstatus
// forward editDEC page with this bean
if (vList.size() > 0)
{
for (int i = 0; i < vList.size(); i++)
{
DEC_Bean DECBean = new DEC_Bean();
DECBean = (DEC_Bean) vList.elementAt(i);
// check if the user has write permission
String contID = DECBean.getDEC_CONTE_IDSEQ();
String sUser = (String) session.getAttribute("Username");
GetACService getAC = new GetACService(m_classReq, m_classRes, this);
String hasPermit = getAC.hasPrivilege("Create", sUser, "dec", contID);
// forward to editDEC if has write permission
if (hasPermit.equals("Yes"))
{
DECBean = serAC.getDECAttributes(DECBean, "Edit", "Edit"); // get DEC other Attributes
// store the bean in the session attribute
DataManager.setAttribute(session, "m_DEC", DECBean);
DEC_Bean oldDEC = new DEC_Bean();
oldDEC = oldDEC.cloneDEC_Bean(DECBean);
DataManager.setAttribute(session, "oldDECBean", oldDEC);
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); // forward to editDEC page
}
// go back to editDE with message if no permission
else
{
DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "No edit permission in "
+ DECBean.getDEC_CONTEXT_NAME() + " context");
ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); // forward to editDE page
}
break;
}
}
// display error message and back to edit DE page
else
DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE,
"Unable to get Existing DEConcept attributes from the database");
}
// display error message and back to editDE page
else
{
DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to get the DEConcept id from the page");
// forward the depage when error occurs
ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); // forward to editDE page
}
}
/**
* Called from doCreateDECActions. Calls 'setAC.setDECValueFromPage' to set the DEC data from the page. Calls
* 'setAC.setValidatePageValuesDEC' to validate the data. Loops through the vector vValidate to check if everything
* is valid and Calls 'doInsertDEC' to insert the data. If vector contains invalid fields, forwards to validation
* page
*
* @throws Exception
*/
private void doSubmitDEC() throws Exception
{
HttpSession session = m_classReq.getSession();
DataManager.setAttribute(session, "sDECAction", "validate");
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
EVS_Bean m_OC = new EVS_Bean();
EVS_Bean m_PC = new EVS_Bean();
EVS_Bean m_OCQ = new EVS_Bean();
EVS_Bean m_PCQ = new EVS_Bean();
GetACService getAC = new GetACService(m_classReq, m_classRes, this);
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
m_OC = (EVS_Bean) session.getAttribute("m_OC");
m_PC = (EVS_Bean) session.getAttribute("m_PC");
m_OCQ = (EVS_Bean) session.getAttribute("m_OCQ");
m_PCQ = (EVS_Bean) session.getAttribute("m_PCQ");
m_setAC.setValidatePageValuesDEC(m_classReq, m_classRes, m_DEC, m_OC, m_PC, getAC, m_OCQ, m_PCQ);
DataManager.setAttribute(session, "m_DEC", m_DEC);
boolean isValid = true;
Vector vValidate = new Vector();
vValidate = (Vector) m_classReq.getAttribute("vValidate");
if (vValidate == null)
isValid = false;
else
{
for (int i = 0; vValidate.size() > i; i = i + 3)
{
String sStat = (String) vValidate.elementAt(i + 2);
if (sStat.equals("Valid") == false)
{
isValid = false;
}
}
}
if (isValid == false)
{
ForwardJSP(m_classReq, m_classRes, "/ValidateDECPage.jsp");
}
else
{
doInsertDEC();
}
} // end of doSumitDE
/**
* The doValidateDEC method gets the values from page the user filled out, validates the input, then forwards
* results to the Validate page Called from 'doCreateDECActions' 'doSubmitDEC' method. Calls
* 'setAC.setDECValueFromPage' to set the data from the page to the bean. Calls 'setAC.setValidatePageValuesDEC' to
* validate the data. Stores 'm_DEC' bean in session. Forwards the page 'ValidateDECPage.jsp' with validation vector
* to display.
*
* @throws Exception
*/
private void doValidateDEC() throws Exception
{
// System.err.println("in doValidateDEC");
HttpSession session = m_classReq.getSession();
// do below for versioning to check whether these two have changed
DataManager.setAttribute(session, "DECPageAction", "validate"); // store the page action in attribute
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
String sOriginAction = (String)session.getAttribute("originAction");
if (m_DEC == null)
m_DEC = new DEC_Bean();
String oldOCIdseq = (String)session.getAttribute("oldOCIdseq");
String oldPropIdseq = (String)session.getAttribute("oldPropIdseq");
String checkValidityOC = "Yes";
String checkValidityProp = "Yes";
//begin GF30681
session.setAttribute("checkValidityOC", "Yes");
session.setAttribute("checkValidityProp", "Yes");
//end GF30681
EVS_Bean m_OC = new EVS_Bean();
EVS_Bean m_PC = new EVS_Bean();
EVS_Bean m_OCQ = new EVS_Bean();
EVS_Bean m_PCQ = new EVS_Bean();
GetACService getAC = new GetACService(m_classReq, m_classRes, this);
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
if ( (m_DEC.getDEC_PROPL_NAME_PRIMARY()== null || m_DEC.getDEC_PROPL_NAME_PRIMARY()!= null && m_DEC.getDEC_PROPL_NAME_PRIMARY().equals(""))
&& (m_DEC.getDEC_PROP_QUALIFIER_NAMES()==null || m_DEC.getDEC_PROP_QUALIFIER_NAMES()!=null && m_DEC.getDEC_PROP_QUALIFIER_NAMES().equals(""))){
checkValidityProp = "No";
}
if (sOriginAction!= null && !sOriginAction.equals("NewDECFromMenu")){
if (m_DEC.getDEC_OCL_IDSEQ() != null && !m_DEC.getDEC_OCL_IDSEQ().equals("") && m_DEC.getDEC_OCL_IDSEQ().equals(oldOCIdseq)){
checkValidityOC = "No";
}
if (m_DEC.getDEC_PROPL_IDSEQ() != null && !m_DEC.getDEC_PROPL_IDSEQ().equals("") && m_DEC.getDEC_PROPL_IDSEQ().equals(oldPropIdseq)){
checkValidityProp = "No";
}
}
DataManager.setAttribute(session, "checkValidityOC", checkValidityOC);
DataManager.setAttribute(session, "checkValidityProp", checkValidityProp);
m_OC = (EVS_Bean) session.getAttribute("m_OC");
m_PC = (EVS_Bean) session.getAttribute("m_PC");
m_OCQ = (EVS_Bean) session.getAttribute("m_OCQ");
m_PCQ = (EVS_Bean) session.getAttribute("m_PCQ");
// System.err.println("in doValidateDEC call setValidate");
m_setAC.setValidatePageValuesDEC(m_classReq, m_classRes, m_DEC, m_OC, m_PC, getAC, m_OCQ, m_PCQ);
DataManager.setAttribute(session, "m_DEC", m_DEC);
ForwardJSP(m_classReq, m_classRes, "/ValidateDECPage.jsp");
} // end of doValidateDEC
/**
* The doValidateDECBlockEdit method gets the values from page the user filled out, validates the input, then
* forwards results to the Validate page Called from 'doCreateDECActions' 'doSubmitDEC' method. Calls
* 'setAC.setDECValueFromPage' to set the data from the page to the bean. Calls 'setAC.setValidatePageValuesDEC' to
* validate the data. Stores 'm_DEC' bean in session. Forwards the page 'ValidateDECPage.jsp' with validation vector
* to display.
*
* @throws Exception
*/
private void doValidateDECBlockEdit() throws Exception
{
HttpSession session = m_classReq.getSession();
DataManager.setAttribute(session, "DECPageAction", "validate"); // store the page action in attribute
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
DataManager.setAttribute(session, "m_DEC", m_DEC);
m_setAC.setValidateBlockEdit(m_classReq, m_classRes, "DataElementConcept");
DataManager.setAttribute(session, "DECEditAction", "DECBlockEdit");
ForwardJSP(m_classReq, m_classRes, "/ValidateDECPage.jsp");
} // end of doValidateDEC
/**
* splits the dec object class or property from cadsr into individual concepts
*
* @param sComp
* name of the searched component
* @param m_Bean
* selected EVS bean
* @param nameAction
* string naming action
*
*/
private void splitIntoConcepts(String sComp, EVS_Bean m_Bean, String nameAction)
{
try
{
HttpSession session = m_classReq.getSession();
// String sSelRow = "";
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
Vector vObjectClass = (Vector) session.getAttribute("vObjectClass");
if (vObjectClass == null)
vObjectClass = new Vector();
Vector vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty == null)
vProperty = new Vector();
String sCondr = m_Bean.getCONDR_IDSEQ();
String sLongName = m_Bean.getLONG_NAME();
String sIDSEQ = m_Bean.getIDSEQ();
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 598 of DECServlet.java "+eBean.getPREFERRED_DEFINITION());
}
for (int i=0; i<vProperty.size();i++){
EVS_Bean eBean =(EVS_Bean)vProperty.get(i);
logger.debug("At line 602 of DECServlet.java "+eBean.getPREFERRED_DEFINITION());
}
if (sIDSEQ == null)
sIDSEQ = "";
if (sComp.equals("ObjectClass") || sComp.equals("ObjectQualifier"))
{
m_DEC.setDEC_OCL_NAME(sLongName);
m_DEC.setDEC_OCL_IDSEQ(sIDSEQ);
}
else if (sComp.equals("Property") || sComp.equals("PropertyClass") || sComp.equals("PropertyQualifier"))
{
m_DEC.setDEC_PROPL_NAME(sLongName);
m_DEC.setDEC_PROPL_IDSEQ(sIDSEQ);
}
// String sObjClass = m_DEC.getDEC_OCL_NAME();
if (sCondr != null && !sCondr.equals(""))
{
GetACService getAC = new GetACService(m_classReq, m_classRes, this);
Vector vCon = getAC.getAC_Concepts(sCondr, null, true);
for (int i=0; i<vCon.size();i++){
EVS_Bean eBean =(EVS_Bean)vCon.get(i);
logger.debug("At line 623 of DECServlet.java "+eBean.getLONG_NAME());
logger.debug("At line 624 of DECServlet.java "+eBean.getEVS_ORIGIN());
logger.debug("At line 625 of DECServlet.java "+eBean.getEVS_DATABASE());
logger.debug("At line 626 of DECServlet.java "+eBean.getCONCEPT_IDENTIFIER());
logger.debug("At line 627 of DECServlet.java "+eBean.getPREFERRED_DEFINITION());
}
if (vCon != null && vCon.size() > 0)
{
for (int j = 0; j < vCon.size(); j++)
{
EVS_Bean bean = new EVS_Bean();
bean = (EVS_Bean) vCon.elementAt(j);
if (bean != null)
{
if (sComp.equals("ObjectClass") || sComp.equals("ObjectQualifier"))
{
logger.debug("At line 622 of DECServlet.java");
if (j == 0) // Primary Concept
m_DEC = this.addOCConcepts(nameAction, m_DEC, bean, "Primary");
else
// Secondary Concepts
m_DEC = this.addOCConcepts(nameAction, m_DEC, bean, "Qualifier");
}
else if (sComp.equals("Property") || sComp.equals("PropertyClass")
|| sComp.equals("PropertyQualifier"))
{
logger.debug("At line 632 of DECServlet.java");
if (j == 0) // Primary Concept
m_DEC = this.addPropConcepts(nameAction, m_DEC, bean, "Primary");
else
// Secondary Concepts
m_DEC = this.addPropConcepts(nameAction, m_DEC, bean, "Qualifier");
}
}
}
}
}// sCondr != null
}
catch (Exception e)
{
this.logger.error("ERROR - splitintoConcept : " + e.toString(), e);
}
}
/**
* makes three types of preferred names and stores it in the bean
*
* @param m_classReq
* HttpServletRequest object
* @param m_classRes
* HttpServletResponse object
* @param newBean
* new evs bean
* @param nameAct
* string new name or apeend name
* @param pageDEC
* current dec bean
* @return dec bean
*/
public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC)
{
HttpSession session = m_classReq.getSession();
DEC_Bean pageDEC = (DEC_Bean)pageAC;
if (pageDEC == null)
pageDEC = (DEC_Bean) session.getAttribute("m_DEC");
// get DEC object class and property names
String sLongName = "";
String sPrefName = "";
String sAbbName = "";
String sOCName = "";
String sPropName = "";
String sDef = "";
//======================GF30798==============START
String sComp = (String) m_classReq.getParameter("sCompBlocks");
InsACService ins = new InsACService(m_classReq, m_classRes, this);
Vector vObjectClass = (Vector) session.getAttribute("vObjectClass");
Vector vProperty = (Vector) session.getAttribute("vProperty");
logger.debug("at Line 700 of DEC.java" + "***" + sComp + "***" + newBean);
if(newBean != null) {
if (sComp.startsWith("Object")) {
logger.debug("at Line 703 of DEC.java" + newBean.getEVS_DATABASE());
if (!(newBean.getEVS_DATABASE().equals("caDSR"))) {
String conIdseq = ins.getConcept("", newBean, false);
if (conIdseq == null || conIdseq.equals("")){
logger.debug("at Line 707 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME());
}else {
logger.debug("at Line 709 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME());
}
}
}else if (sComp.startsWith("Prop")) {
logger.debug("at Line 714 of DEC.java" + newBean.getEVS_DATABASE());
if (!(newBean.getEVS_DATABASE().equals("caDSR"))) {
String conIdseq = ins.getConcept("", newBean, false);
if (conIdseq == null || conIdseq.equals("")){
logger.debug("at Line 718 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME());
}else {
logger.debug("at Line 720 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME());
}
}
}
}
//======================GF30798==============END
// get the existing one if not restructuring the name but appending it
if (newBean != null)
{
sLongName = pageDEC.getDEC_LONG_NAME();
if (sLongName == null)
sLongName = "";
sDef = pageDEC.getDEC_PREFERRED_DEFINITION();
if (sDef == null)
sDef = "";
logger.debug("At line 688 of DECServlet.java"+sLongName+"**"+sDef);
}
// get the typed text on to user name
String selNameType = "";
if (nameAct.equals("Search") || nameAct.equals("Remove"))
{
logger.info("At line 750 of DECServlet.java");
selNameType = (String) m_classReq.getParameter("rNameConv");
sPrefName = (String) m_classReq.getParameter("txPreferredName");
if (selNameType != null && selNameType.equals("USER") && sPrefName != null)
pageDEC.setAC_USER_PREF_NAME(sPrefName);
}
// get the object class into the long name and abbr name
//Vector vObjectClass = (Vector) session.getAttribute("vObjectClass"); //GF30798
if (vObjectClass == null) {
vObjectClass = new Vector();
}
//begin of GF30798
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 762 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
//end of GF30798
// add the Object Class qualifiers first
for (int i = 1; vObjectClass.size() > i; i++)
{
EVS_Bean eCon = (EVS_Bean) vObjectClass.elementAt(i);
if (eCon == null)
eCon = new EVS_Bean();
String conName = eCon.getLONG_NAME();
if (conName == null)
conName = "";
if (!conName.equals(""))
{
logger.info("At line 778 of DECServlet.java");
String nvpValue = "";
if (this.checkNVP(eCon))
nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE();
// rearrange it long name and definition
if (newBean == null)
{
if (!sLongName.equals(""))
sLongName += " ";
sLongName += conName + nvpValue;
if (!sDef.equals(""))
sDef += "_"; // add definition
sDef += eCon.getPREFERRED_DEFINITION() + nvpValue;
logger.debug("At line 792 of DECServlet.java"+sLongName+"**"+sDef);
}
if (!sAbbName.equals(""))
sAbbName += "_";
if (conName.length() > 3)
sAbbName += conName.substring(0, 4); // truncate to four letters
else
sAbbName += conName;
// add object qualifiers to object class name
if (!sOCName.equals(""))
sOCName += " ";
sOCName += conName + nvpValue;
logger.debug("At line 805 of DECServlet.java"+conName+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName);
}
}
// add the Object Class primary
if (vObjectClass != null && vObjectClass.size() > 0)
{
EVS_Bean eCon = (EVS_Bean) vObjectClass.elementAt(0);
if (eCon == null)
eCon = new EVS_Bean();
String sPrimary = eCon.getLONG_NAME();
if (sPrimary == null)
sPrimary = "";
if (!sPrimary.equals(""))
{
logger.info("At line 819 of DECServlet.java");
String nvpValue = "";
if (this.checkNVP(eCon))
nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE();
// rearrange it only long name and definition
if (newBean == null)
{
if (!sLongName.equals(""))
sLongName += " ";
sLongName += sPrimary + nvpValue;
if (!sDef.equals(""))
sDef += "_"; // add definition
sDef += eCon.getPREFERRED_DEFINITION() + nvpValue;
logger.debug("At line 833 of DECServlet.java"+sLongName+"**"+sDef);
}
if (!sAbbName.equals(""))
sAbbName += "_";
if (sPrimary.length() > 3)
sAbbName += sPrimary.substring(0, 4); // truncate to four letters
else
sAbbName += sPrimary;
// add primary object to object name
if (!sOCName.equals(""))
sOCName += " ";
sOCName += sPrimary + nvpValue;
logger.debug("At line 778 of DECServlet.java"+sPrimary+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName);
}
}
// get the Property into the long name and abbr name
//Vector vProperty = (Vector) session.getAttribute("vProperty"); //GF30798
if (vProperty == null)
vProperty = new Vector();
//begin of GF30798
for (int i=0; i<vProperty.size();i++){
EVS_Bean eBean =(EVS_Bean)vProperty.get(i);
logger.debug("At line 853 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
//begin of GF30798
// add the property qualifiers first
for (int i = 1; vProperty.size() > i; i++)
{
EVS_Bean eCon = (EVS_Bean) vProperty.elementAt(i);
if (eCon == null)
eCon = new EVS_Bean();
String conName = eCon.getLONG_NAME();
if (conName == null)
conName = "";
if (!conName.equals(""))
{
logger.info("At line 869 of DECServlet.java");
String nvpValue = "";
if (this.checkNVP(eCon))
nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE();
// rearrange it long name and definition
if (newBean == null)
{
if (!sLongName.equals(""))
sLongName += " ";
sLongName += conName + nvpValue;
if (!sDef.equals(""))
sDef += "_"; // add definition
sDef += eCon.getPREFERRED_DEFINITION() + nvpValue;
logger.debug("At line 883 of DECServlet.java"+sLongName+"**"+sDef);
}
if (!sAbbName.equals(""))
sAbbName += "_";
if (conName.length() > 3)
sAbbName += conName.substring(0, 4); // truncate to four letters
else
sAbbName += conName;
// add property qualifiers to property name
if (!sPropName.equals(""))
sPropName += " ";
sPropName += conName + nvpValue;
logger.debug("At line 895 of DECServlet.java"+conName+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName);
}
}
// add the property primary
if (vProperty != null && vProperty.size() > 0)
{
EVS_Bean eCon = (EVS_Bean) vProperty.elementAt(0);
if (eCon == null)
eCon = new EVS_Bean();
String sPrimary = eCon.getLONG_NAME();
if (sPrimary == null)
sPrimary = "";
if (!sPrimary.equals(""))
{
logger.info("At line 909 of DECServlet.java");
String nvpValue = "";
if (this.checkNVP(eCon))
nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE();
// rearrange it only long name and definition
if (newBean == null)
{
if (!sLongName.equals(""))
sLongName += " ";
sLongName += sPrimary + nvpValue;
if (!sDef.equals(""))
sDef += "_"; // add definition
sDef += eCon.getPREFERRED_DEFINITION() + nvpValue;
logger.debug("At line 923 of DECServlet.java"+sLongName+"**"+sDef);
}
if (!sAbbName.equals(""))
sAbbName += "_";
if (sPrimary.length() > 3)
sAbbName += sPrimary.substring(0, 4); // truncate to four letters
else
sAbbName += sPrimary;
// add primary property to property name
if (!sPropName.equals(""))
sPropName += " ";
sPropName += sPrimary + nvpValue;
logger.debug("At line 935 of DECServlet.java"+sPrimary+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName);
}
}
// truncate to 30 characters
if (sAbbName != null && sAbbName.length() > 30)
sAbbName = sAbbName.substring(0, 30);
// add the abbr name to vd bean and page is selected
pageDEC.setAC_ABBR_PREF_NAME(sAbbName);
// make abbr name name preferrd name if sys was selected
if (selNameType != null && selNameType.equals("ABBR"))
pageDEC.setDEC_PREFERRED_NAME(sAbbName);
// appending to the existing;
if (newBean != null)
{
String sSelectName = newBean.getLONG_NAME();
if (!sLongName.equals(""))
sLongName += " ";
sLongName += sSelectName;
if (!sDef.equals(""))
sDef += "_"; // add definition
sDef += newBean.getPREFERRED_DEFINITION();
logger.debug("At line 956 of DECServlet.java"+sLongName+"**"+sDef);
}
// store the long names, definition, and usr name in vd bean if searched
if (nameAct.equals("Search") || nameAct.equals("Remove")) // GF30798 - added to call when name act is remove
{
pageDEC.setDEC_LONG_NAME(AdministeredItemUtil.handleLongName(sLongName)); //GF32004;
pageDEC.setDEC_PREFERRED_DEFINITION(sDef);
logger.debug("DEC_LONG_NAME at Line 963 of DECServlet.java"+pageDEC.getDEC_LONG_NAME()+"**"+pageDEC.getDEC_PREFERRED_DEFINITION());
}
if (!nameAct.equals("OpenDEC")){
pageDEC.setDEC_OCL_NAME(sOCName);
pageDEC.setDEC_PROPL_NAME(sPropName);
logger.debug("At line 968 of DECServlet.java"+sOCName+"**"+sPropName);
}
if (nameAct.equals("Search") || nameAct.equals("Remove"))
{
pageDEC.setAC_SYS_PREF_NAME("(Generated by the System)"); // only for dec
if (selNameType != null && selNameType.equals("SYS"))
pageDEC.setDEC_PREFERRED_NAME(pageDEC.getAC_SYS_PREF_NAME());
}
return pageDEC;
}
/**
*
* @param nameAction
* string naming action
*
*/
@SuppressWarnings("unchecked")
private void doDECUseSelection(String nameAction)
{
try
{
HttpSession session = m_classReq.getSession();
String sSelRow = "";
boolean selectedOCQualifiers = false;
boolean selectedPropQualifiers = false;
// InsACService insAC = new InsACService(m_classReq, m_classRes, this);
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
Vector<EVS_Bean> vObjectClass = (Vector) session.getAttribute("vObjectClass");
//begin of GF30798
+ String evsDef = null;
if(vObjectClass != null && vObjectClass.size() > 0) {
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
- if(eBean != null)
- logger.debug("At line 1001 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
+ if(eBean != null) {
+ logger.debug("At line 1001 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
+ evsDef = eBean.getPREFERRED_DEFINITION();
+ }
}
}
+ boolean changedOCDefsWarningFlag = false;
+ String userSelectedDef = (String) m_classReq.getParameter("userSelectedDef");
+ if(!userSelectedDef.equals(evsDef)) { //TBD - should check user selection against caDSR not EVS !!!
+ changedOCDefsWarningFlag = true;
+ }
//end of GF30798
- if (vObjectClass == null || vObjectClass.size() == 0) {
+ if (!changedOCDefsWarningFlag && vObjectClass == null || vObjectClass.size() == 0) {
vObjectClass = new Vector<EVS_Bean>();
//reset the attributes for keeping track of non-caDSR choices...
session.removeAttribute("chosenOCCodes");
session.removeAttribute("chosenOCDefs");
session.removeAttribute("changedOCDefsWarning");
}
Vector<EVS_Bean> vProperty = (Vector) session.getAttribute("vProperty");
//begin of GF30798
if(vProperty != null && vProperty.size() > 0) {
for (int i=0; i<vProperty.size();i++){
EVS_Bean eBean =(EVS_Bean)vProperty.get(i);
if(eBean != null)
logger.debug("At line 1015 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
//end of GF30798
if (vProperty == null || vProperty.size() == 0) {
vProperty = new Vector<EVS_Bean>();
//reset the attributes for keeping track of non-caDSR choices...
session.removeAttribute("chosenPropCodes");
session.removeAttribute("chosenPropDefs");
session.removeAttribute("changedPropDefsWarning");
}
if (vObjectClass.size()>1){
selectedOCQualifiers = true;
}
if (vProperty.size()>1){
selectedPropQualifiers = true;
}
Vector vAC = null;
EVS_Bean blockBean = new EVS_Bean();
String sComp = (String) m_classReq.getParameter("sCompBlocks");
if (sComp == null)
sComp = "";
// get the search bean from the selected row
sSelRow = (String) m_classReq.getParameter("selCompBlockRow");
vAC = (Vector) session.getAttribute("vACSearch");
logger.debug("At Line 951 of DECServlet.java"+Arrays.asList(vAC));
if (vAC == null)
vAC = new Vector();
if (sSelRow != null && !sSelRow.equals(""))
{
String sObjRow = sSelRow.substring(2);
Integer intObjRow = new Integer(sObjRow);
int intObjRow2 = intObjRow.intValue();
if (vAC.size() > intObjRow2 - 1)
blockBean = (EVS_Bean) vAC.elementAt(intObjRow2);
String sNVP = (String) m_classReq.getParameter("nvpConcept");
if (sNVP != null && !sNVP.equals(""))
{
blockBean.setNVP_CONCEPT_VALUE(sNVP);
String sName = blockBean.getLONG_NAME();
blockBean.setLONG_NAME(sName + "::" + sNVP);
blockBean.setPREFERRED_DEFINITION(blockBean.getPREFERRED_DEFINITION() + "::" + sNVP);
}
logger.debug("At Line 977 of DECServlet.java"+sNVP+"**"+blockBean.getLONG_NAME()+"**"+ blockBean.getPREFERRED_DEFINITION());
//System.out.println(sNVP + sComp + blockBean.getLONG_NAME() + blockBean.getPREFERRED_DEFINITION());
}
else
{
storeStatusMsg("Unable to get the selected row from the " + sComp + " search results.\\n"
+ "Please try again.");
return;
}
// send it back if unable to obtion the concept
if (blockBean == null || blockBean.getLONG_NAME() == null)
{
storeStatusMsg("Unable to obtain concept from the selected row of the " + sComp
+ " search results.\\n" + "Please try again.");
return;
}
//Store chosen concept code and definition for later use in alt. definition.
String code = blockBean.getCONCEPT_IDENTIFIER();
String def = blockBean.getPREFERRED_DEFINITION();
Vector<String> codes = null;
Vector<String> defs = null;
if (sComp.startsWith("Object")) {
if (session.getAttribute("chosenOCCodes") == null || ((Vector)session.getAttribute("chosenOCCodes")).size() == 0) {
codes = new Vector<String>();
defs = new Vector<String>();
} else {
codes =(Vector<String>) session.getAttribute("chosenOCCodes");
defs = (Vector<String>) session.getAttribute("chosenOCDefs");
}
logger.debug("At line 1009 of DECServlet.java"+codes +"***"+defs);
}
else if (sComp.startsWith("Prop")) {
if (session.getAttribute("chosenPropCodes") == null) {
codes = new Vector<String>();
defs = new Vector<String>();
} else {
codes =(Vector<String>) session.getAttribute("chosenPropCodes");
defs = (Vector<String>) session.getAttribute("chosenPropDefs");
}
logger.debug("At line 1102 of DECServlet.java"+Arrays.asList(codes) +"***"+Arrays.asList(defs));
}
if (!codes.contains(code)) {
codes.add(code);
defs.add(def);
logger.debug("At line 1108 of DECServlet.java"+Arrays.asList(codes) +"***"+Arrays.asList(defs));
}
// do the primary search selection action
if (sComp.equals("ObjectClass") || sComp.equals("Property") || sComp.equals("PropertyClass"))
{
logger.debug("At line 1114 of DECServlet.java");
if (blockBean.getEVS_DATABASE().equals("caDSR"))
{
logger.debug("At line 1117 of DECServlet.java");
// split it if rep term, add concept class to the list if evs id exists
if (blockBean.getCONDR_IDSEQ() == null || blockBean.getCONDR_IDSEQ().equals(""))
{
logger.debug("At line 1121 of DECServlet.java");
if (blockBean.getCONCEPT_IDENTIFIER() == null || blockBean.getCONCEPT_IDENTIFIER().equals(""))
{
storeStatusMsg("This " + sComp
+ " is not associated to a concept, so the data is suspect. \\n"
+ "Please choose another " + sComp + " .");
}
else
// concept class search results
{
if (sComp.equals("ObjectClass"))
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Primary");
else
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Primary");
}
}
else{
logger.debug("At line 1139 of DECServlet.java ");
// split it into concepts for object class or property search results
splitIntoConcepts(sComp, blockBean, nameAction);
}
}
else
// evs search results
{
logger.debug("At line 1147 of DECServlet.java ");
if (sComp.equals("ObjectClass"))
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Primary");
else
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Primary");
}
}
else if (sComp.equals("ObjectQualifier"))
{
logger.debug("At line 1081 of DECServlet.java ");
// Do this to reserve zero position in vector for primary concept
if (vObjectClass.size() < 1)
{
EVS_Bean OCBean = new EVS_Bean();
vObjectClass.addElement(OCBean);
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
}
m_DEC.setDEC_OCL_IDSEQ("");
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Qualifier");
}
else if (sComp.equals("PropertyQualifier"))
{
logger.debug("At line 1078 of DECServlet.java ");
// Do this to reserve zero position in vector for primary concept
if (vProperty.size() < 1)
{
EVS_Bean PCBean = new EVS_Bean();
vProperty.addElement(PCBean);
DataManager.setAttribute(session, "vProperty", vProperty);
}
m_DEC.setDEC_PROPL_IDSEQ("");
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Qualifier");
}
if ( sComp.equals("ObjectClass") || sComp.equals("ObjectQualifier")){
vObjectClass = (Vector) session.getAttribute("vObjectClass");
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1186 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
if (vObjectClass != null && vObjectClass.size()>0){
logger.debug("at line 1189 of DECServlet.java"+vObjectClass.size());
vObjectClass = this.getMatchingThesarusconcept(vObjectClass, "Object Class"); //get the matching concept from EVS based on the caDSR's CDR (object class)
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1193 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER()+"**"+vObjectClass.size());
}
m_DEC = this.updateOCAttribues(vObjectClass, m_DEC); //populate caDSR's DEC bean based on VO (from EVS results)
this.checkChosenConcepts(session,codes, defs, vObjectClass, "OC"); //make sure user's chosen/edited definition is not different from the EVS definition???
}
if (blockBean.getcaDSR_COMPONENT() != null && blockBean.getcaDSR_COMPONENT().equals("Concept Class")){
logger.debug("At line 1139 of DECServlet.java");
m_DEC.setDEC_OCL_IDSEQ("");
}else {//Object Class or from vocabulary
if(blockBean.getcaDSR_COMPONENT() != null && !selectedOCQualifiers){//if selected existing object class (JT just checking getcaDSR_COMPONENT???)
logger.debug("At line 1108 of DECServlet.java");
ValidationStatusBean statusBean = new ValidationStatusBean();
statusBean.setStatusMessage("** Using existing "+blockBean.getcaDSR_COMPONENT()+" "+blockBean.getLONG_NAME()+" ("+blockBean.getID()+"v"+blockBean.getVERSION()+") from "+blockBean.getCONTEXT_NAME());
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(blockBean.getCONDR_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(blockBean.getIDSEQ());
session.setAttribute("ocStatusBean", statusBean);
}else{
m_DEC.setDEC_OCL_IDSEQ("");
}
}
DataManager.setAttribute(session, "vObjectClass", vObjectClass); //save EVS VO in session
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1220 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
if (sComp.equals("Property") || sComp.equals("PropertyClass") || sComp.equals("PropertyQualifier")){
vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty != null && vProperty.size()>0){
vProperty = this.getMatchingThesarusconcept(vProperty, "Property");
logger.debug("At line 1127 of DECServlet.java "+Arrays.asList(vProperty));
m_DEC = this.updatePropAttribues(vProperty, m_DEC);
boolean warning = false;
//Rebuilding codes and defs to get rid of unused codes
Vector<String> rebuiltCodes = new Vector<String>();
Vector<String> rebuiltDefs = new Vector<String>();
//added in 4.1 to check if OC exists and set alternate def. if used an EVS concept
this.checkChosenConcepts(session,codes, defs, vProperty, "Prop");
}
if (blockBean.getcaDSR_COMPONENT()!= null && blockBean.getcaDSR_COMPONENT().equals("Concept Class")){
logger.debug("At line 1141 of DECServlet.java");
m_DEC.setDEC_PROPL_IDSEQ("");
}else{//Property or from vocabulary
if(blockBean.getcaDSR_COMPONENT() != null && !selectedPropQualifiers){//if selected existing property
logger.debug("At line 1145 of DECServlet.java");
ValidationStatusBean statusBean = new ValidationStatusBean();
statusBean.setStatusMessage("** Using existing "+blockBean.getcaDSR_COMPONENT()+" "+blockBean.getLONG_NAME()+" ("+blockBean.getID()+"v"+blockBean.getVERSION()+") from "+blockBean.getCONTEXT_NAME());
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(blockBean.getCONDR_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(blockBean.getIDSEQ());
session.setAttribute("propStatusBean", statusBean);
}else{
m_DEC.setDEC_PROPL_IDSEQ("");
}
}
DataManager.setAttribute(session, "vProperty", vProperty);
logger.debug("At line 1158 of DECServlet.java"+Arrays.asList(vProperty));
}
// rebuild new name if not appending
EVS_Bean nullEVS = null;
if (nameAction.equals("newName"))
m_DEC = (DEC_Bean) this.getACNames(nullEVS, "Search", m_DEC);
else if (nameAction.equals("blockName"))
m_DEC = (DEC_Bean) this.getACNames(nullEVS, "blockName", m_DEC);
DataManager.setAttribute(session, "m_DEC", m_DEC); //set the user's selection + data from EVS in the DEC in session (for submission later on)
}
catch (Exception e)
{
this.logger.error("ERROR - doDECUseSelection : " + e.toString(), e);
}
} // end of doDECUseSelection
public static void checkChosenConcepts(HttpSession session, Vector<String> codes, Vector<String> defs, Vector<EVS_Bean> vConcepts, String type) {
if (codes == null && session.getAttribute("chosen"+type+"Codes") != null) {
codes = (Vector<String>) session.getAttribute("chosen"+type+"Codes");
defs = (Vector<String>) session.getAttribute("chosen"+type+"Defs");
} else if (codes == null)
return;
logger.debug("At line 1207 of DECServlet.java "+Arrays.asList(codes)+"**"+Arrays.asList(defs));
boolean warning = false;
//Rebuilding codes and defs to get rid of unused codes
Vector<String> rebuiltCodes = new Vector<String>();
Vector<String> rebuiltDefs = new Vector<String>();
//vConcepts is a list of all concepts currently used for this element
//Chosen codes and defs are contained in [ ] if are originating from a caDSR element.
//The codes list should not include anything that's not in vConcept (in case of removal)
//Also need to make sure that the new concepts are at the end of the list, like they're supposed to be.
//added in 4.1 to check if OC exists and set alternate def. if used an EVS concept
for(EVS_Bean eb: vConcepts){
String usedCode = eb.getCONCEPT_IDENTIFIER();
String usedDef = eb.getPREFERRED_DEFINITION();
logger.debug("At line 1222 of DECServlet.java "+usedCode+"**"+usedDef);
boolean found = false;
for(int codeCounter = 0; codeCounter < codes.size(); codeCounter++){
String chosenCode = codes.get(codeCounter);
logger.debug("At line 1183 of DECServlet.java "+chosenCode);
if (chosenCode.equals(usedCode) || chosenCode.equals("*"+usedCode) || (chosenCode.contains(usedCode) && chosenCode.endsWith("]"))){
//Code is used, transfer to rebuilt list
found = true;
rebuiltCodes.add("*"+chosenCode); //Adding * to mark a new concept (need to be added at the end of old definition)
rebuiltDefs.add("*"+defs.get(codeCounter));
logger.debug("At line 1233 of DECServlet.java"+defs.get(codeCounter)+"**"+usedDef);
//if definitions don't match, put up a warning.
if (defs != null && usedDef != null && !defs.get(codeCounter).equals(usedDef)) //GF32004 not related to this ticket, but found NPE during the test
warning = true;
}
logger.debug("At line 1239 of DECServlet.java"+Arrays.asList(rebuiltCodes)+"**"+Arrays.asList(rebuiltDefs));
}
logger.debug("At line 1241 of DECServlet.java"+found);
//if you got to here without finding usedCode in chosenCodes, it means you're Editing.
//Add current used code to fill in the gap.
if (!found) {
rebuiltCodes.add(usedCode);
rebuiltDefs.add(usedDef);
logger.debug("At line 1247 of DECServlet.java"+Arrays.asList(rebuiltCodes)+"**"+Arrays.asList(rebuiltDefs));
}
}
logger.debug("At line 1251 of DECServlet.java"+warning+"**");
session.setAttribute("chosen"+type+"Codes", rebuiltCodes);
session.setAttribute("chosen"+type+"Defs", rebuiltDefs);
if (warning)
session.setAttribute("changed"+type+"DefsWarning", Boolean.toString(warning));
else
session.removeAttribute("changed"+type+"DefsWarning");
}
/**
* adds the selected concept to the vector of concepts for property
*
* @param m_classReq
* HttpServletRequest
* @param m_classRes
* HttpServletResponse
* @param nameAction
* String naming action
* @param decBean
* selected DEC_Bean
* @param eBean
* selected EVS_Bean
* @param ocType
* String property type (primary or qualifier)
* @return DEC_Bean
* @throws Exception
*/
@SuppressWarnings("unchecked")
private DEC_Bean addOCConcepts(String nameAction,
DEC_Bean decBean, EVS_Bean eBean, String ocType) throws Exception
{
HttpSession session = m_classReq.getSession();
// add the concept bean to the OC vector and store it in the vector
Vector<EVS_Bean> vObjectClass = (Vector) session.getAttribute("vObjectClass");
if (vObjectClass == null)
vObjectClass = new Vector<EVS_Bean>();
// get the evs user bean
EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG);
// //("EvsUserBean");
if (eUser == null)
eUser = new EVS_UserBean();
eBean.setCON_AC_SUBMIT_ACTION("INS");
eBean.setCONTE_IDSEQ(decBean.getDEC_CONTE_IDSEQ());
String eDB = eBean.getEVS_DATABASE();
logger.debug("At line 1278 of DECServlet.java "+eDB);
if (eDB != null && eBean.getEVS_ORIGIN() != null && eDB.equalsIgnoreCase("caDSR"))
{
logger.debug("At line 1271 of DECServlet.java");
eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName",
// "vocabDBOrigin");
logger.debug("At line 1274 of DECServlet.java"+eDB);
if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue"))
eDB = eBean.getEVS_ORIGIN();
eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN());
}
// get its matching thesaurus concept
// System.out.println(eBean.getEVS_ORIGIN() + " before thes concept for OC " + eDB);
//EVSSearch evs = new EVSSearch(m_classReq, m_classRes, this);
//eBean = evs.getThesaurusConcept(eBean);
// add to the vector and store it in the session, reset if primary and alredy existed, add otehrwise
if (ocType.equals("Primary") && vObjectClass.size() > 0)
vObjectClass.setElementAt(eBean, 0);
else
vObjectClass.addElement(eBean);
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean Bean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1394 of DECServlet.java "+Bean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
DataManager.setAttribute(session, "newObjectClass", "true");
// DataManager.setAttribute(session, "selObjQRow", sSelRow);
// add to name if appending
if (nameAction.equals("appendName"))
decBean = (DEC_Bean) this.getACNames(eBean, "Search", decBean);
return decBean;
} // end addOCConcepts
/**
* adds the selected concept to the vector of concepts for property
*
* @param m_classReq
* HttpServletRequest
* @param m_classRes
* HttpServletResponse
* @param nameAction
* String naming action
* @param decBean
* selected DEC_Bean
* @param eBean
* selected EVS_Bean
* @param propType
* String property type (primary or qualifier)
* @return DEC_Bean
* @throws Exception
*/
@SuppressWarnings("unchecked")
private DEC_Bean addPropConcepts(String nameAction,
DEC_Bean decBean, EVS_Bean eBean, String propType) throws Exception
{
HttpSession session = m_classReq.getSession();
// add the concept bean to the OC vector and store it in the vector
Vector<EVS_Bean> vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty == null)
vProperty = new Vector<EVS_Bean>();
// get the evs user bean
EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG);
// //("EvsUserBean");
if (eUser == null)
eUser = new EVS_UserBean();
eBean.setCON_AC_SUBMIT_ACTION("INS");
eBean.setCONTE_IDSEQ(decBean.getDEC_CONTE_IDSEQ());
String eDB = eBean.getEVS_DATABASE();
if (eDB != null && eBean.getEVS_ORIGIN() != null && eDB.equalsIgnoreCase("caDSR"))
{
eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName",
// "vocabDBOrigin");
logger.debug("At line 1339 of DECServlet.java"+eDB);
if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue"))
eDB = eBean.getEVS_ORIGIN();
eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN());
}
// System.out.println(eBean.getEVS_ORIGIN() + " before thes concept for PROP " + eDB);
// EVSSearch evs = new EVSSearch(m_classReq, m_classRes, this);
//eBean = evs.getThesaurusConcept(eBean);
// add to the vector and store it in the session, reset if primary and alredy existed, add otehrwise
if (propType.equals("Primary") && vProperty.size() > 0)
vProperty.setElementAt(eBean, 0);
else
vProperty.addElement(eBean);
DataManager.setAttribute(session, "vProperty", vProperty);
DataManager.setAttribute(session, "newProperty", "true");
logger.debug("At line 1354 of DECServlet.java**"+Arrays.asList(vProperty));
// DataManager.setAttribute(session, "selObjQRow", sSelRow);
// add to name if appending
if (nameAction.equals("appendName"))
decBean = (DEC_Bean) this.getACNames(eBean, "Search", decBean);
return decBean;
} // end addPropConcepts
/**
* The doInsertDEC method to insert or update record in the database. Called from 'service' method where reqType is
* 'validateDECFromForm'. Retrieves the session bean m_DEC. if the action is reEditDEC forwards the page back to
* Edit or create pages.
*
* Otherwise, calls 'doUpdateDECAction' for editing the vd. calls 'doInsertDECfromDEAction' for creating the vd from
* DE page. calls 'doInsertDECfromMenuAction' for creating the vd from menu .
*
* @throws Exception
*/
private void doInsertDEC() throws Exception
{
HttpSession session = m_classReq.getSession();
// make sure that status message is empty
DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "");
Vector vStat = new Vector();
DataManager.setAttribute(session, "vStatMsg", vStat);
String sOriginAction = (String) session.getAttribute("originAction");
String sDECAction = (String) session.getAttribute("DECAction");
if (sDECAction == null)
sDECAction = "";
String sDECEditAction = (String) session.getAttribute("DECEditAction");
if (sDECEditAction == null)
sDECEditAction = "";
String sAction = (String) m_classReq.getParameter("ValidateDECPageAction");
if (sAction == null)
sAction = "submitting"; // for direct submit without validating
if (sAction != null)
{// going back to create or edit pages from validation page
if (sAction.equals("reEditDEC"))
{
if (sDECAction.equals("EditDEC") || sDECAction.equals("BlockEdit"))
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp");
else
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
else
{
// update the database for edit action
if (sDECAction.equals("EditDEC") && !sOriginAction.equals("BlockEditDEC"))
doUpdateDECAction();
else if (sDECEditAction.equals("DECBlockEdit"))
doUpdateDECActionBE();
// if create new dec from create DE page.
else if (sOriginAction.equals("CreateNewDECfromCreateDE")
|| sOriginAction.equals("CreateNewDECfromEditDE"))
doInsertDECfromDEAction(sOriginAction);
// FROM MENU, TEMPLATE, VERSION
else{
logger.info("*****************doInsertDEC called");
doInsertDECfromMenuAction();
}
}
}
} // end of doInsertDEC
/**
* update record in the database and display the result. Called from 'doInsertDEC' method when the aciton is
* editing. Retrieves the session bean m_DEC. calls 'insAC.setDEC' to update the database. updates the DEbean and
* sends back to EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed
* search result forwards the page back to search page with refreshed list after updating. If ret is not null stores
* the statusMessage as error message in session and forwards the page back to 'EditDECPage.jsp' for Edit.
*
* @throws Exception
*/
private void doUpdateDECAction() throws Exception
{
HttpSession session = m_classReq.getSession();
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
DEC_Bean oldDECBean = (DEC_Bean) session.getAttribute("oldDECBean");
//String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION);
InsACService insAC = new InsACService(m_classReq, m_classRes, this);
// doInsertDECBlocks(m_classReq, m_classRes, null); //insert any building blocks from Thesaurus first
// udpate the status message with DEC name and ID
storeStatusMsg("Data Element Concept Name : " + DECBean.getDEC_LONG_NAME());
storeStatusMsg("Public ID : " + DECBean.getDEC_DEC_ID());
// call stored procedure to update attributes
String ret = insAC.doSetDEC("UPD", DECBean, "Edit", oldDECBean);
// after succcessful update
if ((ret == null) || ret.equals(""))
{
String sOriginAction = (String) session.getAttribute("originAction");
// forward page back to EditDE
if (sOriginAction.equals("editDECfromDE"))
{
DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE");
DEBean.setDE_DEC_IDSEQ(DECBean.getDEC_DEC_IDSEQ());
DEBean.setDE_DEC_NAME(DECBean.getDEC_LONG_NAME());
// reset the attributes
DataManager.setAttribute(session, "originAction", "");
// add DEC Bean into DE BEan
DEBean.setDE_DEC_Bean(DECBean);
CurationServlet deServ = (DataElementServlet) getACServlet("DataElement");
DEBean = (DE_Bean) deServ.getACNames("new", "editDEC", DEBean);
DataManager.setAttribute(session, "m_DE", DEBean);
ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp");
}
// go to search page with refreshed list
else
{
DECBean.setDEC_ALIAS_NAME(DECBean.getDEC_PREFERRED_NAME());
DECBean.setDEC_TYPE_NAME("PRIMARY");
DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, "editDEC");
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
String oldID = DECBean.getDEC_DEC_IDSEQ();
serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Edit", oldID);
ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp");
}
}
// go back to edit page if not successful in update
else
ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); // back to DEC Page
}
/**
* creates new record in the database and display the result. Called from 'doInsertDEC' method when the aciton is
* create new DEC from DEPage. Retrieves the session bean m_DEC. calls 'insAC.setDEC' to update the database.
* forwards the page back to create DE page after successful insert.
*
* If ret is not null stores the statusMessage as error message in session and forwards the page back to
* 'createDECPage.jsp' for Edit.
*
* @param sOrigin
* String value to check where this action originated.
*
* @throws Exception
*/
private void doInsertDECfromDEAction(String sOrigin)
throws Exception
{
HttpSession session = m_classReq.getSession();
InsACService insAC = new InsACService(m_classReq, m_classRes, this);
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
DEC_Bean oldDECBean = (DEC_Bean) session.getAttribute("oldDECBean");
// String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION);
// doInsertDECBlocks(m_classReq, m_classRes, null); //insert any building blocks from Thesaurus first
String ret = insAC.doSetDEC("INS", DECBean, "New", oldDECBean);
// add new dec attributes to de bean and forward to create de page if success.
if ((ret == null) || ret.equals(""))
{
DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE");
DEBean.setDE_DEC_NAME(DECBean.getDEC_LONG_NAME());
DEBean.setDE_DEC_IDSEQ(DECBean.getDEC_DEC_IDSEQ());
// add DEC Bean into DE BEan
DEBean.setDE_DEC_Bean(DECBean);
CurationServlet deServ = (DataElementServlet) getACServlet("DataElement");
DEBean = (DE_Bean) deServ.getACNames("new", "newDEC", DEBean);
DataManager.setAttribute(session, "m_DE", DEBean);
// String sContext = (String) session.getAttribute("sDefaultContext");
// boolean bNewContext = true;
DataManager.setAttribute(session, "originAction", ""); // reset this session attribute
if (sOrigin != null && sOrigin.equals("CreateNewDECfromEditDE"))
ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp");
else
ForwardJSP(m_classReq, m_classRes, "/CreateDEPage.jsp");
}
// go back to create dec page if error
else
{
DataManager.setAttribute(session, "DECPageAction", "validate");
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp"); // send it back to dec page
}
}
/**
* creates new record in the database and display the result. Called from 'doInsertDEC' method when the aciton is
* create new DEC from Menu. Retrieves the session bean m_DEC. calls 'insAC.setVD' to update the database. calls
* 'serAC.refreshData' to get the refreshed search result for template/version forwards the page back to create DEC
* page if new DEC or back to search page if template or version after successful insert.
*
* If ret is not null stores the statusMessage as error message in session and forwards the page back to
* 'createDECPage.jsp' for Edit.
*
* @throws Exception
*/
private void doInsertDECfromMenuAction() throws Exception
{
HttpSession session = m_classReq.getSession();
InsACService insAC = new InsACService(m_classReq, m_classRes, this);
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
String ret = "";
// String ret2 = "";
boolean isUpdateSuccess = true;
String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION);
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
DEC_Bean oldDECBean = (DEC_Bean) session.getAttribute("oldDECBean");
// doInsertDECBlocks(m_classReq, m_classRes, null); //insert any building blocks from Thesaurus first
if (sMenuAction.equals("NewDECVersion"))
{
logger.info("**************called at 1513 of DECs.java");
// udpate the status message with DEC name and ID
storeStatusMsg("Data Element Concept Name : " + DECBean.getDEC_LONG_NAME());
storeStatusMsg("Public ID : " + DECBean.getDEC_DEC_ID());
// creates new version first and updates all other attributes
ret = insAC.setAC_VERSION(null, DECBean, null, "DataElementConcept");
if (ret == null || ret.equals(""))
{
// update other attributes
ret = insAC.doSetDEC("UPD", DECBean, "Version", oldDECBean);
// resetEVSBeans(m_classReq, m_classRes);
if (ret != null && !ret.equals(""))
{
// DataManager.setAttribute(session, "statusMessage", ret + " - Created new version but unable to update
// attributes successfully.");
// add newly created row to searchresults and send it to edit page for update
isUpdateSuccess = false;
// put back old attributes except version, idseq and workflow status
String oldID = oldDECBean.getDEC_DEC_IDSEQ();
String newID = DECBean.getDEC_DEC_IDSEQ();
String newVersion = DECBean.getDEC_VERSION();
DECBean = DECBean.cloneDEC_Bean(oldDECBean);
DECBean.setDEC_DEC_IDSEQ(newID);
DECBean.setDEC_VERSION(newVersion);
DECBean.setDEC_ASL_NAME("DRAFT MOD");
// add newly created dec into the resultset.
serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Version", oldID);
}
}
else
storeStatusMsg("\\t " + ret + " - Unable to create new version successfully.");
}
else
{
logger.info("**************doSetDEC called at 1546 of DECs.java");
ret = insAC.doSetDEC("INS", DECBean, "New", oldDECBean);
}
if ((ret == null) || ret.equals(""))
{
logger.info("**************called at 1551 of DECs.java");
// DataManager.setAttribute(session, "statusMessage", "New Data Element Concept is created successfully.");
DataManager.setAttribute(session, "DECPageAction", "nothing");
// String sContext = (String) session.getAttribute("sDefaultContext");
// boolean bNewContext = true;
DataManager.setAttribute(session, "originAction", ""); // reset this session attribute
// forwards to search page with the refreshed list after success if template or version
if ((sMenuAction.equals("NewDECTemplate")) || (sMenuAction.equals("NewDECVersion")))
{
DataManager.setAttribute(session, "searchAC", "DataElementConcept");
DECBean.setDEC_ALIAS_NAME(DECBean.getDEC_PREFERRED_NAME());
DECBean.setDEC_TYPE_NAME("PRIMARY");
String oldID = oldDECBean.getDEC_DEC_IDSEQ();
if (sMenuAction.equals("NewDECTemplate"))
serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Template", oldID);
else if (sMenuAction.equals("NewDECVersion"))
serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Version", oldID);
ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp");
}
// go back to create dec page to create another one
else
{
logger.info("**************called at 1573 of DECs.java");
DECBean = new DEC_Bean();
DECBean.setDEC_ASL_NAME("DRAFT NEW");
DECBean.setAC_PREF_NAME_TYPE("SYS");
DataManager.setAttribute(session, "m_DEC", DECBean);
EVS_Bean m_OC = new EVS_Bean();
DataManager.setAttribute(session, "m_OC", m_OC);
EVS_Bean m_PC = new EVS_Bean();
DataManager.setAttribute(session, "m_PC", m_PC);
EVS_Bean m_OCQ = new EVS_Bean();
DataManager.setAttribute(session, "m_OCQ", m_OCQ);
EVS_Bean m_PCQ = new EVS_Bean();
DataManager.setAttribute(session, "m_PCQ", m_PCQ);
DataManager.setAttribute(session, "selObjQRow", "");
DataManager.setAttribute(session, "selObjRow", "");
DataManager.setAttribute(session, "selPropQRow", "");
DataManager.setAttribute(session, "selPropRow", "");
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
}
// go back to create dec page if error occurs
else
{
DataManager.setAttribute(session, "DECPageAction", "validate");
// forward to create or edit pages
if (isUpdateSuccess == false){
logger.info("**************called at 1599 of DECs.java");
ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp");
}
else{
logger.info("**************called at 1604 of DECs.java");
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
}
}
/**
* updates bean the selected DEC from the changed values of block edit.
*
* @param DECBeanSR
* selected DEC bean from search result
* @param dec
* DEC_Bean of the changed values.
*
* @throws Exception
*/
private void InsertEditsIntoDECBeanSR(DEC_Bean DECBeanSR, DEC_Bean dec) throws Exception
{
// get all attributes of DECBean, if attribute != "" then set that attribute of DECBeanSR
String sDefinition = dec.getDEC_PREFERRED_DEFINITION();
if (sDefinition == null)
sDefinition = "";
if (!sDefinition.equals(""))
DECBeanSR.setDEC_PREFERRED_DEFINITION(sDefinition);
String sCD_ID = dec.getDEC_CD_IDSEQ();
if (sCD_ID == null)
sCD_ID = "";
if (!sCD_ID.equals(""))
DECBeanSR.setDEC_CD_IDSEQ(sCD_ID);
String sCDName = dec.getDEC_CD_NAME();
if (sCDName == null)
sCDName = "";
if (!sCDName.equals("") && !sCDName.equals(null))
DECBeanSR.setDEC_CD_NAME(sCDName);
//begin===============GF32398========
String RegStatus = dec.getDEC_REG_STATUS();
if (RegStatus == null)
RegStatus = "";
if (!RegStatus.equals(""))
DECBeanSR.setDEC_REG_STATUS(RegStatus);
//end=================GF32398========
String sBeginDate = dec.getDEC_BEGIN_DATE();
if (sBeginDate == null)
sBeginDate = "";
if (!sBeginDate.equals(""))
DECBeanSR.setDEC_BEGIN_DATE(sBeginDate);
String sEndDate = dec.getDEC_END_DATE();
if (sEndDate == null)
sEndDate = "";
if (!sEndDate.equals(""))
DECBeanSR.setDEC_END_DATE(sEndDate);
String sSource = dec.getDEC_SOURCE();
if (sSource == null)
sSource = "";
if (!sSource.equals(""))
DECBeanSR.setDEC_SOURCE(sSource);
String changeNote = dec.getDEC_CHANGE_NOTE();
if (changeNote == null)
changeNote = "";
if (!changeNote.equals(""))
DECBeanSR.setDEC_CHANGE_NOTE(changeNote);
//begin===========GF32398======
String oldReg = DECBeanSR.getDEC_REG_STATUS();
if (oldReg == null)
oldReg = "";
//end=========GF32398=========
// get cs-csi from the page into the DECBean for block edit
Vector<AC_CSI_Bean> vAC_CS = dec.getAC_AC_CSI_VECTOR();
if (vAC_CS != null)
DECBeanSR.setAC_AC_CSI_VECTOR(vAC_CS);
//get the Ref docs from the page into the DEBean for block edit
Vector<REF_DOC_Bean> vAC_REF_DOCS = dec.getAC_REF_DOCS();
if(vAC_REF_DOCS!=null){
Vector<REF_DOC_Bean> temp_REF_DOCS = new Vector<REF_DOC_Bean>();
for(REF_DOC_Bean refBean:vAC_REF_DOCS )
{
if(refBean.getAC_IDSEQ() == DECBeanSR.getDEC_DEC_IDSEQ())
{
temp_REF_DOCS.add(refBean);
}
}
DECBeanSR.setAC_REF_DOCS(temp_REF_DOCS);
}
String sOCL = dec.getDEC_OCL_NAME();
if (sOCL == null)
sOCL = "";
if (!sOCL.equals(""))
{
DECBeanSR.setDEC_OCL_NAME(sOCL);
String sOCCondr = dec.getDEC_OC_CONDR_IDSEQ();
if (sOCCondr == null)
sOCCondr = "";
if (!sOCCondr.equals(""))
DECBeanSR.setDEC_OC_CONDR_IDSEQ(sOCCondr);
String sOCL_IDSEQ = dec.getDEC_OCL_IDSEQ();
if (sOCL_IDSEQ != null && !sOCL_IDSEQ.equals(""))
DECBeanSR.setDEC_OCL_IDSEQ(sOCL_IDSEQ);
}
String sPropL = dec.getDEC_PROPL_NAME();
if (sPropL == null)
sPropL = "";
if (!sPropL.equals(""))
{
DECBeanSR.setDEC_PROPL_NAME(sPropL);
String sPCCondr = dec.getDEC_PROP_CONDR_IDSEQ();
if (sPCCondr == null)
sPCCondr = "";
if (!sPCCondr.equals(""))
DECBeanSR.setDEC_PROP_CONDR_IDSEQ(sPCCondr);
String sPROPL_IDSEQ = dec.getDEC_PROPL_IDSEQ();
if (sPROPL_IDSEQ != null && !sPROPL_IDSEQ.equals(""))
DECBeanSR.setDEC_PROPL_IDSEQ(sPROPL_IDSEQ);
}
// update dec pref type and abbr name
DECBeanSR.setAC_PREF_NAME_TYPE(dec.getAC_PREF_NAME_TYPE());
String status = dec.getDEC_ASL_NAME();
if (status == null)
status = "";
if (!status.equals(""))
DECBeanSR.setDEC_ASL_NAME(status);
String version = dec.getDEC_VERSION();
String lastVersion = (String) DECBeanSR.getDEC_VERSION();
int index = -1;
String pointStr = ".";
String strWhBegNumber = "";
int iWhBegNumber = 0;
index = lastVersion.indexOf(pointStr);
String strPtBegNumber = lastVersion.substring(0, index);
String afterDecimalNumber = lastVersion.substring((index + 1), (index + 2));
if (index == 1)
strWhBegNumber = "";
else if (index == 2)
{
strWhBegNumber = lastVersion.substring(0, index - 1);
Integer WhBegNumber = new Integer(strWhBegNumber);
iWhBegNumber = WhBegNumber.intValue();
}
String strWhEndNumber = ".0";
String beforeDecimalNumber = lastVersion.substring((index - 1), (index));
String sNewVersion = "";
Integer IadNumber = new Integer(0);
Integer IbdNumber = new Integer(0);
String strIncADNumber = "";
String strIncBDNumber = "";
if (version == null)
version = "";
else if (version.equals("Point"))
{
// Point new version
int incrementADNumber = 0;
int incrementBDNumber = 0;
Integer adNumber = new Integer(afterDecimalNumber);
Integer bdNumber = new Integer(strPtBegNumber);
int iADNumber = adNumber.intValue(); // after decimal
int iBDNumber = bdNumber.intValue(); // before decimal
if (iADNumber != 9)
{
incrementADNumber = iADNumber + 1;
IadNumber = new Integer(incrementADNumber);
strIncADNumber = IadNumber.toString();
sNewVersion = strPtBegNumber + "." + strIncADNumber; // + strPtEndNumber;
}
else
// adNumber == 9
{
incrementADNumber = 0;
incrementBDNumber = iBDNumber + 1;
IbdNumber = new Integer(incrementBDNumber);
strIncBDNumber = IbdNumber.toString();
IadNumber = new Integer(incrementADNumber);
strIncADNumber = IadNumber.toString();
sNewVersion = strIncBDNumber + "." + strIncADNumber; // + strPtEndNumber;
}
DECBeanSR.setDEC_VERSION(sNewVersion);
}
else if (version.equals("Whole"))
{
// Whole new version
Integer bdNumber = new Integer(beforeDecimalNumber);
int iBDNumber = bdNumber.intValue();
int incrementBDNumber = iBDNumber + 1;
if (iBDNumber != 9)
{
IbdNumber = new Integer(incrementBDNumber);
strIncBDNumber = IbdNumber.toString();
sNewVersion = strWhBegNumber + strIncBDNumber + strWhEndNumber;
}
else
// before decimal number == 9
{
int incrementWhBegNumber = iWhBegNumber + 1;
Integer IWhBegNumber = new Integer(incrementWhBegNumber);
String strIncWhBegNumber = IWhBegNumber.toString();
IbdNumber = new Integer(0);
strIncBDNumber = IbdNumber.toString();
sNewVersion = strIncWhBegNumber + strIncBDNumber + strWhEndNumber;
}
DECBeanSR.setDEC_VERSION(sNewVersion);
}
}
/**
* update record in the database and display the result. Called from 'doInsertDEC' method when the aciton is
* editing. Retrieves the session bean m_DEC. calls 'insAC.setDEC' to update the database. otherwise calls
* 'serAC.refreshData' to get the refreshed search result forwards the page back to search page with refreshed list
* after updating.
*
* If ret is not null stores the statusMessage as error message in session and forwards the page back to
* 'EditDECPage.jsp' for Edit.
*
* @throws Exception
*/
private void doUpdateDECActionBE() throws Exception
{
HttpSession session = m_classReq.getSession();
DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC");
DataManager.setAttribute(session, "DECEditAction", ""); // reset this
boolean isRefreshed = false;
String ret = ":";
InsACService insAC = new InsACService(m_classReq, m_classRes, this);
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
GetACService getAC = new GetACService(m_classReq, m_classRes, this);
// String sNewOC = (String)session.getAttribute("newObjectClass");
// String sNewProp = (String)session.getAttribute("newProperty");
Vector vBERows = (Vector) session.getAttribute("vBEResult");
int vBESize = vBERows.size();
Integer vBESize2 = new Integer(vBESize);
m_classReq.setAttribute("vBESize", vBESize2);
// String sOC_IDSEQ = "";
// String sProp_IDSEQ = "";
if (vBERows.size() > 0)
{
// Be sure the buffer is loaded when doing versioning.
String newVersion = DECBean.getDEC_VERSION();
if (newVersion == null)
newVersion = "";
boolean newVers = (newVersion.equals("Point") || newVersion.equals("Whole"));
if (newVers)
{
@SuppressWarnings("unchecked")
Vector<AC_Bean> tvec = vBERows;
AltNamesDefsSession.loadAsNew(this, session, tvec);
}
for (int i = 0; i < (vBERows.size()); i++)
{
DEC_Bean DECBeanSR = new DEC_Bean();
DECBeanSR = (DEC_Bean) vBERows.elementAt(i);
DEC_Bean oldDECBean = new DEC_Bean();
oldDECBean = oldDECBean.cloneDEC_Bean(DECBeanSR);
// String oldName = (String) DECBeanSR.getDEC_PREFERRED_NAME();
// gets all the changed attrributes from the page
InsertEditsIntoDECBeanSR(DECBeanSR, DECBean);
// DataManager.setAttribute(session, "m_DEC", DECBeanSR);
String oldID = oldDECBean.getDEC_DEC_IDSEQ();
// udpate the status message with DEC name and ID
storeStatusMsg("Data Element Concept Name : " + DECBeanSR.getDEC_LONG_NAME());
storeStatusMsg("Public ID : " + DECBeanSR.getDEC_DEC_ID());
// creates a new version
if (newVers) // block version
{
// creates new version first and updates all other attributes
String strValid = m_setAC.checkUniqueInContext("Version", "DEC", null, DECBeanSR, null, getAC,
"version");
if (strValid != null && !strValid.equals(""))
ret = "unique constraint";
else
ret = insAC.setAC_VERSION(null, DECBeanSR, null, "DataElementConcept");
if (ret == null || ret.equals(""))
{
ret = insAC.doSetDEC("UPD", DECBeanSR, "BlockVersion", oldDECBean);
// resetEVSBeans(m_classReq, m_classRes);
// add this bean into the session vector
if (ret == null || ret.equals(""))
{
serAC.refreshData(m_classReq, m_classRes, null, DECBeanSR, null, null, "Version", oldID);
isRefreshed = true;
// reset the appened attributes to remove all the checking of the row
Vector vCheck = new Vector();
DataManager.setAttribute(session, "CheckList", vCheck);
DataManager.setAttribute(session, "AppendAction", "Not Appended");
}
}
// alerady exists
else if (ret.indexOf("unique constraint") >= 0)
storeStatusMsg("\\t The version " + DECBeanSR.getDEC_VERSION()
+ " already exists in the data base.\\n");
// some other problem
else
storeStatusMsg("\\t " + ret + " : Unable to create new version "
+ DECBeanSR.getDEC_VERSION() + ".\\n");
}
else
// block edit
{
ret = insAC.doSetDEC("UPD", DECBeanSR, "BlockEdit", oldDECBean);
// forward to search page with refreshed list after successful update
if ((ret == null) || ret.equals(""))
{
serAC.refreshData(m_classReq, m_classRes, null, DECBeanSR, null, null, "Edit", oldID);
isRefreshed = true;
}
}
}
AltNamesDefsSession.blockSave(this, session);
}
// to get the final result vector if not refreshed at all
if (!(isRefreshed))
{
Vector<String> vResult = new Vector<String>();
serAC.getDECResult(m_classReq, m_classRes, vResult, "");
DataManager.setAttribute(session, "results", vResult); // store the final result in the session
DataManager.setAttribute(session, "DECPageAction", "nothing");
}
// forward to search page.
ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp");
}
/**
* The doOpenCreateDECPage method gets the session, gets some values from the createDE page and stores in bean m_DE,
* sets some session attributes, then forwards to CreateDEC page
*
* @throws Exception
*/
public void doOpenCreateDECPage() throws Exception
{
HttpSession session = m_classReq.getSession();
// DataManager.setAttribute(session, "originAction", fromWhere); //"CreateNewDECfromCreateDE");
DE_Bean m_DE = (DE_Bean) session.getAttribute("m_DE");
if (m_DE == null)
m_DE = new DE_Bean();
m_setAC.setDEValueFromPage(m_classReq, m_classRes, m_DE); // store DEC bean
DataManager.setAttribute(session, "m_DE", m_DE);
DEC_Bean m_DEC = new DEC_Bean();
m_DEC.setDEC_ASL_NAME("DRAFT NEW");
m_DEC.setAC_PREF_NAME_TYPE("SYS");
DataManager.setAttribute(session, "m_DEC", m_DEC);
DEC_Bean oldDEC = new DEC_Bean();
oldDEC = oldDEC.cloneDEC_Bean(m_DEC);
DataManager.setAttribute(session, "oldDECBean", oldDEC);
this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes
// DataManager.setAttribute(session, "oldDECBean", m_DEC);
ForwardJSP(m_classReq, m_classRes, "/CreateDECPage.jsp");
}
/**
*
* @throws Exception
*
*/
@SuppressWarnings("unchecked")
private void doRemoveBuildingBlocks() throws Exception
{
HttpSession session = m_classReq.getSession();
String sSelRow = "";
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
Vector<EVS_Bean> vObjectClass = (Vector) session.getAttribute("vObjectClass");
if (vObjectClass == null)
vObjectClass = new Vector<EVS_Bean>();
// int iOCSize = vObjectClass.size();
Vector<EVS_Bean> vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty == null)
vProperty = new Vector<EVS_Bean>();
// int iPropSize = vProperty.size();
String sComp = (String) m_classReq.getParameter("sCompBlocks");
if (sComp == null)
sComp = "";
if (sComp.equals("ObjectClass"))
{
EVS_Bean m_OC = new EVS_Bean();
vObjectClass.setElementAt(m_OC, 0);
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
m_DEC.setDEC_OCL_NAME_PRIMARY("");
m_DEC.setDEC_OC_CONCEPT_CODE("");
m_DEC.setDEC_OC_EVS_CUI_ORIGEN("");
m_DEC.setDEC_OCL_IDSEQ("");
DataManager.setAttribute(session, "RemoveOCBlock", "true");
DataManager.setAttribute(session, "newObjectClass", "true");
}
else if (sComp.equals("Property") || sComp.equals("PropertyClass"))
{
EVS_Bean m_PC = new EVS_Bean();
vProperty.setElementAt(m_PC, 0);
DataManager.setAttribute(session, "vProperty", vProperty);
m_DEC.setDEC_PROPL_NAME_PRIMARY("");
m_DEC.setDEC_PROP_CONCEPT_CODE("");
m_DEC.setDEC_PROP_EVS_CUI_ORIGEN("");
m_DEC.setDEC_PROPL_IDSEQ("");
DataManager.setAttribute(session, "RemovePropBlock", "true");
DataManager.setAttribute(session, "newProperty", "true");
}
else if (sComp.equals("ObjectQualifier"))
{
sSelRow = (String) m_classReq.getParameter("selObjQRow");
if (sSelRow != null && !(sSelRow.equals("")))
{
Integer intObjRow = new Integer(sSelRow);
int intObjRow2 = intObjRow.intValue();
// add 1 because 0 element is OC, not a qualifier
int int1 = intObjRow2 + 1;
if (vObjectClass.size() > (int1))
{
vObjectClass.removeElementAt(int1);
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
}
// m_DEC.setDEC_OBJ_CLASS_QUALIFIER("");
Vector vOCQualifierNames = m_DEC.getDEC_OC_QUALIFIER_NAMES();
if (vOCQualifierNames == null)
vOCQualifierNames = new Vector();
if (vOCQualifierNames.size() > intObjRow2)
vOCQualifierNames.removeElementAt(intObjRow2);
Vector vOCQualifierCodes = m_DEC.getDEC_OC_QUALIFIER_CODES();
if (vOCQualifierCodes == null)
vOCQualifierCodes = new Vector();
if (vOCQualifierCodes.size() > intObjRow2)
vOCQualifierCodes.removeElementAt(intObjRow2);
Vector vOCQualifierDB = m_DEC.getDEC_OC_QUALIFIER_DB();
if (vOCQualifierDB == null)
vOCQualifierDB = new Vector();
if (vOCQualifierDB.size() > intObjRow2)
vOCQualifierDB.removeElementAt(intObjRow2);
m_DEC.setDEC_OC_QUALIFIER_NAMES(vOCQualifierNames);
m_DEC.setDEC_OC_QUALIFIER_CODES(vOCQualifierCodes);
m_DEC.setDEC_OC_QUALIFIER_DB(vOCQualifierDB);
m_DEC.setDEC_OCL_IDSEQ("");
DataManager.setAttribute(session, "RemoveOCBlock", "true");
DataManager.setAttribute(session, "newObjectClass", "true");
DataManager.setAttribute(session, "m_OCQ", null);
}
}
else if (sComp.equals("PropertyQualifier"))
{
sSelRow = (String) m_classReq.getParameter("selPropQRow");
if (sSelRow != null && !(sSelRow.equals("")))
{
Integer intPropRow = new Integer(sSelRow);
int intPropRow2 = intPropRow.intValue();
// add 1 because 0 element is OC, not a qualifier
int int1 = intPropRow2 + 1;
// invert because the list on ui is i9nverse to vector
if (vProperty.size() > (int1))
{
vProperty.removeElementAt(int1);
DataManager.setAttribute(session, "vProperty", vProperty);
}
// m_DEC.setDEC_PROPERTY_QUALIFIER("");
Vector vPropQualifierNames = m_DEC.getDEC_PROP_QUALIFIER_NAMES();
if (vPropQualifierNames == null)
vPropQualifierNames = new Vector();
if (vPropQualifierNames.size() > intPropRow2)
vPropQualifierNames.removeElementAt(intPropRow2);
Vector vPropQualifierCodes = m_DEC.getDEC_PROP_QUALIFIER_CODES();
if (vPropQualifierCodes == null)
vPropQualifierCodes = new Vector();
if (vPropQualifierCodes.size() > intPropRow2)
vPropQualifierCodes.removeElementAt(intPropRow2);
Vector vPropQualifierDB = m_DEC.getDEC_PROP_QUALIFIER_DB();
if (vPropQualifierDB == null)
vPropQualifierDB = new Vector();
if (vPropQualifierDB.size() > intPropRow2)
vPropQualifierDB.removeElementAt(intPropRow2);
m_DEC.setDEC_PROP_QUALIFIER_NAMES(vPropQualifierNames);
m_DEC.setDEC_PROP_QUALIFIER_CODES(vPropQualifierCodes);
m_DEC.setDEC_PROP_QUALIFIER_DB(vPropQualifierDB);
m_DEC.setDEC_PROPL_IDSEQ("");
DataManager.setAttribute(session, "RemovePropBlock", "true");
DataManager.setAttribute(session, "newObjectClass", "true");
DataManager.setAttribute(session, "m_PCQ", null);
}
}
if ( sComp.equals("ObjectClass") || sComp.equals("ObjectQualifier")){
vObjectClass = (Vector)session.getAttribute("vObjectClass");
logger.debug("at line 2225 of DECServlet.java"+vObjectClass.size());
if (vObjectClass != null && vObjectClass.size()>0){
vObjectClass = this.getMatchingThesarusconcept(vObjectClass, "Object Class");
//begin of GF30798
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 2229 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER()+"**"+vObjectClass.size());
}
//end of GF30798
m_DEC = this.updateOCAttribues(vObjectClass, m_DEC);
this.checkChosenConcepts(session, null, null, vObjectClass, "OC");
}
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
}
if (sComp.equals("Property") || sComp.equals("PropertyClass") || sComp.equals("PropertyQualifier")){
vProperty = (Vector)session.getAttribute("vProperty");
if (vProperty != null && vProperty.size()>0){
vProperty = this.getMatchingThesarusconcept(vProperty, "Property");
m_DEC = this.updatePropAttribues(vProperty, m_DEC);
this.checkChosenConcepts(session,null, null, vProperty, "Prop");
}
DataManager.setAttribute(session, "vProperty", vProperty);
}
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC); //GF30798
DataManager.setAttribute(session, "m_DEC", m_DEC);
} // end of doRemoveQualifier
public void doOpenViewPage() throws Exception
{
//System.out.println("I am here open view page");
HttpSession session = m_classReq.getSession();
String acID = (String) m_classReq.getAttribute("acIdseq");
if (acID.equals(""))
acID = m_classReq.getParameter("idseq");
Vector<DEC_Bean> vList = new Vector<DEC_Bean>();
// get DE's attributes from the database again
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this);
if (acID != null && !acID.equals(""))
{
serAC.doDECSearch(acID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "",
"", "", vList, "0");//===gf32398== added one more parameter regstatus
}
if (vList.size() > 0) // get all attributes
{
DEC_Bean DECBean = (DEC_Bean) vList.elementAt(0);
DECBean = serAC.getDECAttributes(DECBean, "openView", "viewDEC");
m_classReq.setAttribute("viewDECId", DECBean.getIDSEQ());
String viewDEC = "viewDEC" + DECBean.getIDSEQ();
DataManager.setAttribute(session, viewDEC, DECBean);
String title = "CDE Curation View DEC "+DECBean.getDEC_LONG_NAME()+ " [" + DECBean.getDEC_DEC_ID() + "v" + DECBean.getDEC_VERSION() +"]";
m_classReq.setAttribute("title", title);
m_classReq.setAttribute("publicID", DECBean.getDEC_DEC_ID());
m_classReq.setAttribute("version", DECBean.getDEC_VERSION());
m_classReq.setAttribute("IncludeViewPage", "EditDEC.jsp") ;
}
}
private DEC_Bean updateOCAttribues(Vector vObjectClass, DEC_Bean decBean) {
HttpSession session = m_classReq.getSession();
// add oc primary attributes to the dec bean
EVS_Bean pBean =(EVS_Bean)vObjectClass.get(0);
String nvpValue = "";
if (checkNVP(pBean)) //JT what is this check for?
nvpValue="::"+pBean.getNVP_CONCEPT_VALUE();
if (pBean.getLONG_NAME() != null)
decBean.setDEC_OCL_NAME_PRIMARY(pBean.getLONG_NAME()+nvpValue);
decBean.setDEC_OC_CONCEPT_CODE(pBean.getCONCEPT_IDENTIFIER());
decBean.setDEC_OC_EVS_CUI_ORIGEN(pBean.getEVS_DATABASE());
//if (pBean.getIDSEQ() != null && pBean.getIDSEQ().length() > 0)
// decBean.setDEC_OCL_IDSEQ(pBean.getIDSEQ());
logger.debug("At line 2218 of DECServlet.java"+decBean.getDEC_OCL_NAME_PRIMARY()+"**"+decBean.getDEC_OC_CONCEPT_CODE()+"**"+decBean.getDEC_OC_EVS_CUI_ORIGEN()+"**"+pBean.getCONTEXT_NAME()+"**"+pBean.getPREFERRED_DEFINITION());
DataManager.setAttribute(session, "m_OC", pBean);
// update qualifier vectors
decBean.setDEC_OC_QUALIFIER_NAMES(null);
decBean.setDEC_OC_QUALIFIER_CODES(null);
decBean.setDEC_OC_QUALIFIER_DB(null);
for (int i=1; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
nvpValue = "";
if (checkNVP(eBean))
nvpValue="::"+eBean.getNVP_CONCEPT_VALUE();
// update qualifier vectors
// add it othe qualifiers attributes of the selected DEC
Vector<String> vOCQualifierNames = decBean.getDEC_OC_QUALIFIER_NAMES();
if (vOCQualifierNames == null)
vOCQualifierNames = new Vector<String>();
vOCQualifierNames.addElement(eBean.getLONG_NAME()+nvpValue);
Vector<String> vOCQualifierCodes = decBean.getDEC_OC_QUALIFIER_CODES();
if (vOCQualifierCodes == null)
vOCQualifierCodes = new Vector<String>();
vOCQualifierCodes.addElement(eBean.getCONCEPT_IDENTIFIER());
Vector<String> vOCQualifierDB = decBean.getDEC_OC_QUALIFIER_DB();
if (vOCQualifierDB == null)
vOCQualifierDB = new Vector<String>();
vOCQualifierDB.addElement(eBean.getEVS_DATABASE());
decBean.setDEC_OC_QUALIFIER_NAMES(vOCQualifierNames);
decBean.setDEC_OC_QUALIFIER_CODES(vOCQualifierCodes);
decBean.setDEC_OC_QUALIFIER_DB(vOCQualifierDB);
logger.debug("At line 2247 of DECServlet.java"+Arrays.asList(vOCQualifierNames)+"**"+Arrays.asList(vOCQualifierCodes)+"**"+Arrays.asList(vOCQualifierDB));
// if (vOCQualifierNames.size()>0)
// decBean.setDEC_OBJ_CLASS_QUALIFIER((String)vOCQualifierNames.elementAt(0));
// store it in the session
DataManager.setAttribute(session, "m_OCQ", eBean);
}
return decBean;
}
private DEC_Bean updatePropAttribues(Vector vProperty, DEC_Bean decBean) {
HttpSession session = m_classReq.getSession();
// add prop primary attributes to the dec bean
EVS_Bean pBean =(EVS_Bean)vProperty.get(0);
String nvpValue = "";
if (checkNVP(pBean))
nvpValue="::"+pBean.getNVP_CONCEPT_VALUE();
if (pBean.getLONG_NAME() != null)
decBean.setDEC_PROPL_NAME_PRIMARY(pBean.getLONG_NAME()+nvpValue);
decBean.setDEC_PROP_CONCEPT_CODE(pBean.getCONCEPT_IDENTIFIER());
decBean.setDEC_PROP_EVS_CUI_ORIGEN(pBean.getEVS_DATABASE());
//decBean.setDEC_PROPL_IDSEQ(pBean.getIDSEQ());
DataManager.setAttribute(session, "m_PC", pBean);
logger.debug("At line 2269 of DECServlet.java"+decBean.getDEC_PROPL_NAME_PRIMARY()+"**"+decBean.getDEC_PROP_CONCEPT_CODE()+"**"+decBean.getDEC_PROP_EVS_CUI_ORIGEN()+"**"+pBean.getCONTEXT_NAME()+"**"+pBean.getPREFERRED_DEFINITION());
// update qualifier vectors
decBean.setDEC_PROP_QUALIFIER_NAMES(null);
decBean.setDEC_PROP_QUALIFIER_CODES(null);
decBean.setDEC_PROP_QUALIFIER_DB(null);
for (int i=1; i<vProperty.size();i++){
EVS_Bean eBean =(EVS_Bean)vProperty.get(i);
nvpValue="";
if (checkNVP(eBean))
nvpValue="::"+eBean.getNVP_CONCEPT_VALUE();
// update qualifier vectors
// add it the qualifiers attributes of the selected DEC
Vector<String> vPropQualifierNames = decBean.getDEC_PROP_QUALIFIER_NAMES();
if (vPropQualifierNames == null)
vPropQualifierNames = new Vector<String>();
vPropQualifierNames.addElement(eBean.getLONG_NAME()+nvpValue);
Vector<String> vPropQualifierCodes = decBean.getDEC_PROP_QUALIFIER_CODES();
if (vPropQualifierCodes == null)
vPropQualifierCodes = new Vector<String>();
vPropQualifierCodes.addElement(eBean.getCONCEPT_IDENTIFIER());
Vector<String> vPropQualifierDB = decBean.getDEC_PROP_QUALIFIER_DB();
if (vPropQualifierDB == null)
vPropQualifierDB = new Vector<String>();
vPropQualifierDB.addElement(eBean.getEVS_DATABASE());
decBean.setDEC_PROP_QUALIFIER_NAMES(vPropQualifierNames);
decBean.setDEC_PROP_QUALIFIER_CODES(vPropQualifierCodes);
decBean.setDEC_PROP_QUALIFIER_DB(vPropQualifierDB);
logger.debug("At line 2253 of DECServlet.java"+Arrays.asList(vPropQualifierNames)+"**"+Arrays.asList(vPropQualifierCodes)+"**"+Arrays.asList(vPropQualifierDB));
// if(vPropQualifierNames.size()>0)
// decBean.setDEC_PROPERTY_QUALIFIER((String)vPropQualifierNames.elementAt(0));
DataManager.setAttribute(session, "m_PCQ", eBean);
}
return decBean;
}
public static boolean checkNVP(EVS_Bean eCon) {
return (eCon.getNAME_VALUE_PAIR_IND() > 0 && eCon.getLONG_NAME().indexOf("::") < 1 && eCon.getNVP_CONCEPT_VALUE().length() > 0); //JT not sure what is this checking for, second portion could be buggy!!!
}
}
| false | true | private void doDECUseSelection(String nameAction)
{
try
{
HttpSession session = m_classReq.getSession();
String sSelRow = "";
boolean selectedOCQualifiers = false;
boolean selectedPropQualifiers = false;
// InsACService insAC = new InsACService(m_classReq, m_classRes, this);
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
Vector<EVS_Bean> vObjectClass = (Vector) session.getAttribute("vObjectClass");
//begin of GF30798
if(vObjectClass != null && vObjectClass.size() > 0) {
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
if(eBean != null)
logger.debug("At line 1001 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
//end of GF30798
if (vObjectClass == null || vObjectClass.size() == 0) {
vObjectClass = new Vector<EVS_Bean>();
//reset the attributes for keeping track of non-caDSR choices...
session.removeAttribute("chosenOCCodes");
session.removeAttribute("chosenOCDefs");
session.removeAttribute("changedOCDefsWarning");
}
Vector<EVS_Bean> vProperty = (Vector) session.getAttribute("vProperty");
//begin of GF30798
if(vProperty != null && vProperty.size() > 0) {
for (int i=0; i<vProperty.size();i++){
EVS_Bean eBean =(EVS_Bean)vProperty.get(i);
if(eBean != null)
logger.debug("At line 1015 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
//end of GF30798
if (vProperty == null || vProperty.size() == 0) {
vProperty = new Vector<EVS_Bean>();
//reset the attributes for keeping track of non-caDSR choices...
session.removeAttribute("chosenPropCodes");
session.removeAttribute("chosenPropDefs");
session.removeAttribute("changedPropDefsWarning");
}
if (vObjectClass.size()>1){
selectedOCQualifiers = true;
}
if (vProperty.size()>1){
selectedPropQualifiers = true;
}
Vector vAC = null;
EVS_Bean blockBean = new EVS_Bean();
String sComp = (String) m_classReq.getParameter("sCompBlocks");
if (sComp == null)
sComp = "";
// get the search bean from the selected row
sSelRow = (String) m_classReq.getParameter("selCompBlockRow");
vAC = (Vector) session.getAttribute("vACSearch");
logger.debug("At Line 951 of DECServlet.java"+Arrays.asList(vAC));
if (vAC == null)
vAC = new Vector();
if (sSelRow != null && !sSelRow.equals(""))
{
String sObjRow = sSelRow.substring(2);
Integer intObjRow = new Integer(sObjRow);
int intObjRow2 = intObjRow.intValue();
if (vAC.size() > intObjRow2 - 1)
blockBean = (EVS_Bean) vAC.elementAt(intObjRow2);
String sNVP = (String) m_classReq.getParameter("nvpConcept");
if (sNVP != null && !sNVP.equals(""))
{
blockBean.setNVP_CONCEPT_VALUE(sNVP);
String sName = blockBean.getLONG_NAME();
blockBean.setLONG_NAME(sName + "::" + sNVP);
blockBean.setPREFERRED_DEFINITION(blockBean.getPREFERRED_DEFINITION() + "::" + sNVP);
}
logger.debug("At Line 977 of DECServlet.java"+sNVP+"**"+blockBean.getLONG_NAME()+"**"+ blockBean.getPREFERRED_DEFINITION());
//System.out.println(sNVP + sComp + blockBean.getLONG_NAME() + blockBean.getPREFERRED_DEFINITION());
}
else
{
storeStatusMsg("Unable to get the selected row from the " + sComp + " search results.\\n"
+ "Please try again.");
return;
}
// send it back if unable to obtion the concept
if (blockBean == null || blockBean.getLONG_NAME() == null)
{
storeStatusMsg("Unable to obtain concept from the selected row of the " + sComp
+ " search results.\\n" + "Please try again.");
return;
}
//Store chosen concept code and definition for later use in alt. definition.
String code = blockBean.getCONCEPT_IDENTIFIER();
String def = blockBean.getPREFERRED_DEFINITION();
Vector<String> codes = null;
Vector<String> defs = null;
if (sComp.startsWith("Object")) {
if (session.getAttribute("chosenOCCodes") == null || ((Vector)session.getAttribute("chosenOCCodes")).size() == 0) {
codes = new Vector<String>();
defs = new Vector<String>();
} else {
codes =(Vector<String>) session.getAttribute("chosenOCCodes");
defs = (Vector<String>) session.getAttribute("chosenOCDefs");
}
logger.debug("At line 1009 of DECServlet.java"+codes +"***"+defs);
}
else if (sComp.startsWith("Prop")) {
if (session.getAttribute("chosenPropCodes") == null) {
codes = new Vector<String>();
defs = new Vector<String>();
} else {
codes =(Vector<String>) session.getAttribute("chosenPropCodes");
defs = (Vector<String>) session.getAttribute("chosenPropDefs");
}
logger.debug("At line 1102 of DECServlet.java"+Arrays.asList(codes) +"***"+Arrays.asList(defs));
}
if (!codes.contains(code)) {
codes.add(code);
defs.add(def);
logger.debug("At line 1108 of DECServlet.java"+Arrays.asList(codes) +"***"+Arrays.asList(defs));
}
// do the primary search selection action
if (sComp.equals("ObjectClass") || sComp.equals("Property") || sComp.equals("PropertyClass"))
{
logger.debug("At line 1114 of DECServlet.java");
if (blockBean.getEVS_DATABASE().equals("caDSR"))
{
logger.debug("At line 1117 of DECServlet.java");
// split it if rep term, add concept class to the list if evs id exists
if (blockBean.getCONDR_IDSEQ() == null || blockBean.getCONDR_IDSEQ().equals(""))
{
logger.debug("At line 1121 of DECServlet.java");
if (blockBean.getCONCEPT_IDENTIFIER() == null || blockBean.getCONCEPT_IDENTIFIER().equals(""))
{
storeStatusMsg("This " + sComp
+ " is not associated to a concept, so the data is suspect. \\n"
+ "Please choose another " + sComp + " .");
}
else
// concept class search results
{
if (sComp.equals("ObjectClass"))
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Primary");
else
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Primary");
}
}
else{
logger.debug("At line 1139 of DECServlet.java ");
// split it into concepts for object class or property search results
splitIntoConcepts(sComp, blockBean, nameAction);
}
}
else
// evs search results
{
logger.debug("At line 1147 of DECServlet.java ");
if (sComp.equals("ObjectClass"))
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Primary");
else
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Primary");
}
}
else if (sComp.equals("ObjectQualifier"))
{
logger.debug("At line 1081 of DECServlet.java ");
// Do this to reserve zero position in vector for primary concept
if (vObjectClass.size() < 1)
{
EVS_Bean OCBean = new EVS_Bean();
vObjectClass.addElement(OCBean);
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
}
m_DEC.setDEC_OCL_IDSEQ("");
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Qualifier");
}
else if (sComp.equals("PropertyQualifier"))
{
logger.debug("At line 1078 of DECServlet.java ");
// Do this to reserve zero position in vector for primary concept
if (vProperty.size() < 1)
{
EVS_Bean PCBean = new EVS_Bean();
vProperty.addElement(PCBean);
DataManager.setAttribute(session, "vProperty", vProperty);
}
m_DEC.setDEC_PROPL_IDSEQ("");
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Qualifier");
}
if ( sComp.equals("ObjectClass") || sComp.equals("ObjectQualifier")){
vObjectClass = (Vector) session.getAttribute("vObjectClass");
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1186 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
if (vObjectClass != null && vObjectClass.size()>0){
logger.debug("at line 1189 of DECServlet.java"+vObjectClass.size());
vObjectClass = this.getMatchingThesarusconcept(vObjectClass, "Object Class"); //get the matching concept from EVS based on the caDSR's CDR (object class)
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1193 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER()+"**"+vObjectClass.size());
}
m_DEC = this.updateOCAttribues(vObjectClass, m_DEC); //populate caDSR's DEC bean based on VO (from EVS results)
this.checkChosenConcepts(session,codes, defs, vObjectClass, "OC"); //make sure user's chosen/edited definition is not different from the EVS definition???
}
if (blockBean.getcaDSR_COMPONENT() != null && blockBean.getcaDSR_COMPONENT().equals("Concept Class")){
logger.debug("At line 1139 of DECServlet.java");
m_DEC.setDEC_OCL_IDSEQ("");
}else {//Object Class or from vocabulary
if(blockBean.getcaDSR_COMPONENT() != null && !selectedOCQualifiers){//if selected existing object class (JT just checking getcaDSR_COMPONENT???)
logger.debug("At line 1108 of DECServlet.java");
ValidationStatusBean statusBean = new ValidationStatusBean();
statusBean.setStatusMessage("** Using existing "+blockBean.getcaDSR_COMPONENT()+" "+blockBean.getLONG_NAME()+" ("+blockBean.getID()+"v"+blockBean.getVERSION()+") from "+blockBean.getCONTEXT_NAME());
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(blockBean.getCONDR_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(blockBean.getIDSEQ());
session.setAttribute("ocStatusBean", statusBean);
}else{
m_DEC.setDEC_OCL_IDSEQ("");
}
}
DataManager.setAttribute(session, "vObjectClass", vObjectClass); //save EVS VO in session
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1220 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
if (sComp.equals("Property") || sComp.equals("PropertyClass") || sComp.equals("PropertyQualifier")){
vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty != null && vProperty.size()>0){
vProperty = this.getMatchingThesarusconcept(vProperty, "Property");
logger.debug("At line 1127 of DECServlet.java "+Arrays.asList(vProperty));
m_DEC = this.updatePropAttribues(vProperty, m_DEC);
boolean warning = false;
//Rebuilding codes and defs to get rid of unused codes
Vector<String> rebuiltCodes = new Vector<String>();
Vector<String> rebuiltDefs = new Vector<String>();
//added in 4.1 to check if OC exists and set alternate def. if used an EVS concept
this.checkChosenConcepts(session,codes, defs, vProperty, "Prop");
}
if (blockBean.getcaDSR_COMPONENT()!= null && blockBean.getcaDSR_COMPONENT().equals("Concept Class")){
logger.debug("At line 1141 of DECServlet.java");
m_DEC.setDEC_PROPL_IDSEQ("");
}else{//Property or from vocabulary
if(blockBean.getcaDSR_COMPONENT() != null && !selectedPropQualifiers){//if selected existing property
logger.debug("At line 1145 of DECServlet.java");
ValidationStatusBean statusBean = new ValidationStatusBean();
statusBean.setStatusMessage("** Using existing "+blockBean.getcaDSR_COMPONENT()+" "+blockBean.getLONG_NAME()+" ("+blockBean.getID()+"v"+blockBean.getVERSION()+") from "+blockBean.getCONTEXT_NAME());
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(blockBean.getCONDR_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(blockBean.getIDSEQ());
session.setAttribute("propStatusBean", statusBean);
}else{
m_DEC.setDEC_PROPL_IDSEQ("");
}
}
DataManager.setAttribute(session, "vProperty", vProperty);
logger.debug("At line 1158 of DECServlet.java"+Arrays.asList(vProperty));
}
// rebuild new name if not appending
EVS_Bean nullEVS = null;
if (nameAction.equals("newName"))
m_DEC = (DEC_Bean) this.getACNames(nullEVS, "Search", m_DEC);
else if (nameAction.equals("blockName"))
m_DEC = (DEC_Bean) this.getACNames(nullEVS, "blockName", m_DEC);
DataManager.setAttribute(session, "m_DEC", m_DEC); //set the user's selection + data from EVS in the DEC in session (for submission later on)
}
catch (Exception e)
{
this.logger.error("ERROR - doDECUseSelection : " + e.toString(), e);
}
} // end of doDECUseSelection
| private void doDECUseSelection(String nameAction)
{
try
{
HttpSession session = m_classReq.getSession();
String sSelRow = "";
boolean selectedOCQualifiers = false;
boolean selectedPropQualifiers = false;
// InsACService insAC = new InsACService(m_classReq, m_classRes, this);
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
if (m_DEC == null)
m_DEC = new DEC_Bean();
m_setAC.setDECValueFromPage(m_classReq, m_classRes, m_DEC);
Vector<EVS_Bean> vObjectClass = (Vector) session.getAttribute("vObjectClass");
//begin of GF30798
String evsDef = null;
if(vObjectClass != null && vObjectClass.size() > 0) {
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
if(eBean != null) {
logger.debug("At line 1001 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
evsDef = eBean.getPREFERRED_DEFINITION();
}
}
}
boolean changedOCDefsWarningFlag = false;
String userSelectedDef = (String) m_classReq.getParameter("userSelectedDef");
if(!userSelectedDef.equals(evsDef)) { //TBD - should check user selection against caDSR not EVS !!!
changedOCDefsWarningFlag = true;
}
//end of GF30798
if (!changedOCDefsWarningFlag && vObjectClass == null || vObjectClass.size() == 0) {
vObjectClass = new Vector<EVS_Bean>();
//reset the attributes for keeping track of non-caDSR choices...
session.removeAttribute("chosenOCCodes");
session.removeAttribute("chosenOCDefs");
session.removeAttribute("changedOCDefsWarning");
}
Vector<EVS_Bean> vProperty = (Vector) session.getAttribute("vProperty");
//begin of GF30798
if(vProperty != null && vProperty.size() > 0) {
for (int i=0; i<vProperty.size();i++){
EVS_Bean eBean =(EVS_Bean)vProperty.get(i);
if(eBean != null)
logger.debug("At line 1015 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
//end of GF30798
if (vProperty == null || vProperty.size() == 0) {
vProperty = new Vector<EVS_Bean>();
//reset the attributes for keeping track of non-caDSR choices...
session.removeAttribute("chosenPropCodes");
session.removeAttribute("chosenPropDefs");
session.removeAttribute("changedPropDefsWarning");
}
if (vObjectClass.size()>1){
selectedOCQualifiers = true;
}
if (vProperty.size()>1){
selectedPropQualifiers = true;
}
Vector vAC = null;
EVS_Bean blockBean = new EVS_Bean();
String sComp = (String) m_classReq.getParameter("sCompBlocks");
if (sComp == null)
sComp = "";
// get the search bean from the selected row
sSelRow = (String) m_classReq.getParameter("selCompBlockRow");
vAC = (Vector) session.getAttribute("vACSearch");
logger.debug("At Line 951 of DECServlet.java"+Arrays.asList(vAC));
if (vAC == null)
vAC = new Vector();
if (sSelRow != null && !sSelRow.equals(""))
{
String sObjRow = sSelRow.substring(2);
Integer intObjRow = new Integer(sObjRow);
int intObjRow2 = intObjRow.intValue();
if (vAC.size() > intObjRow2 - 1)
blockBean = (EVS_Bean) vAC.elementAt(intObjRow2);
String sNVP = (String) m_classReq.getParameter("nvpConcept");
if (sNVP != null && !sNVP.equals(""))
{
blockBean.setNVP_CONCEPT_VALUE(sNVP);
String sName = blockBean.getLONG_NAME();
blockBean.setLONG_NAME(sName + "::" + sNVP);
blockBean.setPREFERRED_DEFINITION(blockBean.getPREFERRED_DEFINITION() + "::" + sNVP);
}
logger.debug("At Line 977 of DECServlet.java"+sNVP+"**"+blockBean.getLONG_NAME()+"**"+ blockBean.getPREFERRED_DEFINITION());
//System.out.println(sNVP + sComp + blockBean.getLONG_NAME() + blockBean.getPREFERRED_DEFINITION());
}
else
{
storeStatusMsg("Unable to get the selected row from the " + sComp + " search results.\\n"
+ "Please try again.");
return;
}
// send it back if unable to obtion the concept
if (blockBean == null || blockBean.getLONG_NAME() == null)
{
storeStatusMsg("Unable to obtain concept from the selected row of the " + sComp
+ " search results.\\n" + "Please try again.");
return;
}
//Store chosen concept code and definition for later use in alt. definition.
String code = blockBean.getCONCEPT_IDENTIFIER();
String def = blockBean.getPREFERRED_DEFINITION();
Vector<String> codes = null;
Vector<String> defs = null;
if (sComp.startsWith("Object")) {
if (session.getAttribute("chosenOCCodes") == null || ((Vector)session.getAttribute("chosenOCCodes")).size() == 0) {
codes = new Vector<String>();
defs = new Vector<String>();
} else {
codes =(Vector<String>) session.getAttribute("chosenOCCodes");
defs = (Vector<String>) session.getAttribute("chosenOCDefs");
}
logger.debug("At line 1009 of DECServlet.java"+codes +"***"+defs);
}
else if (sComp.startsWith("Prop")) {
if (session.getAttribute("chosenPropCodes") == null) {
codes = new Vector<String>();
defs = new Vector<String>();
} else {
codes =(Vector<String>) session.getAttribute("chosenPropCodes");
defs = (Vector<String>) session.getAttribute("chosenPropDefs");
}
logger.debug("At line 1102 of DECServlet.java"+Arrays.asList(codes) +"***"+Arrays.asList(defs));
}
if (!codes.contains(code)) {
codes.add(code);
defs.add(def);
logger.debug("At line 1108 of DECServlet.java"+Arrays.asList(codes) +"***"+Arrays.asList(defs));
}
// do the primary search selection action
if (sComp.equals("ObjectClass") || sComp.equals("Property") || sComp.equals("PropertyClass"))
{
logger.debug("At line 1114 of DECServlet.java");
if (blockBean.getEVS_DATABASE().equals("caDSR"))
{
logger.debug("At line 1117 of DECServlet.java");
// split it if rep term, add concept class to the list if evs id exists
if (blockBean.getCONDR_IDSEQ() == null || blockBean.getCONDR_IDSEQ().equals(""))
{
logger.debug("At line 1121 of DECServlet.java");
if (blockBean.getCONCEPT_IDENTIFIER() == null || blockBean.getCONCEPT_IDENTIFIER().equals(""))
{
storeStatusMsg("This " + sComp
+ " is not associated to a concept, so the data is suspect. \\n"
+ "Please choose another " + sComp + " .");
}
else
// concept class search results
{
if (sComp.equals("ObjectClass"))
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Primary");
else
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Primary");
}
}
else{
logger.debug("At line 1139 of DECServlet.java ");
// split it into concepts for object class or property search results
splitIntoConcepts(sComp, blockBean, nameAction);
}
}
else
// evs search results
{
logger.debug("At line 1147 of DECServlet.java ");
if (sComp.equals("ObjectClass"))
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Primary");
else
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Primary");
}
}
else if (sComp.equals("ObjectQualifier"))
{
logger.debug("At line 1081 of DECServlet.java ");
// Do this to reserve zero position in vector for primary concept
if (vObjectClass.size() < 1)
{
EVS_Bean OCBean = new EVS_Bean();
vObjectClass.addElement(OCBean);
DataManager.setAttribute(session, "vObjectClass", vObjectClass);
}
m_DEC.setDEC_OCL_IDSEQ("");
m_DEC = this.addOCConcepts(nameAction, m_DEC, blockBean, "Qualifier");
}
else if (sComp.equals("PropertyQualifier"))
{
logger.debug("At line 1078 of DECServlet.java ");
// Do this to reserve zero position in vector for primary concept
if (vProperty.size() < 1)
{
EVS_Bean PCBean = new EVS_Bean();
vProperty.addElement(PCBean);
DataManager.setAttribute(session, "vProperty", vProperty);
}
m_DEC.setDEC_PROPL_IDSEQ("");
m_DEC = this.addPropConcepts(nameAction, m_DEC, blockBean, "Qualifier");
}
if ( sComp.equals("ObjectClass") || sComp.equals("ObjectQualifier")){
vObjectClass = (Vector) session.getAttribute("vObjectClass");
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1186 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
if (vObjectClass != null && vObjectClass.size()>0){
logger.debug("at line 1189 of DECServlet.java"+vObjectClass.size());
vObjectClass = this.getMatchingThesarusconcept(vObjectClass, "Object Class"); //get the matching concept from EVS based on the caDSR's CDR (object class)
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1193 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER()+"**"+vObjectClass.size());
}
m_DEC = this.updateOCAttribues(vObjectClass, m_DEC); //populate caDSR's DEC bean based on VO (from EVS results)
this.checkChosenConcepts(session,codes, defs, vObjectClass, "OC"); //make sure user's chosen/edited definition is not different from the EVS definition???
}
if (blockBean.getcaDSR_COMPONENT() != null && blockBean.getcaDSR_COMPONENT().equals("Concept Class")){
logger.debug("At line 1139 of DECServlet.java");
m_DEC.setDEC_OCL_IDSEQ("");
}else {//Object Class or from vocabulary
if(blockBean.getcaDSR_COMPONENT() != null && !selectedOCQualifiers){//if selected existing object class (JT just checking getcaDSR_COMPONENT???)
logger.debug("At line 1108 of DECServlet.java");
ValidationStatusBean statusBean = new ValidationStatusBean();
statusBean.setStatusMessage("** Using existing "+blockBean.getcaDSR_COMPONENT()+" "+blockBean.getLONG_NAME()+" ("+blockBean.getID()+"v"+blockBean.getVERSION()+") from "+blockBean.getCONTEXT_NAME());
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(blockBean.getCONDR_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(blockBean.getIDSEQ());
session.setAttribute("ocStatusBean", statusBean);
}else{
m_DEC.setDEC_OCL_IDSEQ("");
}
}
DataManager.setAttribute(session, "vObjectClass", vObjectClass); //save EVS VO in session
for (int i=0; i<vObjectClass.size();i++){
EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i);
logger.debug("At line 1220 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER());
}
}
if (sComp.equals("Property") || sComp.equals("PropertyClass") || sComp.equals("PropertyQualifier")){
vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty != null && vProperty.size()>0){
vProperty = this.getMatchingThesarusconcept(vProperty, "Property");
logger.debug("At line 1127 of DECServlet.java "+Arrays.asList(vProperty));
m_DEC = this.updatePropAttribues(vProperty, m_DEC);
boolean warning = false;
//Rebuilding codes and defs to get rid of unused codes
Vector<String> rebuiltCodes = new Vector<String>();
Vector<String> rebuiltDefs = new Vector<String>();
//added in 4.1 to check if OC exists and set alternate def. if used an EVS concept
this.checkChosenConcepts(session,codes, defs, vProperty, "Prop");
}
if (blockBean.getcaDSR_COMPONENT()!= null && blockBean.getcaDSR_COMPONENT().equals("Concept Class")){
logger.debug("At line 1141 of DECServlet.java");
m_DEC.setDEC_PROPL_IDSEQ("");
}else{//Property or from vocabulary
if(blockBean.getcaDSR_COMPONENT() != null && !selectedPropQualifiers){//if selected existing property
logger.debug("At line 1145 of DECServlet.java");
ValidationStatusBean statusBean = new ValidationStatusBean();
statusBean.setStatusMessage("** Using existing "+blockBean.getcaDSR_COMPONENT()+" "+blockBean.getLONG_NAME()+" ("+blockBean.getID()+"v"+blockBean.getVERSION()+") from "+blockBean.getCONTEXT_NAME());
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(blockBean.getCONDR_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(blockBean.getIDSEQ());
session.setAttribute("propStatusBean", statusBean);
}else{
m_DEC.setDEC_PROPL_IDSEQ("");
}
}
DataManager.setAttribute(session, "vProperty", vProperty);
logger.debug("At line 1158 of DECServlet.java"+Arrays.asList(vProperty));
}
// rebuild new name if not appending
EVS_Bean nullEVS = null;
if (nameAction.equals("newName"))
m_DEC = (DEC_Bean) this.getACNames(nullEVS, "Search", m_DEC);
else if (nameAction.equals("blockName"))
m_DEC = (DEC_Bean) this.getACNames(nullEVS, "blockName", m_DEC);
DataManager.setAttribute(session, "m_DEC", m_DEC); //set the user's selection + data from EVS in the DEC in session (for submission later on)
}
catch (Exception e)
{
this.logger.error("ERROR - doDECUseSelection : " + e.toString(), e);
}
} // end of doDECUseSelection
|
diff --git a/Sudoku/src/nl/avans/IN13SAh/sudoku/SudokuView.java b/Sudoku/src/nl/avans/IN13SAh/sudoku/SudokuView.java
index e6dff73..c2d1fb2 100644
--- a/Sudoku/src/nl/avans/IN13SAh/sudoku/SudokuView.java
+++ b/Sudoku/src/nl/avans/IN13SAh/sudoku/SudokuView.java
@@ -1,430 +1,434 @@
package nl.avans.IN13SAh.sudoku;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
// TODO: Auto-generated Javadoc
/**
* The Class CanvasView. A custom view for drawing the sudoku field.
*/
class SudokuView extends View {
/** The listener. Used for responding to view events. */
private OnSudokuEventChangeListener listener;
/** The x value of the selection. */
private int selX;
/** The y value of the selection. */
private int selY;
/** The rectangle object of the selection. */
private Rect selRect;
/** The width and height of the grid in pixels. */
private int height, width;
/** The board size. (for example 9 meaning 9x9) */
private int boardSize;
/** Value for enabeling touch responseness for the view. */
private boolean enableTouch = true;
final GestureDetector gestureDetector = new GestureDetector(getContext(),
new GestureDetector.SimpleOnGestureListener() {
@Override
public void onLongPress(MotionEvent e) {
if (listener.ShouldDrawSelection()) {
int x, y;
x = (int) (e.getX() / width);
y = (int) (e.getY() / height);
Vibrator vib = (Vibrator) SudokuView.this.getContext()
.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(300);
listener.OnLongPressAction(SudokuView.this, x, y);
}
}
@Override
public boolean onDoubleTap(MotionEvent e) {
gestureDetector.setIsLongpressEnabled(false);
return true;
};
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (!enableTouch)
return true;
select((int) (e.getX() / width), (int) (e.getY() / height));
// De listener wordt aangeroepen. Belangrijk!
listener.OnSelectionChanged(SudokuView.this, selX, selY,
new Point((int) e.getX(), (int) e.getY()));
Log.d("PuzzleView", "onTouchEvent: " + selX + ", " + selY);
return true;
};
});
/**
* The listener interface for receiving onSudokuEventChange events. The
* class that is interested in processing a onSudokuEventChange event
* implements this interface, and the object created with that class is
* registered with a component using the component's
* <code>addOnSudokuEventChangeListener<code> method. When
* the onSudokuEventChange event occurs, that object's appropriate
* method is invoked.
*
* @see OnSudokuEventChangeEvent
*/
public interface OnSudokuEventChangeListener {
/**
* On selection changed.
*
* @param v
* view object (will be Canvasview)
* @param selX
* the x value of the selection
* @param selY
* the y value of the selection
* @param p
* the point that was touched (containing pixels)
*/
void OnSelectionChanged(View v, int selX, int selY, Point p);
/**
* Method the view uses to get information about a position (from a game
* object).
*
* @param v
* view object (will be canvasview)
* @param x
* x value in the grid
* @param y
* y value in the grid
* @return the int value of a specific field
*/
int OnGetCurrentValueOfPosition(View v, int x, int y);
boolean ShouldDrawSelection();
void OnLongPressAction(View v, int x, int y);
boolean OnCheckCurrentValueIsAllowed(View v, int x, int y);
}
Bitmap background; // maar 1 keer inladen.
/**
* Instantiates a new canvas view.
*
* @param context
* the context (an activity for example)
* @param boardSize
* the board size (for example 9 for 9x9)
*/
public SudokuView(Context context, int boardSize) {
super(context);
selX = -1;
selY = -1;
/* achtergrond plaatje laden en schalen naar device size */
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
this.background = BitmapFactory.decodeResource(getResources(),
R.drawable.startup_background);
this.background = Bitmap.createScaledBitmap(this.background,
display.getWidth(), display.getHeight(), true);
this.boardSize = boardSize;
this.selRect = new Rect();
setFocusable(true);
setFocusableInTouchMode(true);
}
/**
* Sets the on sudoku event change listener.
*
* @param listener
* set the sudokueventchange listener for this view.
*/
public void setOnSudokuEventChangeListener(
OnSudokuEventChangeListener listener) {
this.listener = listener;
}
/* Methode om de view aan of uit te zetten. */
/**
* Enable touch for this view.
*
* @param newValue
* the new enableTouch value
*/
public void enableTouch(boolean newValue) {
this.enableTouch = newValue;
}
/**
* Gets the sel x.
*
* @return the sel x
*/
public int getSelX() {
return (int) selX;
}
/**
* Gets the sel y.
*
* @return the sel y
*/
public int getSelY() {
return (int) selY;
}
/**
* Sets the board size.
*
* @param newSize
* the new board size (for example: 9 for 9x9)
*/
public void setBoardSize(int newSize) {
this.boardSize = newSize;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSaveInstanceState()
*/
@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putInt("selX", selX);
bundle.putInt("selY", selY);
bundle.putParcelable("viewState", super.onSaveInstanceState());
return bundle;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onRestoreInstanceState(android.os.Parcelable)
*/
@Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = new Bundle();
// select(bundle.getInt("selX"), bundle.getInt("selY"))
bundle.getParcelable("viewState");
super.onRestoreInstanceState(state);
}
/*
* (non-Javadoc)
*
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
gestureDetector.setIsLongpressEnabled(true);
return true;
}
/**
* Private method for switchting the selection (visual) in the view.
*
* @param x
* the x
* @param y
* the y
* @return true, if successful
*/
private boolean select(int x, int y) {
invalidate(selRect);
selX = Math.min(Math.max(x, 0), boardSize - 1);
selY = Math.min(Math.max(y, 0), boardSize - 1);
getRect(selX, selY, selRect);
invalidate(selRect);
return true;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
Log.d("PuzzleView", "drawing bg");
// draw background
Paint background = loadColor(R.color.puzzle_background);
if (!listener.ShouldDrawSelection()) { // geen selectie, wel plaatje
canvas.drawBitmap(this.background, 0f, 0f, background);
} else {
canvas.drawRect(0.0f, 0.0f, (float) getWidth(),
(float) getHeight(), background);
Log.d("PuzzleView", "drawing lines");
// draw board
// line colors
Paint dark = loadColor(R.color.puzzle_dark);
dark.setStrokeWidth(2);
Paint hilite = loadColor(R.color.puzzle_hilite);
Paint light = loadColor(R.color.puzzle_light);
// draw lines
int i = 0;
while (i < boardSize) {
// minor lines
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
// major lines
- if (i % (boardSize / 3) == 0) { // TODO grootte van grid ipv 3
+ if (i % (boardSize / (Math.sqrt(boardSize))) == 0) { // TODO
+ // grootte
+ // van
+ // grid
+ // ipv 3
canvas.drawLine(0, i * height, getWidth(), i * height, dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
i++;
}
// draw numbers
Log.d("PuzzleView", "drawing numbers");
Paint foreground = loadColor(R.color.puzzle_foreground);
foreground.setStyle(Style.FILL);
foreground.setTextSize((float) (height * 0.75));
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);
FontMetrics fm = foreground.getFontMetrics();
float x = width / 2;
float y = height / 2 - (fm.ascent + fm.descent) / 2;
i = 0;
int j = 0;
while (i < boardSize) {
j = 0;
while (j < boardSize) {
int celwaarde = listener.OnGetCurrentValueOfPosition(this,
i, j);
// lege string bij nul.
String celtext = celwaarde == 0 ? "" : "" + celwaarde;
canvas.drawText(celtext, i * width + x, j * height + y,
foreground);
// draw isAllowed field marking
if (!listener.OnCheckCurrentValueIsAllowed(this, i, j)) {
Rect isAllowedRect = new Rect();
getRect(i, j, isAllowedRect);
Paint isAllowedPaint = loadColor(R.color.puzzle_wrongplace);
isAllowedPaint.setAlpha(80);
canvas.drawRect(isAllowedRect, isAllowedPaint);
}
j++;
}
i++;
}
// draw hints
/*
* if (Prefs.getHints(getContext)) colors = [
* loadColor(R.color.puzzle_hint_0),
* loadColor(R.color.puzzle_hint_1),
* loadColor(R.color.puzzle_hint_2) ] r = Rect.new i = 0 while (i<9)
* j = 0 while (j<9) used [email protected](i,j) moves_left = 9 -
* used.size if (moves_left < colors.size) getRect(i, j, r)
* canvas.drawRect(r,Paint(colors.get(moves_left))) end j+=1 end
* i+=1 end end
*/
// draw selection
Paint selected = loadColor(R.color.puzzle_selected);
selected.setAlpha(80);
canvas.drawRect(selRect, selected);
}
// Draw call!
super.onDraw(canvas);
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSizeChanged(int, int, int, int)
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
Log.d("PuzzleView", "size changed: #{w}x#{h}");
width = (int) (w / boardSize);
height = (int) (h / boardSize);
getRect(selX, selY, selRect);
super.onSizeChanged(w, h, oldw, oldh);
}
/**
* Gets the rect. Used for getting a rect object at a specific position in
* the sudoku canvas.
*
* @param x
* the x
* @param y
* the y
* @param rect
* the rect
* @return the rect
*/
private Rect getRect(int x, int y, Rect rect) {
rect.set(x * width, y * height, x * width + width, y * height + height);
return rect;
}
/**
* Load color. Create a paint object with a color key. Used in drawing.
*
* @param key
* the key
* @return the paint
*/
private Paint loadColor(int key) {
Paint paint = new Paint();
paint.setColor(getResources().getColor(key));
return paint;
}
}
| true | true | protected void onDraw(Canvas canvas) {
Log.d("PuzzleView", "drawing bg");
// draw background
Paint background = loadColor(R.color.puzzle_background);
if (!listener.ShouldDrawSelection()) { // geen selectie, wel plaatje
canvas.drawBitmap(this.background, 0f, 0f, background);
} else {
canvas.drawRect(0.0f, 0.0f, (float) getWidth(),
(float) getHeight(), background);
Log.d("PuzzleView", "drawing lines");
// draw board
// line colors
Paint dark = loadColor(R.color.puzzle_dark);
dark.setStrokeWidth(2);
Paint hilite = loadColor(R.color.puzzle_hilite);
Paint light = loadColor(R.color.puzzle_light);
// draw lines
int i = 0;
while (i < boardSize) {
// minor lines
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
// major lines
if (i % (boardSize / 3) == 0) { // TODO grootte van grid ipv 3
canvas.drawLine(0, i * height, getWidth(), i * height, dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
i++;
}
// draw numbers
Log.d("PuzzleView", "drawing numbers");
Paint foreground = loadColor(R.color.puzzle_foreground);
foreground.setStyle(Style.FILL);
foreground.setTextSize((float) (height * 0.75));
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);
FontMetrics fm = foreground.getFontMetrics();
float x = width / 2;
float y = height / 2 - (fm.ascent + fm.descent) / 2;
i = 0;
int j = 0;
while (i < boardSize) {
j = 0;
while (j < boardSize) {
int celwaarde = listener.OnGetCurrentValueOfPosition(this,
i, j);
// lege string bij nul.
String celtext = celwaarde == 0 ? "" : "" + celwaarde;
canvas.drawText(celtext, i * width + x, j * height + y,
foreground);
// draw isAllowed field marking
if (!listener.OnCheckCurrentValueIsAllowed(this, i, j)) {
Rect isAllowedRect = new Rect();
getRect(i, j, isAllowedRect);
Paint isAllowedPaint = loadColor(R.color.puzzle_wrongplace);
isAllowedPaint.setAlpha(80);
canvas.drawRect(isAllowedRect, isAllowedPaint);
}
j++;
}
i++;
}
// draw hints
/*
* if (Prefs.getHints(getContext)) colors = [
* loadColor(R.color.puzzle_hint_0),
* loadColor(R.color.puzzle_hint_1),
* loadColor(R.color.puzzle_hint_2) ] r = Rect.new i = 0 while (i<9)
* j = 0 while (j<9) used [email protected](i,j) moves_left = 9 -
* used.size if (moves_left < colors.size) getRect(i, j, r)
* canvas.drawRect(r,Paint(colors.get(moves_left))) end j+=1 end
* i+=1 end end
*/
// draw selection
Paint selected = loadColor(R.color.puzzle_selected);
selected.setAlpha(80);
canvas.drawRect(selRect, selected);
}
// Draw call!
super.onDraw(canvas);
}
| protected void onDraw(Canvas canvas) {
Log.d("PuzzleView", "drawing bg");
// draw background
Paint background = loadColor(R.color.puzzle_background);
if (!listener.ShouldDrawSelection()) { // geen selectie, wel plaatje
canvas.drawBitmap(this.background, 0f, 0f, background);
} else {
canvas.drawRect(0.0f, 0.0f, (float) getWidth(),
(float) getHeight(), background);
Log.d("PuzzleView", "drawing lines");
// draw board
// line colors
Paint dark = loadColor(R.color.puzzle_dark);
dark.setStrokeWidth(2);
Paint hilite = loadColor(R.color.puzzle_hilite);
Paint light = loadColor(R.color.puzzle_light);
// draw lines
int i = 0;
while (i < boardSize) {
// minor lines
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
hilite);
// major lines
if (i % (boardSize / (Math.sqrt(boardSize))) == 0) { // TODO
// grootte
// van
// grid
// ipv 3
canvas.drawLine(0, i * height, getWidth(), i * height, dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
i++;
}
// draw numbers
Log.d("PuzzleView", "drawing numbers");
Paint foreground = loadColor(R.color.puzzle_foreground);
foreground.setStyle(Style.FILL);
foreground.setTextSize((float) (height * 0.75));
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);
FontMetrics fm = foreground.getFontMetrics();
float x = width / 2;
float y = height / 2 - (fm.ascent + fm.descent) / 2;
i = 0;
int j = 0;
while (i < boardSize) {
j = 0;
while (j < boardSize) {
int celwaarde = listener.OnGetCurrentValueOfPosition(this,
i, j);
// lege string bij nul.
String celtext = celwaarde == 0 ? "" : "" + celwaarde;
canvas.drawText(celtext, i * width + x, j * height + y,
foreground);
// draw isAllowed field marking
if (!listener.OnCheckCurrentValueIsAllowed(this, i, j)) {
Rect isAllowedRect = new Rect();
getRect(i, j, isAllowedRect);
Paint isAllowedPaint = loadColor(R.color.puzzle_wrongplace);
isAllowedPaint.setAlpha(80);
canvas.drawRect(isAllowedRect, isAllowedPaint);
}
j++;
}
i++;
}
// draw hints
/*
* if (Prefs.getHints(getContext)) colors = [
* loadColor(R.color.puzzle_hint_0),
* loadColor(R.color.puzzle_hint_1),
* loadColor(R.color.puzzle_hint_2) ] r = Rect.new i = 0 while (i<9)
* j = 0 while (j<9) used [email protected](i,j) moves_left = 9 -
* used.size if (moves_left < colors.size) getRect(i, j, r)
* canvas.drawRect(r,Paint(colors.get(moves_left))) end j+=1 end
* i+=1 end end
*/
// draw selection
Paint selected = loadColor(R.color.puzzle_selected);
selected.setAlpha(80);
canvas.drawRect(selRect, selected);
}
// Draw call!
super.onDraw(canvas);
}
|
diff --git a/game/things/ShopKeeper.java b/game/things/ShopKeeper.java
index 9d4d339..0aa931b 100644
--- a/game/things/ShopKeeper.java
+++ b/game/things/ShopKeeper.java
@@ -1,84 +1,84 @@
package game.things;
import game.*;
import java.util.*;
import serialization.*;
public class ShopKeeper extends Character implements Containable, Namable {
public static void makeSerializer(final SerializerUnion<GameThing> union, final GameWorld world){
union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){
public String type(GameThing g){
return g instanceof ShopKeeper? "shopkeeper" : null;
}
});
union.addSerializer("shopkeeper", new Serializer<GameThing>(){
public Tree write(GameThing o){
ShopKeeper in = (ShopKeeper)o;
Tree out = new Tree();
- out.add(new Tree.Entry("renderer", new Tree(in.name)));
+ out.add(new Tree.Entry("renderer", new Tree(in.renderer())));
out.add(new Tree.Entry("name", new Tree(in.name)));
out.add(new Tree.Entry("parts", Serializers.map(Serializers.Serializer_String, Container.serializer(union.serializer(), world)).write(in.parts)));
return out;
}
public GameThing read(Tree in) throws ParseException {
return new ShopKeeper(world,
in.find("renderer").value(),
in.find("name").value(),
Serializers.map(Serializers.Serializer_String, Container.serializer(union.serializer(), world)).read(in.find("parts")));
}
});
}
private final Map<String, Container> parts;
private String name;
private ShopKeeper(GameWorld world, String r, String n, Map<String, Container> p){
super(world, r);
name = n;
parts = p;
health(1000);
update();
}
public ShopKeeper(GameWorld w, String r, String n){
this(w, r, n, new HashMap<String, Container>());
}
public String name(){
return name;
}
public Container addPart(String name){
Container c = new Container(world());
parts.put(name, c);
update();
return c;
}
public List<String> interactions(){
List<String> out = new LinkedList<String>();
for(String n : parts.keySet())
out.add("buy " + n);
out.addAll(super.interactions());
return out;
}
public void interact(String name, Player who){
for(Map.Entry<String, Container> kv : parts.entrySet())
if(name.equals("buy " + kv.getKey()))
who.showContainer(kv.getValue(), "Buying " + kv.getKey());
super.interact(name, who);
}
public String name(String s){
return name = s;
}
public Map<String, Container> getContainers(){
return new HashMap<String, Container>(parts);
}
}
| true | true | public static void makeSerializer(final SerializerUnion<GameThing> union, final GameWorld world){
union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){
public String type(GameThing g){
return g instanceof ShopKeeper? "shopkeeper" : null;
}
});
union.addSerializer("shopkeeper", new Serializer<GameThing>(){
public Tree write(GameThing o){
ShopKeeper in = (ShopKeeper)o;
Tree out = new Tree();
out.add(new Tree.Entry("renderer", new Tree(in.name)));
out.add(new Tree.Entry("name", new Tree(in.name)));
out.add(new Tree.Entry("parts", Serializers.map(Serializers.Serializer_String, Container.serializer(union.serializer(), world)).write(in.parts)));
return out;
}
public GameThing read(Tree in) throws ParseException {
return new ShopKeeper(world,
in.find("renderer").value(),
in.find("name").value(),
Serializers.map(Serializers.Serializer_String, Container.serializer(union.serializer(), world)).read(in.find("parts")));
}
});
}
| public static void makeSerializer(final SerializerUnion<GameThing> union, final GameWorld world){
union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){
public String type(GameThing g){
return g instanceof ShopKeeper? "shopkeeper" : null;
}
});
union.addSerializer("shopkeeper", new Serializer<GameThing>(){
public Tree write(GameThing o){
ShopKeeper in = (ShopKeeper)o;
Tree out = new Tree();
out.add(new Tree.Entry("renderer", new Tree(in.renderer())));
out.add(new Tree.Entry("name", new Tree(in.name)));
out.add(new Tree.Entry("parts", Serializers.map(Serializers.Serializer_String, Container.serializer(union.serializer(), world)).write(in.parts)));
return out;
}
public GameThing read(Tree in) throws ParseException {
return new ShopKeeper(world,
in.find("renderer").value(),
in.find("name").value(),
Serializers.map(Serializers.Serializer_String, Container.serializer(union.serializer(), world)).read(in.find("parts")));
}
});
}
|
diff --git a/src/powercrystals/minefactoryreloaded/MineFactoryReloadedCore.java b/src/powercrystals/minefactoryreloaded/MineFactoryReloadedCore.java
index 9cd55565..f699bedf 100644
--- a/src/powercrystals/minefactoryreloaded/MineFactoryReloadedCore.java
+++ b/src/powercrystals/minefactoryreloaded/MineFactoryReloadedCore.java
@@ -1,653 +1,653 @@
package powercrystals.minefactoryreloaded;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDispenser;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraft.world.World;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.Property;
import net.minecraftforge.event.Event.Result;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.player.BonemealEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.liquids.LiquidContainerData;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidDictionary;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.oredict.OreDictionary;
import powercrystals.core.mod.BaseMod;
import powercrystals.core.updater.IUpdateableMod;
import powercrystals.core.updater.UpdateManager;
import powercrystals.minefactoryreloaded.block.BlockConveyor;
import powercrystals.minefactoryreloaded.block.BlockDecorativeStone;
import powercrystals.minefactoryreloaded.block.BlockFactoryDecorativeBricks;
import powercrystals.minefactoryreloaded.block.BlockFactoryGlass;
import powercrystals.minefactoryreloaded.block.BlockFactoryGlassPane;
import powercrystals.minefactoryreloaded.block.BlockFactoryMachine;
import powercrystals.minefactoryreloaded.block.BlockFactoryRoad;
import powercrystals.minefactoryreloaded.block.BlockFluidFactory;
import powercrystals.minefactoryreloaded.block.BlockRailCargoDropoff;
import powercrystals.minefactoryreloaded.block.BlockRailCargoPickup;
import powercrystals.minefactoryreloaded.block.BlockRailPassengerDropoff;
import powercrystals.minefactoryreloaded.block.BlockRailPassengerPickup;
import powercrystals.minefactoryreloaded.block.BlockRedstoneCable;
import powercrystals.minefactoryreloaded.block.BlockRubberLeaves;
import powercrystals.minefactoryreloaded.block.BlockRubberSapling;
import powercrystals.minefactoryreloaded.block.BlockRubberWood;
import powercrystals.minefactoryreloaded.block.BlockVanillaGlassPane;
import powercrystals.minefactoryreloaded.block.BlockVanillaIce;
import powercrystals.minefactoryreloaded.block.ItemBlockConveyor;
import powercrystals.minefactoryreloaded.block.ItemBlockDecorativeStone;
import powercrystals.minefactoryreloaded.block.ItemBlockFactoryDecorativeBrick;
import powercrystals.minefactoryreloaded.block.ItemBlockFactoryGlass;
import powercrystals.minefactoryreloaded.block.ItemBlockFactoryGlassPane;
import powercrystals.minefactoryreloaded.block.ItemBlockFactoryMachine;
import powercrystals.minefactoryreloaded.block.ItemBlockFactoryRoad;
import powercrystals.minefactoryreloaded.block.ItemBlockVanillaIce;
import powercrystals.minefactoryreloaded.entity.EntitySafariNet;
import powercrystals.minefactoryreloaded.gui.MFRGUIHandler;
import powercrystals.minefactoryreloaded.item.ItemCeramicDye;
import powercrystals.minefactoryreloaded.item.ItemFactory;
import powercrystals.minefactoryreloaded.item.ItemFactoryBucket;
import powercrystals.minefactoryreloaded.item.ItemFactoryHammer;
import powercrystals.minefactoryreloaded.item.ItemMilkBottle;
import powercrystals.minefactoryreloaded.item.ItemPortaSpawner;
import powercrystals.minefactoryreloaded.item.ItemSafariNet;
import powercrystals.minefactoryreloaded.item.ItemSafariNetLauncher;
import powercrystals.minefactoryreloaded.item.ItemSpyglass;
import powercrystals.minefactoryreloaded.item.ItemStraw;
import powercrystals.minefactoryreloaded.item.ItemSyringeCure;
import powercrystals.minefactoryreloaded.item.ItemSyringeGrowth;
import powercrystals.minefactoryreloaded.item.ItemSyringeHealth;
import powercrystals.minefactoryreloaded.item.ItemSyringeSlime;
import powercrystals.minefactoryreloaded.item.ItemSyringeZombie;
import powercrystals.minefactoryreloaded.item.ItemUpgrade;
import powercrystals.minefactoryreloaded.item.ItemXpExtractor;
import powercrystals.minefactoryreloaded.net.ClientPacketHandler;
import powercrystals.minefactoryreloaded.net.ConnectionHandler;
import powercrystals.minefactoryreloaded.net.IMFRProxy;
import powercrystals.minefactoryreloaded.net.ServerPacketHandler;
import powercrystals.minefactoryreloaded.setup.BehaviorDispenseSafariNet;
import powercrystals.minefactoryreloaded.setup.Machine;
import powercrystals.minefactoryreloaded.setup.MineFactoryReloadedFuelHandler;
import powercrystals.minefactoryreloaded.setup.MineFactoryReloadedWorldGen;
import powercrystals.minefactoryreloaded.setup.recipe.Vanilla;
import powercrystals.minefactoryreloaded.setup.village.VillageCreationHandler;
import powercrystals.minefactoryreloaded.setup.village.VillageTradeHandler;
import powercrystals.minefactoryreloaded.tile.TileEntityConveyor;
import powercrystals.minefactoryreloaded.tile.TileRedstoneCable;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.NetworkMod.SidedPacketHandler;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.common.registry.VillagerRegistry;
import cpw.mods.fml.relauncher.Side;
@Mod(modid = MineFactoryReloadedCore.modId, name = MineFactoryReloadedCore.modName, version = MineFactoryReloadedCore.version,
dependencies = "after:BuildCraft|Core;after:BuildCraft|Factory;after:BuildCraft|Energy;after:BuildCraft|Builders;after:BuildCraft|Transport;after:IC2;required-after:PowerCrystalsCore;before:Forestry")
@NetworkMod(clientSideRequired = true, serverSideRequired = false,
clientPacketHandlerSpec = @SidedPacketHandler(channels = { MineFactoryReloadedCore.modNetworkChannel }, packetHandler = ClientPacketHandler.class),
serverPacketHandlerSpec = @SidedPacketHandler(channels = { MineFactoryReloadedCore.modNetworkChannel }, packetHandler = ServerPacketHandler.class),
connectionHandler = ConnectionHandler.class)
public class MineFactoryReloadedCore extends BaseMod implements IUpdateableMod
{
@SidedProxy(clientSide = "powercrystals.minefactoryreloaded.net.ClientProxy", serverSide = "powercrystals.minefactoryreloaded.net.CommonProxy")
public static IMFRProxy proxy;
public static final String modId = "MineFactoryReloaded";
public static final String modNetworkChannel = "MFReloaded";
public static final String version = "1.5.1R2.4.1B1";
public static final String modName = "Minefactory Reloaded";
public static final String guiFolder = "/powercrystals/minefactoryreloaded/textures/gui/";
public static final String villagerFolder = "/powercrystals/minefactoryreloaded/textures/villager/";
public static final String tileEntityFolder = "/powercrystals/minefactoryreloaded/textures/tileentity/";
public static int renderIdConveyor = 1000;
public static int renderIdFactoryGlassPane = 1001;
public static int renderIdRedstoneCable = 1002;
public static int renderIdFluidClassic = 1003;
public static Map<Integer, Block> machineBlocks = new HashMap<Integer, Block>();
public static Block conveyorBlock;
public static Block factoryGlassBlock;
public static Block factoryGlassPaneBlock;
public static Block factoryRoadBlock;
public static Block factoryDecorativeBrickBlock;
public static Block factoryDecorativeStoneBlock;
public static Block rubberWoodBlock;
public static Block rubberLeavesBlock;
public static Block rubberSaplingBlock;
public static Block railPickupCargoBlock;
public static Block railDropoffCargoBlock;
public static Block railPickupPassengerBlock;
public static Block railDropoffPassengerBlock;
public static BlockRedstoneCable rednetCableBlock;
public static Block milkLiquid;
public static Block sludgeLiquid;
public static Block sewageLiquid;
public static Block essenceLiquid;
public static Block biofuelLiquid;
public static Item machineItem;
public static Item factoryHammerItem;
public static Item fertilizerItem;
public static Item plasticSheetItem;
public static Item rubberBarItem;
public static Item rawPlasticItem;
public static Item sewageBucketItem;
public static Item sludgeBucketItem;
public static Item mobEssenceBucketItem;
public static Item syringeEmptyItem;
public static Item syringeHealthItem;
public static Item syringeGrowthItem;
public static Item rawRubberItem;
public static Item machineBaseItem;
public static Item safariNetItem;
public static Item ceramicDyeItem;
public static Item blankRecordItem;
public static Item syringeZombieItem;
public static Item safariNetSingleItem;
public static Item bioFuelBucketItem;
public static Item upgradeItem;
public static Item safariNetLauncherItem;
public static Item sugarCharcoalItem;
public static Item milkBottleItem;
public static Item spyglassItem;
public static Item portaSpawnerItem;
public static Item strawItem;
public static Item xpExtractorItem;
public static Item syringeSlimeItem;
public static Item syringeCureItem;
// client config
public static Property spyglassRange;
// common config
public static Property machineBlock0Id;
public static Property machineBlock1Id;
public static Property conveyorBlockId;
public static Property factoryGlassBlockId;
public static Property factoryGlassPaneBlockId;
public static Property factoryRoadBlockId;
public static Property factoryDecorativeBrickBlockId;
public static Property factoryDecorativeStoneBlockId;
public static Property rubberWoodBlockId;
public static Property rubberLeavesBlockId;
public static Property rubberSaplingBlockId;
public static Property railPickupCargoBlockId;
public static Property railDropoffCargoBlockId;
public static Property railPickupPassengerBlockId;
public static Property railDropoffPassengerBlockId;
public static Property rednetCableBlockId;
public static Property milkStillBlockId;
public static Property sludgeStillBlockId;
public static Property sewageStillBlockId;
public static Property essenceStillBlockId;
public static Property biofuelStillBlockId;
public static Property hammerItemId;
public static Property milkItemId;
public static Property sludgeItemId;
public static Property sewageItemId;
public static Property mobEssenceItemId;
public static Property fertilizerItemId;
public static Property plasticSheetItemId;
public static Property rawPlasticItemId;
public static Property rubberBarItemId;
public static Property sewageBucketItemId;
public static Property sludgeBucketItemId;
public static Property mobEssenceBucketItemId;
public static Property syringeEmptyItemId;
public static Property syringeHealthItemId;
public static Property syringeGrowthItemId;
public static Property rawRubberItemId;
public static Property machineBaseItemId;
public static Property safariNetItemId;
public static Property ceramicDyeId;
public static Property blankRecordId;
public static Property syringeZombieId;
public static Property safariNetSingleItemId;
public static Property bioFuelItemId;
public static Property bioFuelBucketItemId;
public static Property upgradeItemId;
public static Property safariNetLauncherItemId;
public static Property sugarCharcoalItemId;
public static Property milkBottleItemId;
public static Property spyglassItemId;
public static Property portaSpawnerItemId;
public static Property strawItemId;
public static Property xpExtractorItemId;
public static Property syringeSlimeItemId;
public static Property syringeCureItemId;
public static Property zoolologistEntityId;
public static Property treeSearchMaxVertical;
public static Property treeSearchMaxHorizontal;
public static Property verticalHarvestSearchMaxVertical;
public static Property rubberTreeWorldGen;
public static Property mfrLakeWorldGen;
public static Property enableBonemealFertilizing;
public static Property enableCheapDSU;
public static Property enableMossyCobbleRecipe;
public static Property conveyorCaptureNonItems;
public static Property playSounds;
public static Property vanillaOverrideGlassPane;
public static Property vanillaOverrideIce;
public static Property vanillaOverrideMilkBucket;
public static Property enableCompatibleAutoEnchanter;
public static Property enableSlipperyRoads;
public static Property rubberTreeBiomeWhitelist;
public static Property rubberTreeBiomeBlacklist;
public static Property passengerRailSearchMaxHorizontal;
public static Property passengerRailSearchMaxVertical;
private static MineFactoryReloadedCore instance;
public static MineFactoryReloadedCore instance()
{
return instance;
}
@PreInit
public void preInit(FMLPreInitializationEvent evt)
{
setConfigFolderBase(evt.getModConfigurationDirectory());
loadCommonConfig(getCommonConfig());
loadClientConfig(getClientConfig());
extractLang(new String[] { "en_US", "es_AR", "es_ES", "es_MX", "es_UY", "es_VE" });
loadLang();
}
@Init
public void init(FMLInitializationEvent evt)
{
instance = this;
conveyorBlock = new BlockConveyor(conveyorBlockId.getInt());
machineBlocks.put(0, new BlockFactoryMachine(machineBlock0Id.getInt(), 0));
machineBlocks.put(1, new BlockFactoryMachine(machineBlock1Id.getInt(), 1));
factoryGlassBlock = new BlockFactoryGlass(factoryGlassBlockId.getInt());
factoryGlassPaneBlock = new BlockFactoryGlassPane(factoryGlassPaneBlockId.getInt());
factoryRoadBlock = new BlockFactoryRoad(factoryRoadBlockId.getInt());
factoryDecorativeBrickBlock = new BlockFactoryDecorativeBricks(factoryDecorativeBrickBlockId.getInt());
factoryDecorativeStoneBlock = new BlockDecorativeStone(factoryDecorativeStoneBlockId.getInt());
rubberWoodBlock = new BlockRubberWood(rubberWoodBlockId.getInt());
rubberLeavesBlock = new BlockRubberLeaves(rubberLeavesBlockId.getInt());
rubberSaplingBlock = new BlockRubberSapling(rubberSaplingBlockId.getInt());
railDropoffCargoBlock = new BlockRailCargoDropoff(railDropoffCargoBlockId.getInt());
railPickupCargoBlock = new BlockRailCargoPickup(railPickupCargoBlockId.getInt());
railDropoffPassengerBlock = new BlockRailPassengerDropoff(railDropoffPassengerBlockId.getInt());
railPickupPassengerBlock = new BlockRailPassengerPickup(railPickupPassengerBlockId.getInt());
rednetCableBlock = new BlockRedstoneCable(rednetCableBlockId.getInt());
milkLiquid = new BlockFluidFactory(milkStillBlockId.getInt(), "milk");
sludgeLiquid = new BlockFluidFactory(sludgeStillBlockId.getInt(), "sludge");
sewageLiquid = new BlockFluidFactory(sewageStillBlockId.getInt(), "sewage");
essenceLiquid = new BlockFluidFactory(essenceStillBlockId.getInt(), "essence");
biofuelLiquid = new BlockFluidFactory(biofuelStillBlockId.getInt(), "biofuel");
factoryHammerItem = (new ItemFactoryHammer(hammerItemId.getInt())).setUnlocalizedName("mfr.hammer").setMaxStackSize(1);
fertilizerItem = (new ItemFactory(fertilizerItemId.getInt())).setUnlocalizedName("mfr.fertilizer");
plasticSheetItem = (new ItemFactory(plasticSheetItemId.getInt())).setUnlocalizedName("mfr.plastic.sheet");
rawPlasticItem = (new ItemFactory(rawPlasticItemId.getInt())).setUnlocalizedName("mfr.plastic.raw");
rubberBarItem = (new ItemFactory(rubberBarItemId.getInt())).setUnlocalizedName("mfr.rubber.bar");
sewageBucketItem = (new ItemFactoryBucket(sewageBucketItemId.getInt(), sewageLiquid.blockID)).setUnlocalizedName("mfr.bucket.sewage").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
sludgeBucketItem = (new ItemFactoryBucket(sludgeBucketItemId.getInt(), sludgeLiquid.blockID)).setUnlocalizedName("mfr.bucket.sludge").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
mobEssenceBucketItem = (new ItemFactoryBucket(mobEssenceBucketItemId.getInt(), essenceLiquid.blockID)).setUnlocalizedName("mfr.bucket.essence").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
syringeEmptyItem = (new ItemFactory(syringeEmptyItemId.getInt())).setUnlocalizedName("mfr.syringe.empty");
syringeHealthItem = (new ItemSyringeHealth()).setUnlocalizedName("mfr.syringe.health").setContainerItem(syringeEmptyItem);
syringeGrowthItem = (new ItemSyringeGrowth()).setUnlocalizedName("mfr.syringe.growth").setContainerItem(syringeEmptyItem);
rawRubberItem = (new ItemFactory(rawRubberItemId.getInt())).setUnlocalizedName("mfr.rubber.raw");
machineBaseItem = (new ItemFactory(machineBaseItemId.getInt())).setUnlocalizedName("mfr.machineblock");
safariNetItem = (new ItemSafariNet(safariNetItemId.getInt())).setUnlocalizedName("mfr.safarinet.reusable");
ceramicDyeItem = (new ItemCeramicDye(ceramicDyeId.getInt())).setUnlocalizedName("mfr.ceramicdye");
blankRecordItem = (new ItemFactory(blankRecordId.getInt())).setUnlocalizedName("mfr.record.blank").setMaxStackSize(1);
syringeZombieItem = (new ItemSyringeZombie()).setUnlocalizedName("mfr.syringe.zombie").setContainerItem(syringeEmptyItem);
safariNetSingleItem = (new ItemSafariNet(safariNetSingleItemId.getInt())).setUnlocalizedName("mfr.safarinet.singleuse");
bioFuelBucketItem = (new ItemFactoryBucket(bioFuelBucketItemId.getInt(), biofuelLiquid.blockID)).setUnlocalizedName("mfr.bucket.biofuel").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
upgradeItem = (new ItemUpgrade(upgradeItemId.getInt())).setUnlocalizedName("mfr.upgrade.radius").setMaxStackSize(1);
safariNetLauncherItem = (new ItemSafariNetLauncher(safariNetLauncherItemId.getInt())).setUnlocalizedName("mfr.safarinet.launcher").setMaxStackSize(1);
sugarCharcoalItem = (new ItemFactory(sugarCharcoalItemId.getInt())).setUnlocalizedName("mfr.sugarcharcoal");
milkBottleItem = (new ItemMilkBottle(milkBottleItemId.getInt())).setUnlocalizedName("mfr.milkbottle").setMaxStackSize(1);
spyglassItem = (new ItemSpyglass(spyglassItemId.getInt())).setUnlocalizedName("mfr.spyglass").setMaxStackSize(1);
portaSpawnerItem = (new ItemPortaSpawner(portaSpawnerItemId.getInt())).setUnlocalizedName("mfr.portaspawner").setMaxStackSize(1);
strawItem = (new ItemStraw(strawItemId.getInt())).setUnlocalizedName("mfr.straw").setMaxStackSize(1);
xpExtractorItem = (new ItemXpExtractor(xpExtractorItemId.getInt())).setUnlocalizedName("mfr.xpextractor").setMaxStackSize(1);
syringeSlimeItem = (new ItemSyringeSlime(syringeSlimeItemId.getInt())).setUnlocalizedName("mfr.syringe.slime").setContainerItem(syringeEmptyItem);
syringeCureItem = (new ItemSyringeCure(syringeCureItemId.getInt())).setUnlocalizedName("mfr.syringe.cure").setContainerItem(syringeEmptyItem);
for(Entry<Integer, Block> machine : machineBlocks.entrySet())
{
GameRegistry.registerBlock(machine.getValue(), ItemBlockFactoryMachine.class, machine.getValue().getUnlocalizedName());
}
GameRegistry.registerBlock(conveyorBlock, ItemBlockConveyor.class, conveyorBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryGlassBlock, ItemBlockFactoryGlass.class, factoryGlassBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryGlassPaneBlock, ItemBlockFactoryGlassPane.class, factoryGlassPaneBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryRoadBlock, ItemBlockFactoryRoad.class, factoryRoadBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryDecorativeBrickBlock, ItemBlockFactoryDecorativeBrick.class, factoryDecorativeBrickBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryDecorativeStoneBlock, ItemBlockDecorativeStone.class, factoryDecorativeStoneBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberWoodBlock, rubberWoodBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberLeavesBlock, rubberLeavesBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberSaplingBlock, rubberSaplingBlock.getUnlocalizedName());
GameRegistry.registerBlock(railPickupCargoBlock, railPickupCargoBlock.getUnlocalizedName());
GameRegistry.registerBlock(railDropoffCargoBlock, railDropoffCargoBlock.getUnlocalizedName());
GameRegistry.registerBlock(railPickupPassengerBlock, railPickupPassengerBlock.getUnlocalizedName());
GameRegistry.registerBlock(railDropoffPassengerBlock, railDropoffPassengerBlock.getUnlocalizedName());
GameRegistry.registerBlock(rednetCableBlock, rednetCableBlock.getUnlocalizedName());
GameRegistry.registerBlock(milkLiquid, milkLiquid.getUnlocalizedName());
GameRegistry.registerBlock(sludgeLiquid, sludgeLiquid.getUnlocalizedName());
GameRegistry.registerBlock(sewageLiquid, sewageLiquid.getUnlocalizedName());
GameRegistry.registerBlock(essenceLiquid, essenceLiquid.getUnlocalizedName());
GameRegistry.registerBlock(biofuelLiquid, biofuelLiquid.getUnlocalizedName());
Block.setBurnProperties(rubberWoodBlock.blockID, 4, 20);
Block.setBurnProperties(rubberLeavesBlock.blockID, 30, 20);
MinecraftForge.setBlockHarvestLevel(MineFactoryReloadedCore.rednetCableBlock, 0, "pickaxe", 0);
if(vanillaOverrideGlassPane.getBoolean(true))
{
Block.blocksList[Block.thinGlass.blockID] = null;
Item.itemsList[Block.thinGlass.blockID] = null;
Block.thinGlass = new BlockVanillaGlassPane();
GameRegistry.registerBlock(Block.thinGlass, Block.thinGlass.getUnlocalizedName());
}
if(vanillaOverrideIce.getBoolean(true))
{
Block.blocksList[Block.ice.blockID] = null;
Item.itemsList[Block.ice.blockID] = null;
Block.ice = new BlockVanillaIce();
GameRegistry.registerBlock(Block.ice, ItemBlockVanillaIce.class, "blockVanillaIce");
}
if(vanillaOverrideMilkBucket.getBoolean(true))
{
- int milkBucketId = Item.bucketMilk.itemID;
+ int milkBucketId = Item.bucketMilk.itemID - 256;
Item.itemsList[milkBucketId] = null;
Item.bucketMilk = new ItemFactoryBucket(milkBucketId, milkLiquid.blockID).setUnlocalizedName("mfr.bucket.milk").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
}
GameRegistry.registerTileEntity(TileEntityConveyor.class, "factoryConveyor");
GameRegistry.registerTileEntity(TileRedstoneCable.class, "factoryRedstoneCable");
EntityRegistry.registerModEntity(EntitySafariNet.class, "entitySafariNet", 0, instance, 160, 5, true);
MinecraftForge.EVENT_BUS.register(instance);
MinecraftForge.EVENT_BUS.register(proxy);
Vanilla.registerRecipes();
OreDictionary.registerOre("itemRubber", MineFactoryReloadedCore.rubberBarItem);
OreDictionary.registerOre("woodRubber", MineFactoryReloadedCore.rubberWoodBlock);
GameRegistry.registerFuelHandler(new MineFactoryReloadedFuelHandler());
proxy.init();
NetworkRegistry.instance().registerGuiHandler(this, new MFRGUIHandler());
BlockDispenser.dispenseBehaviorRegistry.putObject(safariNetItem, new BehaviorDispenseSafariNet());
BlockDispenser.dispenseBehaviorRegistry.putObject(safariNetSingleItem, new BehaviorDispenseSafariNet());
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
VillagerRegistry.instance().registerVillageCreationHandler(new VillageCreationHandler());
VillagerRegistry.instance().registerVillagerType(zoolologistEntityId.getInt(), villagerFolder + "zoologist.png");
VillagerRegistry.instance().registerVillageTradeHandler(zoolologistEntityId.getInt(), new VillageTradeHandler());
GameRegistry.registerWorldGenerator(new MineFactoryReloadedWorldGen());
TickRegistry.registerScheduledTickHandler(new UpdateManager(this), Side.CLIENT);
}
@PostInit
public void postInit(FMLPostInitializationEvent evt)
{
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("milk", new LiquidStack(milkLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(Item.bucketMilk), new ItemStack(Item.bucketEmpty)));
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("sludge", new LiquidStack(sludgeLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(sludgeBucketItem), new ItemStack(Item.bucketEmpty)));
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("sewage", new LiquidStack(sewageLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(sewageBucketItem), new ItemStack(Item.bucketEmpty)));
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("mobEssence", new LiquidStack(essenceLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(mobEssenceBucketItem), new ItemStack(Item.bucketEmpty)));
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(LiquidDictionary.getOrCreateLiquid("biofuel", new LiquidStack(biofuelLiquid, LiquidContainerRegistry.BUCKET_VOLUME)), new ItemStack(bioFuelBucketItem), new ItemStack(Item.bucketEmpty)));
for(ItemStack s : OreDictionary.getOres("itemRubber"))
{
FurnaceRecipes.smelting().addSmelting(s.itemID, s.getItemDamage(), new ItemStack(rawPlasticItem), 0.3F);
}
FurnaceRecipes.smelting().addSmelting(Item.sugar.itemID, new ItemStack(sugarCharcoalItem), 0.1F);
String[] biomeWhitelist = rubberTreeBiomeWhitelist.getString().split(",");
for(String biome : biomeWhitelist)
{
MFRRegistry.registerRubberTreeBiome(biome);
}
String[] biomeBlacklist = rubberTreeBiomeBlacklist.getString().split(",");
for(String biome : biomeBlacklist)
{
MFRRegistry.getRubberTreeBiomes().remove(biome);
}
}
@ForgeSubscribe
public void onBonemeal(BonemealEvent e)
{
if(!e.world.isRemote && e.world.getBlockId(e.X, e.Y, e.Z) == MineFactoryReloadedCore.rubberSaplingBlock.blockID)
{
((BlockRubberSapling)MineFactoryReloadedCore.rubberSaplingBlock).growTree(e.world, e.X, e.Y, e.Z, e.world.rand);
e.setResult(Result.ALLOW);
}
}
@ForgeSubscribe
public void onBucketFill(FillBucketEvent e)
{
ItemStack filledBucket = fillBucket(e.world, e.target);
if(filledBucket != null)
{
e.world.setBlockToAir(e.target.blockX, e.target.blockY, e.target.blockZ);
e.result = filledBucket;
e.setResult(Result.ALLOW);
}
}
private ItemStack fillBucket(World world, MovingObjectPosition block)
{
int blockId = world.getBlockId(block.blockX, block.blockY, block.blockZ);
if(blockId == milkLiquid.blockID) return new ItemStack(Item.bucketMilk);
else if(blockId == sludgeLiquid.blockID) return new ItemStack(sludgeBucketItem);
else if(blockId == sewageLiquid.blockID) return new ItemStack(sewageBucketItem);
else if(blockId == essenceLiquid.blockID) return new ItemStack(mobEssenceBucketItem);
else if(blockId == biofuelLiquid.blockID) return new ItemStack(bioFuelBucketItem);
else return null;
}
private static void loadClientConfig(File configFile)
{
Configuration c = new Configuration(configFile);
spyglassRange = c.get(Configuration.CATEGORY_GENERAL, "SpyglassRange", 200);
spyglassRange.comment = "The maximum number of blocks the spyglass can look to find something. This calculation is performed only on the client side.";
c.save();
}
private static void loadCommonConfig(File configFile)
{
Configuration c = new Configuration(configFile);
c.load();
machineBlock0Id = c.getBlock("ID.MachineBlock", 3120);
conveyorBlockId = c.getBlock("ID.ConveyorBlock", 3121);
rubberWoodBlockId = c.getBlock("ID.RubberWood", 3122);
rubberLeavesBlockId = c.getBlock("ID.RubberLeaves", 3123);
rubberSaplingBlockId = c.getBlock("ID.RubberSapling", 3124);
railDropoffCargoBlockId = c.getBlock("ID.CargoRailDropoffBlock", 3125);
railPickupCargoBlockId = c.getBlock("ID.CargoRailPickupBlock", 3126);
railDropoffPassengerBlockId = c.getBlock("ID.PassengerRailDropoffBlock", 3127);
railPickupPassengerBlockId = c.getBlock("ID.PassengerRailPickupBlock", 3128);
factoryGlassBlockId = c.getBlock("ID.StainedGlass", 3129);
factoryGlassPaneBlockId = c.getBlock("ID.StainedGlassPane", 3130);
machineBlock1Id = c.getBlock("ID.MachineBlock1", 3131);
factoryRoadBlockId = c.getBlock("ID.Road", 3132);
factoryDecorativeBrickBlockId = c.getBlock("ID.Bricks", 3133);
milkStillBlockId = c.getBlock("ID.Milk.Still", 3135);
sludgeStillBlockId = c.getBlock("ID.Sludge.Still", 3137);
sewageStillBlockId = c.getBlock("ID.Sewage.Still", 3139);
essenceStillBlockId = c.getBlock("ID.MobEssence.Still", 3141);
biofuelStillBlockId = c.getBlock("ID.BioFuel.Still", 3143);
rednetCableBlockId = c.getBlock("ID.RedNet.Cable", 3144);
factoryDecorativeStoneBlockId = c.getBlock("ID.Stone", 3134);
hammerItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Hammer", 11987);
milkItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Milk", 11988);
sludgeItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Sludge", 11989);
sewageItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Sewage", 11990);
mobEssenceItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.MobEssence", 11991);
fertilizerItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.FertilizerItem", 11992);
plasticSheetItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.PlasticSheet", 11993);
rawPlasticItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.RawPlastic", 11994);
rubberBarItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.RubberBar", 11995);
sewageBucketItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SewageBucket", 11996);
sludgeBucketItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SludgeBucket", 11997);
mobEssenceBucketItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.MobEssenceBucket", 11998);
syringeEmptyItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SyringeEmpty", 11999);
syringeHealthItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SyringeHealth", 12000);
syringeGrowthItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SyringeGrowth", 12001);
rawRubberItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.RawRubber", 12002);
machineBaseItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.MachineBlock", 12003);
safariNetItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SafariNet", 12004);
ceramicDyeId = c.getItem(Configuration.CATEGORY_ITEM, "ID.CeramicDye", 12005);
blankRecordId = c.getItem(Configuration.CATEGORY_ITEM, "ID.BlankRecord", 12006);
syringeZombieId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SyringeZombie", 12007);
safariNetSingleItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SafariNetSingleUse", 12008);
bioFuelItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.BioFuel", 12009);
bioFuelBucketItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.BioFuelBucket", 12010);
upgradeItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Upgrade", 12011);
safariNetLauncherItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SafariNetLauncher", 12012);
sugarCharcoalItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SugarCharcoal", 12013);
milkBottleItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.MilkBottle", 12014);
spyglassItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Spyglass", 12015);
portaSpawnerItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.PortaSpawner", 12016);
strawItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.Straw", 12017);
xpExtractorItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.XPExtractor", 12018);
syringeSlimeItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SyringeSlime", 12019);
syringeCureItemId = c.getItem(Configuration.CATEGORY_ITEM, "ID.SyringeCure", 12020);
zoolologistEntityId = c.get("Entity", "ID.Zoologist", 330);
treeSearchMaxHorizontal = c.get(Configuration.CATEGORY_GENERAL, "SearchDistance.TreeMaxHoriztonal", 8);
treeSearchMaxHorizontal.comment = "When searching for parts of a tree, how far out to the sides (radius) to search";
treeSearchMaxVertical = c.get(Configuration.CATEGORY_GENERAL, "SearchDistance.TreeMaxVertical", 40);
treeSearchMaxVertical.comment = "When searching for parts of a tree, how far up to search";
verticalHarvestSearchMaxVertical = c.get(Configuration.CATEGORY_GENERAL, "SearchDistance.StackingBlockMaxVertical", 3);
verticalHarvestSearchMaxVertical.comment = "How far upward to search for members of \"stacking\" blocks, like cactus and sugarcane";
passengerRailSearchMaxVertical = c.get(Configuration.CATEGORY_GENERAL, "SearchDistance.PassengerRailMaxVertical", 2);
passengerRailSearchMaxVertical.comment = "When searching for players or dropoff locations, how far up to search";
passengerRailSearchMaxHorizontal = c.get(Configuration.CATEGORY_GENERAL, "SearchDistance.PassengerRailMaxHorizontal", 3);
passengerRailSearchMaxHorizontal.comment = "When searching for players or dropoff locations, how far out to the sides (radius) to search";
rubberTreeWorldGen = c.get(Configuration.CATEGORY_GENERAL, "WorldGen.RubberTree", true);
rubberTreeWorldGen.comment = "Whether or not to generate rubber trees during map generation";
mfrLakeWorldGen = c.get(Configuration.CATEGORY_GENERAL, "WorldGen.MFRLakes", true);
mfrLakeWorldGen.comment = "Whether or not to generate MFR lakes during map generation";
enableBonemealFertilizing = c.get(Configuration.CATEGORY_GENERAL, "Fertilizer.EnableBonemeal", false);
enableBonemealFertilizing.comment = "If true, the fertilizer will use bonemeal as well as MFR fertilizer. Provided for those who want a less work-intensive farm.";
enableCheapDSU = c.get(Configuration.CATEGORY_GENERAL, "DSU.EnableCheaperRecipe", false);
enableCheapDSU.comment = "If true, DSU can be built out of chests instead of ender pearls. Does nothing if the DSU recipe is disabled.";
enableMossyCobbleRecipe = c.get(Configuration.CATEGORY_GENERAL, "EnableMossyCobbleRecipe", true);
enableMossyCobbleRecipe.comment = "If true, mossy cobble can be crafted.";
conveyorCaptureNonItems = c.get(Configuration.CATEGORY_GENERAL, "Conveyor.CaptureNonItems", true);
conveyorCaptureNonItems.comment = "If false, conveyors will not grab non-item entities. Breaks conveyor mob grinders but makes them safe for golems, etc.";
playSounds = c.get(Configuration.CATEGORY_GENERAL, "PlaySounds", true);
playSounds.comment = "Set to false to disable the harvester's sound when a block is harvested.";
vanillaOverrideGlassPane = c.get(Configuration.CATEGORY_GENERAL, "VanillaOverride.GlassPanes", true);
vanillaOverrideGlassPane.comment = "If true, allows vanilla glass panes to connect to MFR stained glass panes.";
vanillaOverrideIce = c.get(Configuration.CATEGORY_GENERAL, "VanillaOverride.Ice", true);
vanillaOverrideIce.comment = "If true, enables MFR unmelting ice as well as vanilla ice.";
vanillaOverrideMilkBucket = c.get(Configuration.CATEGORY_GENERAL, "VanillaOverride.MilkBucket", true);
vanillaOverrideMilkBucket.comment = "If true, replaces the vanilla milk bucket so milk can be placed in the world.";
enableCompatibleAutoEnchanter = c.get(Configuration.CATEGORY_GENERAL, "AutoEnchanter.EnableSafeMode", false);
enableCompatibleAutoEnchanter.comment = "If true, the Auto Enchanter will accept entire stacks of books. This is provided to prevent a crash with BuildCraft. This will allow many books to be enchanted at once - only enable this if you know what you're doing.";
enableSlipperyRoads = c.get(Configuration.CATEGORY_GENERAL, "Road.Slippery", true);
enableSlipperyRoads.comment = "If true, roads will be slippery like ice.";
rubberTreeBiomeWhitelist = c.get(Configuration.CATEGORY_GENERAL, "WorldGen.RubberTreeBiomeWhitelist", "");
rubberTreeBiomeWhitelist.comment = "A comma-separated list of biomes to allow rubber trees to spawn in. Does nothing if rubber tree worldgen is disabled.";
rubberTreeBiomeBlacklist = c.get(Configuration.CATEGORY_GENERAL, "WorldGen.RubberTreeBiomeBlacklist", "");
rubberTreeBiomeBlacklist.comment = "A comma-separated list of biomes to disallow rubber trees to spawn in. Overrides any other biomes added.";
for(Machine machine : Machine.values())
{
machine.load(c);
}
c.save();
}
@Override
public String getModId()
{
return modId;
}
@Override
public String getModName()
{
return modName;
}
@Override
public String getModVersion()
{
return version;
}
}
| true | true | public void init(FMLInitializationEvent evt)
{
instance = this;
conveyorBlock = new BlockConveyor(conveyorBlockId.getInt());
machineBlocks.put(0, new BlockFactoryMachine(machineBlock0Id.getInt(), 0));
machineBlocks.put(1, new BlockFactoryMachine(machineBlock1Id.getInt(), 1));
factoryGlassBlock = new BlockFactoryGlass(factoryGlassBlockId.getInt());
factoryGlassPaneBlock = new BlockFactoryGlassPane(factoryGlassPaneBlockId.getInt());
factoryRoadBlock = new BlockFactoryRoad(factoryRoadBlockId.getInt());
factoryDecorativeBrickBlock = new BlockFactoryDecorativeBricks(factoryDecorativeBrickBlockId.getInt());
factoryDecorativeStoneBlock = new BlockDecorativeStone(factoryDecorativeStoneBlockId.getInt());
rubberWoodBlock = new BlockRubberWood(rubberWoodBlockId.getInt());
rubberLeavesBlock = new BlockRubberLeaves(rubberLeavesBlockId.getInt());
rubberSaplingBlock = new BlockRubberSapling(rubberSaplingBlockId.getInt());
railDropoffCargoBlock = new BlockRailCargoDropoff(railDropoffCargoBlockId.getInt());
railPickupCargoBlock = new BlockRailCargoPickup(railPickupCargoBlockId.getInt());
railDropoffPassengerBlock = new BlockRailPassengerDropoff(railDropoffPassengerBlockId.getInt());
railPickupPassengerBlock = new BlockRailPassengerPickup(railPickupPassengerBlockId.getInt());
rednetCableBlock = new BlockRedstoneCable(rednetCableBlockId.getInt());
milkLiquid = new BlockFluidFactory(milkStillBlockId.getInt(), "milk");
sludgeLiquid = new BlockFluidFactory(sludgeStillBlockId.getInt(), "sludge");
sewageLiquid = new BlockFluidFactory(sewageStillBlockId.getInt(), "sewage");
essenceLiquid = new BlockFluidFactory(essenceStillBlockId.getInt(), "essence");
biofuelLiquid = new BlockFluidFactory(biofuelStillBlockId.getInt(), "biofuel");
factoryHammerItem = (new ItemFactoryHammer(hammerItemId.getInt())).setUnlocalizedName("mfr.hammer").setMaxStackSize(1);
fertilizerItem = (new ItemFactory(fertilizerItemId.getInt())).setUnlocalizedName("mfr.fertilizer");
plasticSheetItem = (new ItemFactory(plasticSheetItemId.getInt())).setUnlocalizedName("mfr.plastic.sheet");
rawPlasticItem = (new ItemFactory(rawPlasticItemId.getInt())).setUnlocalizedName("mfr.plastic.raw");
rubberBarItem = (new ItemFactory(rubberBarItemId.getInt())).setUnlocalizedName("mfr.rubber.bar");
sewageBucketItem = (new ItemFactoryBucket(sewageBucketItemId.getInt(), sewageLiquid.blockID)).setUnlocalizedName("mfr.bucket.sewage").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
sludgeBucketItem = (new ItemFactoryBucket(sludgeBucketItemId.getInt(), sludgeLiquid.blockID)).setUnlocalizedName("mfr.bucket.sludge").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
mobEssenceBucketItem = (new ItemFactoryBucket(mobEssenceBucketItemId.getInt(), essenceLiquid.blockID)).setUnlocalizedName("mfr.bucket.essence").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
syringeEmptyItem = (new ItemFactory(syringeEmptyItemId.getInt())).setUnlocalizedName("mfr.syringe.empty");
syringeHealthItem = (new ItemSyringeHealth()).setUnlocalizedName("mfr.syringe.health").setContainerItem(syringeEmptyItem);
syringeGrowthItem = (new ItemSyringeGrowth()).setUnlocalizedName("mfr.syringe.growth").setContainerItem(syringeEmptyItem);
rawRubberItem = (new ItemFactory(rawRubberItemId.getInt())).setUnlocalizedName("mfr.rubber.raw");
machineBaseItem = (new ItemFactory(machineBaseItemId.getInt())).setUnlocalizedName("mfr.machineblock");
safariNetItem = (new ItemSafariNet(safariNetItemId.getInt())).setUnlocalizedName("mfr.safarinet.reusable");
ceramicDyeItem = (new ItemCeramicDye(ceramicDyeId.getInt())).setUnlocalizedName("mfr.ceramicdye");
blankRecordItem = (new ItemFactory(blankRecordId.getInt())).setUnlocalizedName("mfr.record.blank").setMaxStackSize(1);
syringeZombieItem = (new ItemSyringeZombie()).setUnlocalizedName("mfr.syringe.zombie").setContainerItem(syringeEmptyItem);
safariNetSingleItem = (new ItemSafariNet(safariNetSingleItemId.getInt())).setUnlocalizedName("mfr.safarinet.singleuse");
bioFuelBucketItem = (new ItemFactoryBucket(bioFuelBucketItemId.getInt(), biofuelLiquid.blockID)).setUnlocalizedName("mfr.bucket.biofuel").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
upgradeItem = (new ItemUpgrade(upgradeItemId.getInt())).setUnlocalizedName("mfr.upgrade.radius").setMaxStackSize(1);
safariNetLauncherItem = (new ItemSafariNetLauncher(safariNetLauncherItemId.getInt())).setUnlocalizedName("mfr.safarinet.launcher").setMaxStackSize(1);
sugarCharcoalItem = (new ItemFactory(sugarCharcoalItemId.getInt())).setUnlocalizedName("mfr.sugarcharcoal");
milkBottleItem = (new ItemMilkBottle(milkBottleItemId.getInt())).setUnlocalizedName("mfr.milkbottle").setMaxStackSize(1);
spyglassItem = (new ItemSpyglass(spyglassItemId.getInt())).setUnlocalizedName("mfr.spyglass").setMaxStackSize(1);
portaSpawnerItem = (new ItemPortaSpawner(portaSpawnerItemId.getInt())).setUnlocalizedName("mfr.portaspawner").setMaxStackSize(1);
strawItem = (new ItemStraw(strawItemId.getInt())).setUnlocalizedName("mfr.straw").setMaxStackSize(1);
xpExtractorItem = (new ItemXpExtractor(xpExtractorItemId.getInt())).setUnlocalizedName("mfr.xpextractor").setMaxStackSize(1);
syringeSlimeItem = (new ItemSyringeSlime(syringeSlimeItemId.getInt())).setUnlocalizedName("mfr.syringe.slime").setContainerItem(syringeEmptyItem);
syringeCureItem = (new ItemSyringeCure(syringeCureItemId.getInt())).setUnlocalizedName("mfr.syringe.cure").setContainerItem(syringeEmptyItem);
for(Entry<Integer, Block> machine : machineBlocks.entrySet())
{
GameRegistry.registerBlock(machine.getValue(), ItemBlockFactoryMachine.class, machine.getValue().getUnlocalizedName());
}
GameRegistry.registerBlock(conveyorBlock, ItemBlockConveyor.class, conveyorBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryGlassBlock, ItemBlockFactoryGlass.class, factoryGlassBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryGlassPaneBlock, ItemBlockFactoryGlassPane.class, factoryGlassPaneBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryRoadBlock, ItemBlockFactoryRoad.class, factoryRoadBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryDecorativeBrickBlock, ItemBlockFactoryDecorativeBrick.class, factoryDecorativeBrickBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryDecorativeStoneBlock, ItemBlockDecorativeStone.class, factoryDecorativeStoneBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberWoodBlock, rubberWoodBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberLeavesBlock, rubberLeavesBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberSaplingBlock, rubberSaplingBlock.getUnlocalizedName());
GameRegistry.registerBlock(railPickupCargoBlock, railPickupCargoBlock.getUnlocalizedName());
GameRegistry.registerBlock(railDropoffCargoBlock, railDropoffCargoBlock.getUnlocalizedName());
GameRegistry.registerBlock(railPickupPassengerBlock, railPickupPassengerBlock.getUnlocalizedName());
GameRegistry.registerBlock(railDropoffPassengerBlock, railDropoffPassengerBlock.getUnlocalizedName());
GameRegistry.registerBlock(rednetCableBlock, rednetCableBlock.getUnlocalizedName());
GameRegistry.registerBlock(milkLiquid, milkLiquid.getUnlocalizedName());
GameRegistry.registerBlock(sludgeLiquid, sludgeLiquid.getUnlocalizedName());
GameRegistry.registerBlock(sewageLiquid, sewageLiquid.getUnlocalizedName());
GameRegistry.registerBlock(essenceLiquid, essenceLiquid.getUnlocalizedName());
GameRegistry.registerBlock(biofuelLiquid, biofuelLiquid.getUnlocalizedName());
Block.setBurnProperties(rubberWoodBlock.blockID, 4, 20);
Block.setBurnProperties(rubberLeavesBlock.blockID, 30, 20);
MinecraftForge.setBlockHarvestLevel(MineFactoryReloadedCore.rednetCableBlock, 0, "pickaxe", 0);
if(vanillaOverrideGlassPane.getBoolean(true))
{
Block.blocksList[Block.thinGlass.blockID] = null;
Item.itemsList[Block.thinGlass.blockID] = null;
Block.thinGlass = new BlockVanillaGlassPane();
GameRegistry.registerBlock(Block.thinGlass, Block.thinGlass.getUnlocalizedName());
}
if(vanillaOverrideIce.getBoolean(true))
{
Block.blocksList[Block.ice.blockID] = null;
Item.itemsList[Block.ice.blockID] = null;
Block.ice = new BlockVanillaIce();
GameRegistry.registerBlock(Block.ice, ItemBlockVanillaIce.class, "blockVanillaIce");
}
if(vanillaOverrideMilkBucket.getBoolean(true))
{
int milkBucketId = Item.bucketMilk.itemID;
Item.itemsList[milkBucketId] = null;
Item.bucketMilk = new ItemFactoryBucket(milkBucketId, milkLiquid.blockID).setUnlocalizedName("mfr.bucket.milk").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
}
GameRegistry.registerTileEntity(TileEntityConveyor.class, "factoryConveyor");
GameRegistry.registerTileEntity(TileRedstoneCable.class, "factoryRedstoneCable");
EntityRegistry.registerModEntity(EntitySafariNet.class, "entitySafariNet", 0, instance, 160, 5, true);
MinecraftForge.EVENT_BUS.register(instance);
MinecraftForge.EVENT_BUS.register(proxy);
Vanilla.registerRecipes();
OreDictionary.registerOre("itemRubber", MineFactoryReloadedCore.rubberBarItem);
OreDictionary.registerOre("woodRubber", MineFactoryReloadedCore.rubberWoodBlock);
GameRegistry.registerFuelHandler(new MineFactoryReloadedFuelHandler());
proxy.init();
NetworkRegistry.instance().registerGuiHandler(this, new MFRGUIHandler());
BlockDispenser.dispenseBehaviorRegistry.putObject(safariNetItem, new BehaviorDispenseSafariNet());
BlockDispenser.dispenseBehaviorRegistry.putObject(safariNetSingleItem, new BehaviorDispenseSafariNet());
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
VillagerRegistry.instance().registerVillageCreationHandler(new VillageCreationHandler());
VillagerRegistry.instance().registerVillagerType(zoolologistEntityId.getInt(), villagerFolder + "zoologist.png");
VillagerRegistry.instance().registerVillageTradeHandler(zoolologistEntityId.getInt(), new VillageTradeHandler());
GameRegistry.registerWorldGenerator(new MineFactoryReloadedWorldGen());
TickRegistry.registerScheduledTickHandler(new UpdateManager(this), Side.CLIENT);
}
| public void init(FMLInitializationEvent evt)
{
instance = this;
conveyorBlock = new BlockConveyor(conveyorBlockId.getInt());
machineBlocks.put(0, new BlockFactoryMachine(machineBlock0Id.getInt(), 0));
machineBlocks.put(1, new BlockFactoryMachine(machineBlock1Id.getInt(), 1));
factoryGlassBlock = new BlockFactoryGlass(factoryGlassBlockId.getInt());
factoryGlassPaneBlock = new BlockFactoryGlassPane(factoryGlassPaneBlockId.getInt());
factoryRoadBlock = new BlockFactoryRoad(factoryRoadBlockId.getInt());
factoryDecorativeBrickBlock = new BlockFactoryDecorativeBricks(factoryDecorativeBrickBlockId.getInt());
factoryDecorativeStoneBlock = new BlockDecorativeStone(factoryDecorativeStoneBlockId.getInt());
rubberWoodBlock = new BlockRubberWood(rubberWoodBlockId.getInt());
rubberLeavesBlock = new BlockRubberLeaves(rubberLeavesBlockId.getInt());
rubberSaplingBlock = new BlockRubberSapling(rubberSaplingBlockId.getInt());
railDropoffCargoBlock = new BlockRailCargoDropoff(railDropoffCargoBlockId.getInt());
railPickupCargoBlock = new BlockRailCargoPickup(railPickupCargoBlockId.getInt());
railDropoffPassengerBlock = new BlockRailPassengerDropoff(railDropoffPassengerBlockId.getInt());
railPickupPassengerBlock = new BlockRailPassengerPickup(railPickupPassengerBlockId.getInt());
rednetCableBlock = new BlockRedstoneCable(rednetCableBlockId.getInt());
milkLiquid = new BlockFluidFactory(milkStillBlockId.getInt(), "milk");
sludgeLiquid = new BlockFluidFactory(sludgeStillBlockId.getInt(), "sludge");
sewageLiquid = new BlockFluidFactory(sewageStillBlockId.getInt(), "sewage");
essenceLiquid = new BlockFluidFactory(essenceStillBlockId.getInt(), "essence");
biofuelLiquid = new BlockFluidFactory(biofuelStillBlockId.getInt(), "biofuel");
factoryHammerItem = (new ItemFactoryHammer(hammerItemId.getInt())).setUnlocalizedName("mfr.hammer").setMaxStackSize(1);
fertilizerItem = (new ItemFactory(fertilizerItemId.getInt())).setUnlocalizedName("mfr.fertilizer");
plasticSheetItem = (new ItemFactory(plasticSheetItemId.getInt())).setUnlocalizedName("mfr.plastic.sheet");
rawPlasticItem = (new ItemFactory(rawPlasticItemId.getInt())).setUnlocalizedName("mfr.plastic.raw");
rubberBarItem = (new ItemFactory(rubberBarItemId.getInt())).setUnlocalizedName("mfr.rubber.bar");
sewageBucketItem = (new ItemFactoryBucket(sewageBucketItemId.getInt(), sewageLiquid.blockID)).setUnlocalizedName("mfr.bucket.sewage").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
sludgeBucketItem = (new ItemFactoryBucket(sludgeBucketItemId.getInt(), sludgeLiquid.blockID)).setUnlocalizedName("mfr.bucket.sludge").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
mobEssenceBucketItem = (new ItemFactoryBucket(mobEssenceBucketItemId.getInt(), essenceLiquid.blockID)).setUnlocalizedName("mfr.bucket.essence").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
syringeEmptyItem = (new ItemFactory(syringeEmptyItemId.getInt())).setUnlocalizedName("mfr.syringe.empty");
syringeHealthItem = (new ItemSyringeHealth()).setUnlocalizedName("mfr.syringe.health").setContainerItem(syringeEmptyItem);
syringeGrowthItem = (new ItemSyringeGrowth()).setUnlocalizedName("mfr.syringe.growth").setContainerItem(syringeEmptyItem);
rawRubberItem = (new ItemFactory(rawRubberItemId.getInt())).setUnlocalizedName("mfr.rubber.raw");
machineBaseItem = (new ItemFactory(machineBaseItemId.getInt())).setUnlocalizedName("mfr.machineblock");
safariNetItem = (new ItemSafariNet(safariNetItemId.getInt())).setUnlocalizedName("mfr.safarinet.reusable");
ceramicDyeItem = (new ItemCeramicDye(ceramicDyeId.getInt())).setUnlocalizedName("mfr.ceramicdye");
blankRecordItem = (new ItemFactory(blankRecordId.getInt())).setUnlocalizedName("mfr.record.blank").setMaxStackSize(1);
syringeZombieItem = (new ItemSyringeZombie()).setUnlocalizedName("mfr.syringe.zombie").setContainerItem(syringeEmptyItem);
safariNetSingleItem = (new ItemSafariNet(safariNetSingleItemId.getInt())).setUnlocalizedName("mfr.safarinet.singleuse");
bioFuelBucketItem = (new ItemFactoryBucket(bioFuelBucketItemId.getInt(), biofuelLiquid.blockID)).setUnlocalizedName("mfr.bucket.biofuel").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
upgradeItem = (new ItemUpgrade(upgradeItemId.getInt())).setUnlocalizedName("mfr.upgrade.radius").setMaxStackSize(1);
safariNetLauncherItem = (new ItemSafariNetLauncher(safariNetLauncherItemId.getInt())).setUnlocalizedName("mfr.safarinet.launcher").setMaxStackSize(1);
sugarCharcoalItem = (new ItemFactory(sugarCharcoalItemId.getInt())).setUnlocalizedName("mfr.sugarcharcoal");
milkBottleItem = (new ItemMilkBottle(milkBottleItemId.getInt())).setUnlocalizedName("mfr.milkbottle").setMaxStackSize(1);
spyglassItem = (new ItemSpyglass(spyglassItemId.getInt())).setUnlocalizedName("mfr.spyglass").setMaxStackSize(1);
portaSpawnerItem = (new ItemPortaSpawner(portaSpawnerItemId.getInt())).setUnlocalizedName("mfr.portaspawner").setMaxStackSize(1);
strawItem = (new ItemStraw(strawItemId.getInt())).setUnlocalizedName("mfr.straw").setMaxStackSize(1);
xpExtractorItem = (new ItemXpExtractor(xpExtractorItemId.getInt())).setUnlocalizedName("mfr.xpextractor").setMaxStackSize(1);
syringeSlimeItem = (new ItemSyringeSlime(syringeSlimeItemId.getInt())).setUnlocalizedName("mfr.syringe.slime").setContainerItem(syringeEmptyItem);
syringeCureItem = (new ItemSyringeCure(syringeCureItemId.getInt())).setUnlocalizedName("mfr.syringe.cure").setContainerItem(syringeEmptyItem);
for(Entry<Integer, Block> machine : machineBlocks.entrySet())
{
GameRegistry.registerBlock(machine.getValue(), ItemBlockFactoryMachine.class, machine.getValue().getUnlocalizedName());
}
GameRegistry.registerBlock(conveyorBlock, ItemBlockConveyor.class, conveyorBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryGlassBlock, ItemBlockFactoryGlass.class, factoryGlassBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryGlassPaneBlock, ItemBlockFactoryGlassPane.class, factoryGlassPaneBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryRoadBlock, ItemBlockFactoryRoad.class, factoryRoadBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryDecorativeBrickBlock, ItemBlockFactoryDecorativeBrick.class, factoryDecorativeBrickBlock.getUnlocalizedName());
GameRegistry.registerBlock(factoryDecorativeStoneBlock, ItemBlockDecorativeStone.class, factoryDecorativeStoneBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberWoodBlock, rubberWoodBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberLeavesBlock, rubberLeavesBlock.getUnlocalizedName());
GameRegistry.registerBlock(rubberSaplingBlock, rubberSaplingBlock.getUnlocalizedName());
GameRegistry.registerBlock(railPickupCargoBlock, railPickupCargoBlock.getUnlocalizedName());
GameRegistry.registerBlock(railDropoffCargoBlock, railDropoffCargoBlock.getUnlocalizedName());
GameRegistry.registerBlock(railPickupPassengerBlock, railPickupPassengerBlock.getUnlocalizedName());
GameRegistry.registerBlock(railDropoffPassengerBlock, railDropoffPassengerBlock.getUnlocalizedName());
GameRegistry.registerBlock(rednetCableBlock, rednetCableBlock.getUnlocalizedName());
GameRegistry.registerBlock(milkLiquid, milkLiquid.getUnlocalizedName());
GameRegistry.registerBlock(sludgeLiquid, sludgeLiquid.getUnlocalizedName());
GameRegistry.registerBlock(sewageLiquid, sewageLiquid.getUnlocalizedName());
GameRegistry.registerBlock(essenceLiquid, essenceLiquid.getUnlocalizedName());
GameRegistry.registerBlock(biofuelLiquid, biofuelLiquid.getUnlocalizedName());
Block.setBurnProperties(rubberWoodBlock.blockID, 4, 20);
Block.setBurnProperties(rubberLeavesBlock.blockID, 30, 20);
MinecraftForge.setBlockHarvestLevel(MineFactoryReloadedCore.rednetCableBlock, 0, "pickaxe", 0);
if(vanillaOverrideGlassPane.getBoolean(true))
{
Block.blocksList[Block.thinGlass.blockID] = null;
Item.itemsList[Block.thinGlass.blockID] = null;
Block.thinGlass = new BlockVanillaGlassPane();
GameRegistry.registerBlock(Block.thinGlass, Block.thinGlass.getUnlocalizedName());
}
if(vanillaOverrideIce.getBoolean(true))
{
Block.blocksList[Block.ice.blockID] = null;
Item.itemsList[Block.ice.blockID] = null;
Block.ice = new BlockVanillaIce();
GameRegistry.registerBlock(Block.ice, ItemBlockVanillaIce.class, "blockVanillaIce");
}
if(vanillaOverrideMilkBucket.getBoolean(true))
{
int milkBucketId = Item.bucketMilk.itemID - 256;
Item.itemsList[milkBucketId] = null;
Item.bucketMilk = new ItemFactoryBucket(milkBucketId, milkLiquid.blockID).setUnlocalizedName("mfr.bucket.milk").setMaxStackSize(1).setContainerItem(Item.bucketEmpty);
}
GameRegistry.registerTileEntity(TileEntityConveyor.class, "factoryConveyor");
GameRegistry.registerTileEntity(TileRedstoneCable.class, "factoryRedstoneCable");
EntityRegistry.registerModEntity(EntitySafariNet.class, "entitySafariNet", 0, instance, 160, 5, true);
MinecraftForge.EVENT_BUS.register(instance);
MinecraftForge.EVENT_BUS.register(proxy);
Vanilla.registerRecipes();
OreDictionary.registerOre("itemRubber", MineFactoryReloadedCore.rubberBarItem);
OreDictionary.registerOre("woodRubber", MineFactoryReloadedCore.rubberWoodBlock);
GameRegistry.registerFuelHandler(new MineFactoryReloadedFuelHandler());
proxy.init();
NetworkRegistry.instance().registerGuiHandler(this, new MFRGUIHandler());
BlockDispenser.dispenseBehaviorRegistry.putObject(safariNetItem, new BehaviorDispenseSafariNet());
BlockDispenser.dispenseBehaviorRegistry.putObject(safariNetSingleItem, new BehaviorDispenseSafariNet());
ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(safariNetSingleItem), 1, 1, 25));
VillagerRegistry.instance().registerVillageCreationHandler(new VillageCreationHandler());
VillagerRegistry.instance().registerVillagerType(zoolologistEntityId.getInt(), villagerFolder + "zoologist.png");
VillagerRegistry.instance().registerVillageTradeHandler(zoolologistEntityId.getInt(), new VillageTradeHandler());
GameRegistry.registerWorldGenerator(new MineFactoryReloadedWorldGen());
TickRegistry.registerScheduledTickHandler(new UpdateManager(this), Side.CLIENT);
}
|
diff --git a/src/main/java/archimulator/model/experiment/CheckpointedExperiment.java b/src/main/java/archimulator/model/experiment/CheckpointedExperiment.java
index 950eb1cf..bf192ef5 100644
--- a/src/main/java/archimulator/model/experiment/CheckpointedExperiment.java
+++ b/src/main/java/archimulator/model/experiment/CheckpointedExperiment.java
@@ -1,52 +1,52 @@
/*******************************************************************************
* Copyright (c) 2010-2012 by Min Cai ([email protected]).
*
* This file is part of the Archimulator multicore architectural simulator.
*
* Archimulator 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.
*
* Archimulator 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 Archimulator. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package archimulator.model.experiment;
import archimulator.model.capability.*;
import archimulator.model.simulation.ContextConfig;
import archimulator.model.simulation.SimulationStartingImage;
import archimulator.model.strategy.checkpoint.CheckpointToInstructionCountBasedDetailedSimulationStrategy;
import archimulator.model.strategy.checkpoint.RoiBasedRunToCheckpointFunctionalSimulationStrategy;
import archimulator.model.capability.KernelCapability;
import archimulator.sim.uncore.cache.eviction.EvictionPolicyFactory;
import java.util.List;
public class CheckpointedExperiment extends Experiment {
private int maxInsts;
private int pthreadSpawnedIndex;
public CheckpointedExperiment(String title, int numCores, int numThreadsPerCore, List<ContextConfig> contextConfigs, int maxInsts, int l2Size, int l2Associativity, EvictionPolicyFactory l2EvictionPolicyFactory, int pthreadSpawnedIndex, List<Class<? extends SimulationCapability>> simulationCapabilityClasses, List<Class<? extends ProcessorCapability>> processorCapabilityClasses, List<Class<? extends KernelCapability>> kernelCapabilityClasses) {
super(title, numCores, numThreadsPerCore, contextConfigs, l2Size, l2Associativity, l2EvictionPolicyFactory, simulationCapabilityClasses, processorCapabilityClasses, kernelCapabilityClasses);
this.maxInsts = maxInsts;
this.pthreadSpawnedIndex = pthreadSpawnedIndex;
}
@Override
protected void doStart() {
SimulationStartingImage simulationStartingImage = new SimulationStartingImage();
this.doSimulation(this.getTitle() + "/checkpointedSimulation/phase0", new RoiBasedRunToCheckpointFunctionalSimulationStrategy(this.getPhaser(), this.pthreadSpawnedIndex, simulationStartingImage), getBlockingEventDispatcher(), getCycleAccurateEventQueue());
- getBlockingEventDispatcher().clearListeners();
+// getBlockingEventDispatcher().clearListeners(); //TODO: error here!!!
getCycleAccurateEventQueue().resetCurrentCycle();
this.doSimulation(this.getTitle() + "/checkpointedSimulation/phase1", new CheckpointToInstructionCountBasedDetailedSimulationStrategy(this.getPhaser(), this.maxInsts, simulationStartingImage), getBlockingEventDispatcher(), getCycleAccurateEventQueue());
}
}
| true | true | protected void doStart() {
SimulationStartingImage simulationStartingImage = new SimulationStartingImage();
this.doSimulation(this.getTitle() + "/checkpointedSimulation/phase0", new RoiBasedRunToCheckpointFunctionalSimulationStrategy(this.getPhaser(), this.pthreadSpawnedIndex, simulationStartingImage), getBlockingEventDispatcher(), getCycleAccurateEventQueue());
getBlockingEventDispatcher().clearListeners();
getCycleAccurateEventQueue().resetCurrentCycle();
this.doSimulation(this.getTitle() + "/checkpointedSimulation/phase1", new CheckpointToInstructionCountBasedDetailedSimulationStrategy(this.getPhaser(), this.maxInsts, simulationStartingImage), getBlockingEventDispatcher(), getCycleAccurateEventQueue());
}
| protected void doStart() {
SimulationStartingImage simulationStartingImage = new SimulationStartingImage();
this.doSimulation(this.getTitle() + "/checkpointedSimulation/phase0", new RoiBasedRunToCheckpointFunctionalSimulationStrategy(this.getPhaser(), this.pthreadSpawnedIndex, simulationStartingImage), getBlockingEventDispatcher(), getCycleAccurateEventQueue());
// getBlockingEventDispatcher().clearListeners(); //TODO: error here!!!
getCycleAccurateEventQueue().resetCurrentCycle();
this.doSimulation(this.getTitle() + "/checkpointedSimulation/phase1", new CheckpointToInstructionCountBasedDetailedSimulationStrategy(this.getPhaser(), this.maxInsts, simulationStartingImage), getBlockingEventDispatcher(), getCycleAccurateEventQueue());
}
|
diff --git a/src/Model/Skills/Warrior/SkillGrapplingHook.java b/src/Model/Skills/Warrior/SkillGrapplingHook.java
index a8c407a..0a967a8 100644
--- a/src/Model/Skills/Warrior/SkillGrapplingHook.java
+++ b/src/Model/Skills/Warrior/SkillGrapplingHook.java
@@ -1,43 +1,43 @@
package Model.Skills.Warrior;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import Model.Skills.Skill;
public class SkillGrapplingHook extends Skill {
public SkillGrapplingHook(){
//String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE
super("Grappling hook", 11000, 400, 0.4, 3, 0, 150,"The wizard \n" +
"Level 1: 15 damage\n" +
"Level 2: 25 damage\n" +
"Level 3: 35 damage\n" +
"Level 4: 45 damage", false);
Image attackImage = null;
Image[] animation = new Image[7];
Image[] skillBar = new Image[3];
try {
attackImage = new Image("res/animations/explode1.png");
animation[0] = new Image("res/animations/explode1.png");
animation[1] = new Image("res/animations/explode2.png");
animation[2] = new Image("res/animations/explode3.png");
animation[3] = new Image("res/animations/explode4.png");
animation[4] = new Image("res/animations/explode5.png");
animation[5] = new Image("res/animations/explode6.png");
animation[6] = new Image("res/animations/explode7.png");
- skillBar[0] = new Image("res/skillIcons/fireball.png");
+ skillBar[0] = new Image("res/skillIcons/fireball_active.png");
skillBar[1] = new Image("res/skillIcons/fireball_active.png");
skillBar[2] = new Image("res/skillIcons/fireball_disabled.png");
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.setImage(attackImage, attackImage.getHeight(), attackImage.getWidth());
super.setEndState(animation, 200, 400);
super.setSkillBarImages(skillBar);
}
}
| true | true | public SkillGrapplingHook(){
//String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE
super("Grappling hook", 11000, 400, 0.4, 3, 0, 150,"The wizard \n" +
"Level 1: 15 damage\n" +
"Level 2: 25 damage\n" +
"Level 3: 35 damage\n" +
"Level 4: 45 damage", false);
Image attackImage = null;
Image[] animation = new Image[7];
Image[] skillBar = new Image[3];
try {
attackImage = new Image("res/animations/explode1.png");
animation[0] = new Image("res/animations/explode1.png");
animation[1] = new Image("res/animations/explode2.png");
animation[2] = new Image("res/animations/explode3.png");
animation[3] = new Image("res/animations/explode4.png");
animation[4] = new Image("res/animations/explode5.png");
animation[5] = new Image("res/animations/explode6.png");
animation[6] = new Image("res/animations/explode7.png");
skillBar[0] = new Image("res/skillIcons/fireball.png");
skillBar[1] = new Image("res/skillIcons/fireball_active.png");
skillBar[2] = new Image("res/skillIcons/fireball_disabled.png");
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.setImage(attackImage, attackImage.getHeight(), attackImage.getWidth());
super.setEndState(animation, 200, 400);
super.setSkillBarImages(skillBar);
}
| public SkillGrapplingHook(){
//String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE
super("Grappling hook", 11000, 400, 0.4, 3, 0, 150,"The wizard \n" +
"Level 1: 15 damage\n" +
"Level 2: 25 damage\n" +
"Level 3: 35 damage\n" +
"Level 4: 45 damage", false);
Image attackImage = null;
Image[] animation = new Image[7];
Image[] skillBar = new Image[3];
try {
attackImage = new Image("res/animations/explode1.png");
animation[0] = new Image("res/animations/explode1.png");
animation[1] = new Image("res/animations/explode2.png");
animation[2] = new Image("res/animations/explode3.png");
animation[3] = new Image("res/animations/explode4.png");
animation[4] = new Image("res/animations/explode5.png");
animation[5] = new Image("res/animations/explode6.png");
animation[6] = new Image("res/animations/explode7.png");
skillBar[0] = new Image("res/skillIcons/fireball_active.png");
skillBar[1] = new Image("res/skillIcons/fireball_active.png");
skillBar[2] = new Image("res/skillIcons/fireball_disabled.png");
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.setImage(attackImage, attackImage.getHeight(), attackImage.getWidth());
super.setEndState(animation, 200, 400);
super.setSkillBarImages(skillBar);
}
|
diff --git a/src/org/openstreetmap/josm/plugins/notes/gui/NotesDialog.java b/src/org/openstreetmap/josm/plugins/notes/gui/NotesDialog.java
index 5f4c08d..0b2fc9f 100644
--- a/src/org/openstreetmap/josm/plugins/notes/gui/NotesDialog.java
+++ b/src/org/openstreetmap/josm/plugins/notes/gui/NotesDialog.java
@@ -1,440 +1,441 @@
/* Copyright (c) 2013, Ian Dees
* 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 project 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.openstreetmap.josm.plugins.notes.gui;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JToggleButton;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.gui.MapView;
import org.openstreetmap.josm.gui.MapView.LayerChangeListener;
import org.openstreetmap.josm.gui.dialogs.ToggleDialog;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.plugins.notes.ConfigKeys;
import org.openstreetmap.josm.plugins.notes.Note;
import org.openstreetmap.josm.plugins.notes.NotesObserver;
import org.openstreetmap.josm.plugins.notes.NotesPlugin;
import org.openstreetmap.josm.plugins.notes.gui.action.ActionQueue;
import org.openstreetmap.josm.plugins.notes.gui.action.AddCommentAction;
import org.openstreetmap.josm.plugins.notes.gui.action.CloseNoteAction;
import org.openstreetmap.josm.plugins.notes.gui.action.NotesAction;
import org.openstreetmap.josm.plugins.notes.gui.action.NotesActionObserver;
import org.openstreetmap.josm.plugins.notes.gui.action.PointToNewNoteAction;
import org.openstreetmap.josm.plugins.notes.gui.action.PopupFactory;
import org.openstreetmap.josm.plugins.notes.gui.action.ReopenAction;
import org.openstreetmap.josm.plugins.notes.gui.action.ToggleConnectionModeAction;
import org.openstreetmap.josm.tools.OsmUrlToBounds;
import org.openstreetmap.josm.tools.Shortcut;
public class NotesDialog extends ToggleDialog implements NotesObserver, ListSelectionListener, LayerChangeListener, MouseListener, NotesActionObserver {
private static final long serialVersionUID = 1L;
private JPanel bugListPanel, queuePanel;
private DefaultListModel bugListModel;
private JList bugList;
private JList queueList;
private NotesPlugin notesPlugin;
private boolean fireSelectionChanged = true;
private JButton refresh;
private JButton addComment;
private JButton closeIssue;
private JButton reopenNote;
private JButton processQueue = new JButton(tr("Process queue"));
private JToggleButton newIssue = new JToggleButton();
private JToggleButton toggleConnectionMode;
private JTabbedPane tabbedPane = new JTabbedPane();
private boolean queuePanelVisible = false;
private final ActionQueue actionQueue = new ActionQueue();
private boolean buttonLabels = Main.pref.getBoolean(ConfigKeys.NOTES_BUTTON_LABELS);
public NotesDialog(final NotesPlugin plugin) {
super(tr("OpenStreetMap Notes"), "note_icon24.png",
tr("Opens the OpenStreetMap Notes window and activates the automatic download"), Shortcut.registerShortcut(
"view:osmnotes", tr("Toggle: {0}", tr("Open OpenStreetMap Notes")), KeyEvent.VK_B,
Shortcut.ALT_SHIFT), 150);
notesPlugin = plugin;
bugListPanel = new JPanel(new BorderLayout());
bugListPanel.setName(tr("Bug list"));
add(bugListPanel, BorderLayout.CENTER);
bugListModel = new DefaultListModel();
bugList = new JList(bugListModel);
bugList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
bugList.addListSelectionListener(this);
bugList.addMouseListener(this);
bugList.setCellRenderer(new NotesBugListCellRenderer());
bugListPanel.add(new JScrollPane(bugList), BorderLayout.CENTER);
// create dialog buttons
GridLayout layout = buttonLabels ? new GridLayout(3, 2) : new GridLayout(1, 6);
JPanel buttonPanel = new JPanel(layout);
refresh = new JButton(tr("Refresh"));
refresh.setToolTipText(tr("Refresh"));
refresh.setIcon(NotesPlugin.loadIcon("view-refresh22.png"));
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int zoom = OsmUrlToBounds.getZoom(Main.map.mapView.getRealBounds());
// check zoom level
if (zoom > 15 || zoom < 9) {
JOptionPane.showMessageDialog(Main.parent,
tr("The visible area is either too small or too big to download data from OpenStreetMap Notes"),
tr("Warning"), JOptionPane.INFORMATION_MESSAGE);
return;
}
plugin.updateData();
}
});
bugListPanel.add(buttonPanel, BorderLayout.SOUTH);
Action toggleConnectionModeAction = new ToggleConnectionModeAction(this, notesPlugin);
toggleConnectionMode = new JToggleButton(toggleConnectionModeAction);
toggleConnectionMode.setToolTipText(ToggleConnectionModeAction.MSG_OFFLINE);
boolean offline = Main.pref.getBoolean(ConfigKeys.NOTES_API_OFFLINE);
toggleConnectionMode.setIcon(NotesPlugin.loadIcon("online22.png"));
toggleConnectionMode.setSelectedIcon(NotesPlugin.loadIcon("offline22.png"));
if(offline) {
// inverse the current value and then do a click, so that
// we are offline and the gui represents the offline state, too
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, false);
toggleConnectionMode.doClick();
}
AddCommentAction addCommentAction = new AddCommentAction(this);
addComment = new JButton(addCommentAction);
addComment.setEnabled(false);
addComment.setToolTipText((String) addComment.getAction().getValue(Action.NAME));
addComment.setIcon(NotesPlugin.loadIcon("add_comment22.png"));
CloseNoteAction closeIssueAction = new CloseNoteAction(this);
closeIssue = new JButton(closeIssueAction);
closeIssue.setEnabled(false);
closeIssue.setToolTipText((String) closeIssue.getAction().getValue(Action.NAME));
closeIssue.setIcon(NotesPlugin.loadIcon("closed_note22.png"));
PointToNewNoteAction nia = new PointToNewNoteAction(newIssue, notesPlugin);
newIssue.setAction(nia);
newIssue.setToolTipText((String) newIssue.getAction().getValue(Action.NAME));
newIssue.setIcon(NotesPlugin.loadIcon("new_note22.png"));
ReopenAction reopenAction = new ReopenAction(this);
reopenNote = new JButton(reopenAction);
reopenNote.setIcon(NotesPlugin.loadIcon("reopen_note22.png"));
reopenNote.setToolTipText(reopenNote.getAction().getValue(Action.NAME).toString());
buttonPanel.add(toggleConnectionMode);
buttonPanel.add(refresh);
buttonPanel.add(newIssue);
buttonPanel.add(addComment);
buttonPanel.add(closeIssue);
buttonPanel.add(reopenNote);
queuePanel = new JPanel(new BorderLayout());
queuePanel.setName(tr("Queue"));
queueList = new JList(getActionQueue());
queueList.setCellRenderer(new NotesQueueListCellRenderer());
queuePanel.add(new JScrollPane(queueList), BorderLayout.CENTER);
queuePanel.add(processQueue, BorderLayout.SOUTH);
processQueue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, "false");
setConnectionMode(false);
try {
getActionQueue().processQueue();
// refresh, if the api is enabled
if(!Main.pref.getBoolean(ConfigKeys.NOTES_API_DISABLED)) {
plugin.updateData();
}
} catch (Exception e1) {
System.err.println("Couldn't process action queue");
e1.printStackTrace();
}
}
});
tabbedPane.add(queuePanel);
if (buttonLabels) {
toggleConnectionMode.setHorizontalAlignment(SwingConstants.LEFT);
refresh.setHorizontalAlignment(SwingConstants.LEFT);
addComment.setHorizontalAlignment(SwingConstants.LEFT);
closeIssue.setHorizontalAlignment(SwingConstants.LEFT);
newIssue.setHorizontalAlignment(SwingConstants.LEFT);
+ reopenNote.setHorizontalAlignment(SwingConstants.LEFT);
} else {
toggleConnectionMode.setText(null);
refresh.setText(null);
addComment.setText(null);
closeIssue.setText(null);
newIssue.setText(null);
}
addCommentAction.addActionObserver(this);
closeIssueAction.addActionObserver(this);
setConnectionMode(offline);
MapView.addLayerChangeListener(this);
}
@Override
public void destroy() {
super.destroy();
MapView.removeLayerChangeListener(this);
}
public synchronized void update(final Collection<Note> dataset) {
// create a new list model
bugListModel = new DefaultListModel();
List<Note> sortedList = new ArrayList<Note>(dataset);
Collections.sort(sortedList, new BugComparator());
for (Note note : sortedList) {
bugListModel.addElement(note);
}
bugList.setModel(bugListModel);
}
public void valueChanged(ListSelectionEvent e) {
if (bugList.getSelectedValues().length == 0) {
addComment.setEnabled(false);
closeIssue.setEnabled(false);
return;
}
List<Note> selected = new ArrayList<Note>();
for (Object n : bugList.getSelectedValues()) {
Note note = (Note)n;
selected.add(note);
switch(note.getState()) {
case closed:
addComment.setEnabled(false);
closeIssue.setEnabled(false);
case open:
addComment.setEnabled(true);
closeIssue.setEnabled(true);
}
scrollToSelected(note);
}
// CurrentDataSet may be null if there is no normal, edible map
// If so, a temporary DataSet is created because it's the simplest way
// to fire all necessary events so OSB updates its popups.
List<Note> ds = notesPlugin.getLayer().getDataSet();
if (fireSelectionChanged) {
if(ds == null)
ds = new ArrayList<Note>();
}
}
private void scrollToSelected(Note node) {
for (int i = 0; i < bugListModel.getSize(); i++) {
Note current = (Note)bugListModel.get(i);
if (current.getId()== node.getId()) {
bugList.scrollRectToVisible(bugList.getCellBounds(i, i));
bugList.setSelectedIndex(i);
return;
}
}
}
public void activeLayerChange(Layer oldLayer, Layer newLayer) {
}
public void layerAdded(Layer newLayer) {
if (newLayer == notesPlugin.getLayer()) {
update(notesPlugin.getDataSet());
Main.map.mapView.moveLayer(newLayer, 0);
}
}
public void layerRemoved(Layer oldLayer) {
if (oldLayer == notesPlugin.getLayer()) {
bugListModel.removeAllElements();
}
}
public void zoomToNote(Note node) {
Main.map.mapView.zoomTo(node.getLatLon());
}
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
Note selectedNote = getSelectedNote();
if(selectedNote != null) {
notesPlugin.getLayer().replaceSelection(selectedNote);
if (e.getClickCount() == 2) {
zoomToNote(selectedNote);
}
}
}
}
public void mousePressed(MouseEvent e) {
mayTriggerPopup(e);
}
public void mouseReleased(MouseEvent e) {
mayTriggerPopup(e);
}
private void mayTriggerPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
int selectedRow = bugList.locationToIndex(e.getPoint());
bugList.setSelectedIndex(selectedRow);
Note selectedNote = getSelectedNote();
if(selectedNote != null) {
PopupFactory.createPopup(selectedNote, this).show(e.getComponent(), e.getX(), e.getY());
}
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void actionPerformed(NotesAction action) {
if (action instanceof AddCommentAction || action instanceof CloseNoteAction) {
update(notesPlugin.getDataSet());
}
}
private static class BugComparator implements Comparator<Note> {
public int compare(Note o1, Note o2) {
Note.State state1 = o1.getState();
Note.State state2 = o2.getState();
if (state1.equals(state2)) {
return o1.getFirstComment().getText().compareTo(o2.getFirstComment().getText());
}
return state1.compareTo(state2);
}
}
public void showQueuePanel() {
if(!queuePanelVisible) {
remove(bugListPanel);
tabbedPane.add(bugListPanel, 0);
add(tabbedPane, BorderLayout.CENTER);
tabbedPane.setSelectedIndex(0);
queuePanelVisible = true;
invalidate();
repaint();
}
}
public void hideQueuePanel() {
if(queuePanelVisible) {
tabbedPane.remove(bugListPanel);
remove(tabbedPane);
add(bugListPanel, BorderLayout.CENTER);
queuePanelVisible = false;
invalidate();
repaint();
}
}
public Note getSelectedNote() {
if(bugList.getSelectedValue() != null) {
return (Note)bugList.getSelectedValue();
} else {
return null;
}
}
public void setSelectedNote(Note note) {
if(note == null) {
bugList.clearSelection();
} else {
bugList.setSelectedValue(note, true);
}
}
public void setConnectionMode(boolean offline) {
refresh.setEnabled(!offline);
setTitle(tr("OpenStreetMap Notes ({0})", (offline ? tr("offline") : tr("online"))));
toggleConnectionMode.setSelected(offline);
}
public void selectionChanged(Collection<Note> newSelection) {
if(newSelection.size() == 1) {
Note selectedNote = newSelection.iterator().next();
if(notesPlugin.getLayer() != null && notesPlugin.getLayer().getDataSet() != null
&& notesPlugin.getLayer().getDataSet() != null
&& notesPlugin.getLayer().getDataSet().contains(selectedNote))
{
setSelectedNote(selectedNote);
} else {
bugList.clearSelection();
}
} else {
bugList.clearSelection();
}
}
public ActionQueue getActionQueue() {
return actionQueue;
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
bugList.setEnabled(enabled);
queueList.setEnabled(enabled);
addComment.setEnabled(enabled);
closeIssue.setEnabled(enabled);
}
}
| true | true | public NotesDialog(final NotesPlugin plugin) {
super(tr("OpenStreetMap Notes"), "note_icon24.png",
tr("Opens the OpenStreetMap Notes window and activates the automatic download"), Shortcut.registerShortcut(
"view:osmnotes", tr("Toggle: {0}", tr("Open OpenStreetMap Notes")), KeyEvent.VK_B,
Shortcut.ALT_SHIFT), 150);
notesPlugin = plugin;
bugListPanel = new JPanel(new BorderLayout());
bugListPanel.setName(tr("Bug list"));
add(bugListPanel, BorderLayout.CENTER);
bugListModel = new DefaultListModel();
bugList = new JList(bugListModel);
bugList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
bugList.addListSelectionListener(this);
bugList.addMouseListener(this);
bugList.setCellRenderer(new NotesBugListCellRenderer());
bugListPanel.add(new JScrollPane(bugList), BorderLayout.CENTER);
// create dialog buttons
GridLayout layout = buttonLabels ? new GridLayout(3, 2) : new GridLayout(1, 6);
JPanel buttonPanel = new JPanel(layout);
refresh = new JButton(tr("Refresh"));
refresh.setToolTipText(tr("Refresh"));
refresh.setIcon(NotesPlugin.loadIcon("view-refresh22.png"));
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int zoom = OsmUrlToBounds.getZoom(Main.map.mapView.getRealBounds());
// check zoom level
if (zoom > 15 || zoom < 9) {
JOptionPane.showMessageDialog(Main.parent,
tr("The visible area is either too small or too big to download data from OpenStreetMap Notes"),
tr("Warning"), JOptionPane.INFORMATION_MESSAGE);
return;
}
plugin.updateData();
}
});
bugListPanel.add(buttonPanel, BorderLayout.SOUTH);
Action toggleConnectionModeAction = new ToggleConnectionModeAction(this, notesPlugin);
toggleConnectionMode = new JToggleButton(toggleConnectionModeAction);
toggleConnectionMode.setToolTipText(ToggleConnectionModeAction.MSG_OFFLINE);
boolean offline = Main.pref.getBoolean(ConfigKeys.NOTES_API_OFFLINE);
toggleConnectionMode.setIcon(NotesPlugin.loadIcon("online22.png"));
toggleConnectionMode.setSelectedIcon(NotesPlugin.loadIcon("offline22.png"));
if(offline) {
// inverse the current value and then do a click, so that
// we are offline and the gui represents the offline state, too
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, false);
toggleConnectionMode.doClick();
}
AddCommentAction addCommentAction = new AddCommentAction(this);
addComment = new JButton(addCommentAction);
addComment.setEnabled(false);
addComment.setToolTipText((String) addComment.getAction().getValue(Action.NAME));
addComment.setIcon(NotesPlugin.loadIcon("add_comment22.png"));
CloseNoteAction closeIssueAction = new CloseNoteAction(this);
closeIssue = new JButton(closeIssueAction);
closeIssue.setEnabled(false);
closeIssue.setToolTipText((String) closeIssue.getAction().getValue(Action.NAME));
closeIssue.setIcon(NotesPlugin.loadIcon("closed_note22.png"));
PointToNewNoteAction nia = new PointToNewNoteAction(newIssue, notesPlugin);
newIssue.setAction(nia);
newIssue.setToolTipText((String) newIssue.getAction().getValue(Action.NAME));
newIssue.setIcon(NotesPlugin.loadIcon("new_note22.png"));
ReopenAction reopenAction = new ReopenAction(this);
reopenNote = new JButton(reopenAction);
reopenNote.setIcon(NotesPlugin.loadIcon("reopen_note22.png"));
reopenNote.setToolTipText(reopenNote.getAction().getValue(Action.NAME).toString());
buttonPanel.add(toggleConnectionMode);
buttonPanel.add(refresh);
buttonPanel.add(newIssue);
buttonPanel.add(addComment);
buttonPanel.add(closeIssue);
buttonPanel.add(reopenNote);
queuePanel = new JPanel(new BorderLayout());
queuePanel.setName(tr("Queue"));
queueList = new JList(getActionQueue());
queueList.setCellRenderer(new NotesQueueListCellRenderer());
queuePanel.add(new JScrollPane(queueList), BorderLayout.CENTER);
queuePanel.add(processQueue, BorderLayout.SOUTH);
processQueue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, "false");
setConnectionMode(false);
try {
getActionQueue().processQueue();
// refresh, if the api is enabled
if(!Main.pref.getBoolean(ConfigKeys.NOTES_API_DISABLED)) {
plugin.updateData();
}
} catch (Exception e1) {
System.err.println("Couldn't process action queue");
e1.printStackTrace();
}
}
});
tabbedPane.add(queuePanel);
if (buttonLabels) {
toggleConnectionMode.setHorizontalAlignment(SwingConstants.LEFT);
refresh.setHorizontalAlignment(SwingConstants.LEFT);
addComment.setHorizontalAlignment(SwingConstants.LEFT);
closeIssue.setHorizontalAlignment(SwingConstants.LEFT);
newIssue.setHorizontalAlignment(SwingConstants.LEFT);
} else {
toggleConnectionMode.setText(null);
refresh.setText(null);
addComment.setText(null);
closeIssue.setText(null);
newIssue.setText(null);
}
addCommentAction.addActionObserver(this);
closeIssueAction.addActionObserver(this);
setConnectionMode(offline);
MapView.addLayerChangeListener(this);
}
| public NotesDialog(final NotesPlugin plugin) {
super(tr("OpenStreetMap Notes"), "note_icon24.png",
tr("Opens the OpenStreetMap Notes window and activates the automatic download"), Shortcut.registerShortcut(
"view:osmnotes", tr("Toggle: {0}", tr("Open OpenStreetMap Notes")), KeyEvent.VK_B,
Shortcut.ALT_SHIFT), 150);
notesPlugin = plugin;
bugListPanel = new JPanel(new BorderLayout());
bugListPanel.setName(tr("Bug list"));
add(bugListPanel, BorderLayout.CENTER);
bugListModel = new DefaultListModel();
bugList = new JList(bugListModel);
bugList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
bugList.addListSelectionListener(this);
bugList.addMouseListener(this);
bugList.setCellRenderer(new NotesBugListCellRenderer());
bugListPanel.add(new JScrollPane(bugList), BorderLayout.CENTER);
// create dialog buttons
GridLayout layout = buttonLabels ? new GridLayout(3, 2) : new GridLayout(1, 6);
JPanel buttonPanel = new JPanel(layout);
refresh = new JButton(tr("Refresh"));
refresh.setToolTipText(tr("Refresh"));
refresh.setIcon(NotesPlugin.loadIcon("view-refresh22.png"));
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int zoom = OsmUrlToBounds.getZoom(Main.map.mapView.getRealBounds());
// check zoom level
if (zoom > 15 || zoom < 9) {
JOptionPane.showMessageDialog(Main.parent,
tr("The visible area is either too small or too big to download data from OpenStreetMap Notes"),
tr("Warning"), JOptionPane.INFORMATION_MESSAGE);
return;
}
plugin.updateData();
}
});
bugListPanel.add(buttonPanel, BorderLayout.SOUTH);
Action toggleConnectionModeAction = new ToggleConnectionModeAction(this, notesPlugin);
toggleConnectionMode = new JToggleButton(toggleConnectionModeAction);
toggleConnectionMode.setToolTipText(ToggleConnectionModeAction.MSG_OFFLINE);
boolean offline = Main.pref.getBoolean(ConfigKeys.NOTES_API_OFFLINE);
toggleConnectionMode.setIcon(NotesPlugin.loadIcon("online22.png"));
toggleConnectionMode.setSelectedIcon(NotesPlugin.loadIcon("offline22.png"));
if(offline) {
// inverse the current value and then do a click, so that
// we are offline and the gui represents the offline state, too
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, false);
toggleConnectionMode.doClick();
}
AddCommentAction addCommentAction = new AddCommentAction(this);
addComment = new JButton(addCommentAction);
addComment.setEnabled(false);
addComment.setToolTipText((String) addComment.getAction().getValue(Action.NAME));
addComment.setIcon(NotesPlugin.loadIcon("add_comment22.png"));
CloseNoteAction closeIssueAction = new CloseNoteAction(this);
closeIssue = new JButton(closeIssueAction);
closeIssue.setEnabled(false);
closeIssue.setToolTipText((String) closeIssue.getAction().getValue(Action.NAME));
closeIssue.setIcon(NotesPlugin.loadIcon("closed_note22.png"));
PointToNewNoteAction nia = new PointToNewNoteAction(newIssue, notesPlugin);
newIssue.setAction(nia);
newIssue.setToolTipText((String) newIssue.getAction().getValue(Action.NAME));
newIssue.setIcon(NotesPlugin.loadIcon("new_note22.png"));
ReopenAction reopenAction = new ReopenAction(this);
reopenNote = new JButton(reopenAction);
reopenNote.setIcon(NotesPlugin.loadIcon("reopen_note22.png"));
reopenNote.setToolTipText(reopenNote.getAction().getValue(Action.NAME).toString());
buttonPanel.add(toggleConnectionMode);
buttonPanel.add(refresh);
buttonPanel.add(newIssue);
buttonPanel.add(addComment);
buttonPanel.add(closeIssue);
buttonPanel.add(reopenNote);
queuePanel = new JPanel(new BorderLayout());
queuePanel.setName(tr("Queue"));
queueList = new JList(getActionQueue());
queueList.setCellRenderer(new NotesQueueListCellRenderer());
queuePanel.add(new JScrollPane(queueList), BorderLayout.CENTER);
queuePanel.add(processQueue, BorderLayout.SOUTH);
processQueue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, "false");
setConnectionMode(false);
try {
getActionQueue().processQueue();
// refresh, if the api is enabled
if(!Main.pref.getBoolean(ConfigKeys.NOTES_API_DISABLED)) {
plugin.updateData();
}
} catch (Exception e1) {
System.err.println("Couldn't process action queue");
e1.printStackTrace();
}
}
});
tabbedPane.add(queuePanel);
if (buttonLabels) {
toggleConnectionMode.setHorizontalAlignment(SwingConstants.LEFT);
refresh.setHorizontalAlignment(SwingConstants.LEFT);
addComment.setHorizontalAlignment(SwingConstants.LEFT);
closeIssue.setHorizontalAlignment(SwingConstants.LEFT);
newIssue.setHorizontalAlignment(SwingConstants.LEFT);
reopenNote.setHorizontalAlignment(SwingConstants.LEFT);
} else {
toggleConnectionMode.setText(null);
refresh.setText(null);
addComment.setText(null);
closeIssue.setText(null);
newIssue.setText(null);
}
addCommentAction.addActionObserver(this);
closeIssueAction.addActionObserver(this);
setConnectionMode(offline);
MapView.addLayerChangeListener(this);
}
|
diff --git a/src/main/ed/db/DBCollection.java b/src/main/ed/db/DBCollection.java
index 2958d6384..b4c79be54 100644
--- a/src/main/ed/db/DBCollection.java
+++ b/src/main/ed/db/DBCollection.java
@@ -1,773 +1,778 @@
// DBCollection.java
package ed.db;
import java.util.*;
import java.lang.reflect.*;
import ed.js.*;
import ed.js.func.*;
import ed.js.engine.*;
import ed.util.*;
/** DB Collection
*
* Class for database collection objects. When you invoke something like:
* var my_coll = db.students;
* you get back a collection which can be used to perform various database operations.
*
* @anonymous name : {base}, desc : {The name of the database containing this collection.} type : {String}, isField : {true}
* @anonymous name : {name}, desc : {The name of this collection}, type : {String}, isField : {true}
* @anonymous name : {save}, desc : {Saves an object to the collection.}, return : {type : (JSObject), desc : (new object from the collection)}, param : {type : (JSObject), name : (o), desc : (object to save)}
* @anonymous name : {update}, desc : {Updates an object in the collection.}, return : {type : (JSObject), desc : (the updated object)}, param : {type : (JSObject), name : (o), desc : (object to update)}, param : { type : (JSObject), name : (newo), desc : (object with which to update the old object)}, param : { type : (JSObject), name : (opts), desc : (boolean options to set for update)}
* @anonymous name : {remove}, desc : {Removes an object from this collection.}, return : {type : (int), desc : (-1)}, param : {type : (JSObject), name : (q), desc : (removes object that match this query)}
* @anonymous name : {apply}, desc : {Prepares an object for insertion into the collection.}, return : {type : (JSObject), desc : (given object with added "hidden" database fields)}, param : {type : (JSObject), name : (o), desc : (object to prepare) }
* @anonymous name : {find}, desc : {Finds objects in this collection matching a given query.}, return : {type : (DBCursor), desc : (a cursor over any matching elements)}, param : {type : (JSObject), name : (query), desc : (query to use)}, param : { type : (JSObject), name : (f), desc : (fields to return)
* @anonymous name : {findOne}, desc : {Returns the first object in this collection matching a given query.}, return : {type : (JSObject), desc : (the first matching element)}, param : {type : (JSObject), name : (query), desc : (query to use)}, param : { type : (JSObject), name : (f), desc : (fields to return)
* @anonymous name : {tojson}, desc : {Returns a description of this collection as a string.}, return : {type : (String), desc : ("{DBCollection:this.collection.name}")}
* @expose
* @docmodule system.database.collection
*/
public abstract class DBCollection extends JSObjectLame {
/** @unexpose */
final static boolean DEBUG = Boolean.getBoolean( "DEBUG.DB" );
/** Saves an object to the database.
* @param o object to save
* @return the new database object
*/
protected abstract JSObject doSave( JSObject o );
/** Performs an update operation.
* @param q search query for old object to update
* @param o object with which to update <tt>q</tt>
* @param upsert if the database should create the element if it does not exist
* @param apply if an _id field should be added to the new object
* See www.10gen.com/wiki/db.update
*/
public abstract JSObject update( JSObject q , JSObject o , boolean upsert , boolean apply );
/** Adds any necessary fields to a given object before saving it to the collection.
* @param o object to which to add the fields
*/
protected abstract void doapply( JSObject o );
/** Removes an object from the database collection.
* @param id The _id of the object to be removed
* @return -1
*/
public abstract int remove( JSObject id );
/** Finds an object by its id.
* @param id the id of the object
* @return the object, if found
*/
protected abstract JSObject dofind( ObjectId id );
/** Finds an object.
* @param ref query used to search
* @param fields the fields of matching objects to return
* @param numToSkip will not return the first <tt>numToSkip</tt> matches
* @param numToReturn limit the results to this number
* @return the objects, if found
*/
public abstract Iterator<JSObject> find( JSObject ref , JSObject fields , int numToSkip , int numToReturn );
/** Ensures an index on this collection (that is, the index will be created if it does not exist).
* ensureIndex is optimized and is inexpensive if the index already exists.
* @param keys fields to use for index
* @param name an identifier for the index
*/
public abstract void ensureIndex( JSObject keys , String name );
// ------
/** Finds an object by its id.
* @param id the id of the object
* @return the object, if found
*/
public final JSObject find( ObjectId id ){
ensureIDIndex();
JSObject ret = dofind( id );
if ( ret == null )
return null;
apply( ret , false );
return ret;
}
/** Ensures an index on the id field, if one does not already exist.
* @param key an object with an _id field.
*/
public void checkForIDIndex( JSObject key ){
if ( _checkedIdIndex ) // we already created it, so who cares
return;
if ( key.get( "_id" ) == null )
return;
if ( key.keySet( false ).size() > 1 )
return;
ensureIDIndex();
}
/** Creates an index on the id field, if one does not already exist.
* @param key an object with an _id field.
*/
public void ensureIDIndex(){
if ( _checkedIdIndex )
return;
ensureIndex( _idKey );
_checkedIdIndex = true;
}
/** Creates an index on a set of fields, if one does not already exist.
* @param keys an object with a key set of the fields desired for the index
*/
public final void ensureIndex( final JSObject keys ){
ensureIndex( keys , false );
}
/** Forces creation of an index on a set of fields, if one does not already exist.
* @param keys an object with a key set of the fields desired for the index
*/
public final void createIndex( final JSObject keys ){
ensureIndex( keys , true );
}
/** Creates an index on a set of fields, if one does not already exist.
* @param keys an object with a key set of the fields desired for the index
* @param force if index creation should be forced, even if it is unnecessary
*/
public final void ensureIndex( final JSObject keys , final boolean force ){
if ( checkReadOnly( false ) ) return;
final String name = genIndexName( keys );
boolean doEnsureIndex = false;
if ( Math.random() > 0.999 )
doEnsureIndex = true;
else if ( ! _createIndexes.contains( name ) )
doEnsureIndex = true;
else if ( _anyUpdateSave && ! _createIndexesAfterSave.contains( name ) )
doEnsureIndex = true;
if ( ! ( force || doEnsureIndex ) )
return;
ensureIndex( keys , name );
_createIndexes.add( name );
if ( _anyUpdateSave )
_createIndexesAfterSave.add( name );
}
/** Clear all indices on this collection. */
public void resetIndexCache(){
_createIndexes.clear();
}
/** Generate an index name from the set of fields it is over.
* @param keys the names of the fields used in this index
* @return a string representation of this index's fields
*/
public String genIndexName( JSObject keys ){
String name = "";
for ( String s : keys.keySet( false ) ){
if ( name.length() > 0 )
name += "_";
name += s + "_";
Object val = keys.get( s );
if ( val instanceof Number )
name += JSInternalFunctions.JS_toString( val ).replace( ' ' , '_' );
}
return name;
}
/** Queries for an object in this collection.
* @param ref object for which to search
* @return an iterator over the results
*/
public final Iterator<JSObject> find( JSObject ref ){
return find( ref == null ? new JSObjectBase() : ref , null , 0 , 0 );
}
public final Iterator<JSObject> find(){
return find( new JSObjectBase() , null , 0 , 0 );
}
public final JSObject findOne(){
return findOne( new JSObjectBase() );
}
public final JSObject findOne( JSObject o ){
Iterator<JSObject> i = find( o , null , 0 , 1 );
if ( i == null || ! i.hasNext() )
return null;
return i.next();
}
/**
*/
public final ObjectId apply( Object o ){
return apply( o , true );
}
/** Adds the "private" fields _save, _update, and _id to an object.
* @param o object to which to add fields
* @param ensureID if an _id field is needed
* @return the _id assigned to the object
* @throws RuntimeException if <tt>o</tt> is not a JSObject
*/
public final ObjectId apply( Object o , boolean ensureID ){
if ( ! ( o instanceof JSObject ) )
throw new RuntimeException( "can only apply JSObject" );
JSObject jo = (JSObject)o;
jo.set( "_save" , _save );
jo.set( "_update" , _update );
ObjectId id = (ObjectId)jo.get( "_id" );
if ( ensureID && id == null ){
id = ObjectId.get();
jo.set( "_id" , id );
}
doapply( jo );
return id;
}
/** Sets a constructor to use for objects in this collection.
* @param cons the constructor to use
*/
public void setConstructor( JSFunction cons ){
_constructor = cons;
}
/** Returns the constructor for this collection.
* @return the constructor function
*/
public JSFunction getConstructor(){
return _constructor;
}
/** Saves an object to this collection.
* @param o the object to save
* @return the new object from the collection
*/
public final Object save( Object o ){
if ( checkReadOnly( true ) ) return null;
return save( null , o );
}
/** Saves an object to this collection executing the preSave function in a given scope.
* @param s scope to use (can be null)
* @param o the object to save
* @return the new object from the collection
*/
public final Object save( Scope s , Object o ){
if ( checkReadOnly( true ) ) return o;
o = _handleThis( s , o );
_checkObject( o , false );
JSObject jo = (JSObject)o;
if ( s != null ){
Object presaveObject = jo.get( "preSave" );
if ( presaveObject == null )
presaveObject = jo.get( "presave" ); // TODO: we should deprecate
if ( presaveObject != null ){
if ( presaveObject instanceof JSFunction ){
s.setThis( jo );
((JSFunction)presaveObject).call( s );
s.clearThisNormal( null );
}
else {
System.out.println( "warning, preSave is a " + presaveObject.getClass() );
}
}
_findSubObject( s , jo , null );
}
ObjectId id = (ObjectId)jo.get( "_id" );
if ( DEBUG ) System.out.println( "id : " + id );
if ( id == null || id._new ){
if ( DEBUG ) System.out.println( "saving new object" );
if ( id != null )
id._new = false;
doSave( jo );
return jo;
}
if ( DEBUG ) System.out.println( "doing implicit upsert : " + jo.get( "_id" ) );
JSObject q = new JSObjectBase();
q.set( "_id" , id );
return _update.call( s , q , jo , _upsertOptions );
}
// ------
/** Initializes a new collection.
* @param base database in which to create the collection
* @param name the name of the collection
*/
protected DBCollection( DBBase base , String name ){
_base = base;
_name = name;
_fullName = _base.getName() + "." + name;
_entries.put( "base" , _base.getName() );
_entries.put( "name" , _name );
_save = new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object fooasd[] ){
_anyUpdateSave = true;
return save( s , o );
}
};
_entries.put( "save" , _save );
_update = new JSFunctionCalls4(){
public Object call( Scope s , Object q , Object o , Object options , Object seen , Object foo[] ){
if ( checkReadOnly( true ) ) return o;
_anyUpdateSave = true;
_checkObject( q , false );
_checkObject( o , false );
if ( s != null )
_findSubObject( s , (JSObject)o , (IdentitySet)seen );
boolean upsert = false;
boolean apply = true;
/* this is for $inc and $set: we don't add an object id then. see struct Mod in p/db/query.cpp */
if ( o instanceof JSObject ) {
apply = false;
for( String key : ((JSObject)o).keySet() ){
if ( ! key.startsWith( "$" ) ){
apply = true;
break;
}
}
}
// if ( o instanceof JSObject && ((JSObject)o).containsKey( "$inc" ) )
// apply = false;
if ( options instanceof JSObject ){
JSObject params = (JSObject)options;
upsert = JSInternalFunctions.JS_evalToBool( params.get( "upsert" ) );
if ( params.get( "ids" ) != null )
apply = JSInternalFunctions.JS_evalToBool( params.get( "ids" ) );
}
return update( (JSObject)q , (JSObject)o , upsert , apply );
}
};
_entries.put( "update" , _update );
_entries.put( "remove" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object o , Object foo[] ){
if ( checkReadOnly( true ) ) return o;
o = _handleThis( s , o );
if ( o == null )
throw new NullPointerException( "can't pass null to collection.remove. if you mean to remove everything, do remove( {} ) " );
if ( ! ( o instanceof JSObject ) )
throw new RuntimeException( "have to pass collection.remove a javascript object" );
return remove( (JSObject)o );
}
} );
_apply = new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
return apply( o );
}
};
_entries.put( "apply" , _apply );
_find = new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object fieldsWantedO , Object foo[] ){
if ( o instanceof DBRef )
o = ((DBRef)o)._id;
if ( o == null )
o = new JSObjectBase();
if ( o instanceof JSFunction && ((JSFunction)o).isCallable() && ((JSFunction)o).getSourceCode() != null ){
JSObjectBase obj = new JSObjectBase();
obj.set( "$where" , o );
o = obj;
}
if ( o instanceof String || o instanceof JSString ){
String str = o.toString();
if ( ObjectId.isValid( str ) )
o = new ObjectId( str );
else
throw new IllegalArgumentException( "can't call find() with a string that is not a valid ObjectId" );
}
- if ( o instanceof ObjectId )
- return find( (ObjectId)o );
+ if ( o instanceof ObjectId ){
+ if ( fieldsWantedO == null )
+ return find( (ObjectId)o );
+ JSObjectBase obj = new JSObjectBase();
+ obj.set( "_id" , o );
+ o = obj;
+ }
if ( o instanceof JSObject ){
JSObject key = (JSObject)o;
checkForIDIndex( key );
return new DBCursor( DBCollection.this , key , (JSObject)fieldsWantedO , _constructor );
}
throw new RuntimeException( "wtf : " + o.getClass() );
}
};
_entries.put( "find" , _find );
_entries.put( "findOne" ,
new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
Object res = _find.call( s , o , foo );
if ( res == null )
return null;
if ( res instanceof DBCursor )
((DBCursor)res).limit( 1 );
if ( res instanceof JSArray ){
JSArray a = (JSArray)res;
if ( a.size() == 0 )
return null;
return a.getInt( 0 );
}
if ( res instanceof Iterator ){
Iterator<JSObject> it = (Iterator<JSObject>)res;
if ( ! it.hasNext() )
return null;
return it.next();
}
if ( res instanceof JSObject )
return res;
throw new RuntimeException( "wtf : " + res.getClass() );
}
} );
_entries.put( "tojson" ,
new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return "{DBCollection:" + DBCollection.this._fullName + "}";
}
} );
}
protected void _finishInit(){
if ( _name.equals( "_file" ) )
JSFile.setup( this );
else if ( _name.equals( "_chunks" ) )
JSFileChunk.setup( this );
}
private final Object _handleThis( Scope s , Object o ){
if ( o != null )
return o;
Object t = s.getThis();
if ( t == null )
return null;
if ( t.getClass() != JSObjectBase.class )
return null;
return t;
}
private final void _checkObject( Object o , boolean canBeNull ){
if ( o == null ){
if ( canBeNull )
return;
throw new NullPointerException( "can't be null" );
}
if ( o instanceof JSObjectBase &&
((JSObjectBase)o).isPartialObject() )
throw new IllegalArgumentException( "can't save partial objects" );
if ( o instanceof JSObject )
return;
throw new IllegalArgumentException( " has to be a JSObject not : " + o.getClass() );
}
private void _findSubObject( Scope s , JSObject jo , IdentitySet seenSubs ){
if ( seenSubs == null )
seenSubs = new IdentitySet();
if ( seenSubs.contains( jo ) )
return;
seenSubs.add( jo );
if ( DEBUG ) System.out.println( "_findSubObject on : " + jo.get( "_id" ) );
LinkedList<JSObject> toSearch = new LinkedList();
Map<JSObject,String> seen = new IdentityHashMap<JSObject,String>();
toSearch.add( jo );
while ( toSearch.size() > 0 ){
Map<JSObject,String> seenNow = new IdentityHashMap<JSObject,String>( seen );
JSObject n = toSearch.remove(0);
for ( String name : n.keySet( false ) ){
Object foo = n.get( name );
if ( foo == null )
continue;
if ( ! ( foo instanceof JSObject ) )
continue;
if ( foo instanceof JSFunction )
continue;
if ( foo instanceof JSString
|| foo instanceof JSRegex
|| foo instanceof JSDate )
continue;
JSObject e = (JSObject)foo;
if ( e instanceof JSObjectBase )
((JSObjectBase)e).prefunc();
if ( n.get( name ) == null )
continue;
if ( e instanceof JSFileChunk ){
_base.getCollection( "_chunks" ).apply( e );
}
if ( e.get( "_ns" ) == null ){
if ( seen.containsKey( e ) )
throw new RuntimeException( "you have a loop. key : " + name + " from a " + n.getClass() + " whis is a : " + e.getClass() );
seenNow.put( e , "a" );
toSearch.add( e );
continue;
}
// ok - now we knows its a reference
if ( e.get( "_id" ) == null ){ // new object, lets save it
JSFunction otherSave = e.getFunction( "_save" );
if ( otherSave == null )
throw new RuntimeException( "no save :(" );
otherSave.call( s , e , null );
continue;
}
// old object, lets update TODO: dirty tracking
JSObject lookup = new JSObjectBase();
lookup.set( "_id" , e.get( "_id" ) );
JSFunction otherUpdate = e.getFunction( "_update" );
if ( otherUpdate == null ){
// already taken care of
if ( e instanceof DBRef )
continue;
throw new RuntimeException( "_update is null. keyset : " + e.keySet( false ) + " ns:" + e.get( "_ns" ) );
}
if ( e instanceof JSObjectBase && ! ((JSObjectBase)e).isDirty() )
continue;
otherUpdate.call( s , lookup , e , _upsertOptions , seenSubs );
}
seen.putAll( seenNow );
}
}
/** Gets any type of object matching the given object from this collection's database.
* @param n object to find
* @return the object, if found
*/
public Object get( Object n ){
if ( n == null )
return null;
Object foo = _entries.get( n.toString() );
if ( foo != null )
return foo;
foo = _base._collectionPrototype.get( n );
if ( foo != null )
return foo;
String s = n.toString();
if ( _getJavaMethods().contains( s ) )
return null;
return getCollection( s );
}
public Collection<String> keySet( boolean includePrototype ){
Set<String> set = new HashSet<String>();
set.addAll( _entries.keySet() );
set.addAll( _base._collectionPrototype.keySet() );
set.addAll( _getJavaMethods() );
// TODO: ? add sub collection names
return set;
}
/** Find a collection that is prefixed with this collection's name.
* @param n the name of the collection to find
* @return the matching collection
*/
public DBCollection getCollection( String n ){
return _base.getCollection( _name + "." + n );
}
/** Returns the name of this collection.
* @return the name of this collection
*/
public String getName(){
return _name;
}
/** Returns the full name of this collection, with the database name as a prefix.
* @return the name of this collection
*/
public String getFullName(){
return _fullName;
}
/** Returns the database this collection is a member of.
* @return this collection's database
*/
public DBBase getDB(){
return _base;
}
/** Returns the database this collection is a member of.
* @return this collection's database
*/
public DBBase getBase(){
return _base;
}
/** Returns if this collection can be modified.
* @return if this collection can be modified
*/
protected boolean checkReadOnly( boolean strict ){
if ( ! _base._readOnly )
return false;
if ( ! strict )
return true;
Scope scope = Scope.getThreadLocal();
if ( scope == null )
throw new JSException( "db is read only" );
Object foo = scope.get( "dbStrict" );
if ( foo == null || JSInternalFunctions.JS_evalToBool( foo ) )
throw new JSException( "db is read only" );
return true;
}
/** Calculates the hash code for this collection.
* @return the hash code
*/
public int hashCode(){
return _fullName.hashCode();
}
/** Checks if this collection is equal to another object.
* @param o object with which to compare this collection
* @return if the two collections are equal
*/
public boolean equals( Object o ){
return o == this;
}
/** Returns a string representation of this collection, that is, "{DBCollection: name.of.this.collection}"
* @return a string representation of this collection
*/
public String toString(){
return "{DBCollection:" + _name + "}";
}
private Set<String> _getJavaMethods(){
if ( _javaMethods == null ){
Set<String> temp = new HashSet<String>();
for ( Method m : this.getClass().getMethods() )
temp.add( m.getName() );
_javaMethods = temp;
}
return _javaMethods;
}
final DBBase _base;
final JSFunction _save;
final JSFunction _update;
final JSFunction _apply;
final JSFunction _find;
static Set<String> _javaMethods;
protected Map _entries = new TreeMap();
final protected String _name;
final protected String _fullName;
protected JSFunction _constructor;
private boolean _anyUpdateSave = false;
private boolean _checkedIdIndex = false;
final private Set<String> _createIndexes = new HashSet<String>();
final private Set<String> _createIndexesAfterSave = new HashSet<String>();
private final static JSObjectBase _upsertOptions = new JSObjectBase();
static {
_upsertOptions.set( "upsert" , true );
_upsertOptions.setReadOnly( true );
}
private final static JSObjectBase _idKey = new JSObjectBase();
static {
_idKey.set( "_id" , ObjectId.get() );
_idKey.setReadOnly( true );
}
}
| true | true | protected DBCollection( DBBase base , String name ){
_base = base;
_name = name;
_fullName = _base.getName() + "." + name;
_entries.put( "base" , _base.getName() );
_entries.put( "name" , _name );
_save = new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object fooasd[] ){
_anyUpdateSave = true;
return save( s , o );
}
};
_entries.put( "save" , _save );
_update = new JSFunctionCalls4(){
public Object call( Scope s , Object q , Object o , Object options , Object seen , Object foo[] ){
if ( checkReadOnly( true ) ) return o;
_anyUpdateSave = true;
_checkObject( q , false );
_checkObject( o , false );
if ( s != null )
_findSubObject( s , (JSObject)o , (IdentitySet)seen );
boolean upsert = false;
boolean apply = true;
/* this is for $inc and $set: we don't add an object id then. see struct Mod in p/db/query.cpp */
if ( o instanceof JSObject ) {
apply = false;
for( String key : ((JSObject)o).keySet() ){
if ( ! key.startsWith( "$" ) ){
apply = true;
break;
}
}
}
// if ( o instanceof JSObject && ((JSObject)o).containsKey( "$inc" ) )
// apply = false;
if ( options instanceof JSObject ){
JSObject params = (JSObject)options;
upsert = JSInternalFunctions.JS_evalToBool( params.get( "upsert" ) );
if ( params.get( "ids" ) != null )
apply = JSInternalFunctions.JS_evalToBool( params.get( "ids" ) );
}
return update( (JSObject)q , (JSObject)o , upsert , apply );
}
};
_entries.put( "update" , _update );
_entries.put( "remove" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object o , Object foo[] ){
if ( checkReadOnly( true ) ) return o;
o = _handleThis( s , o );
if ( o == null )
throw new NullPointerException( "can't pass null to collection.remove. if you mean to remove everything, do remove( {} ) " );
if ( ! ( o instanceof JSObject ) )
throw new RuntimeException( "have to pass collection.remove a javascript object" );
return remove( (JSObject)o );
}
} );
_apply = new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
return apply( o );
}
};
_entries.put( "apply" , _apply );
_find = new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object fieldsWantedO , Object foo[] ){
if ( o instanceof DBRef )
o = ((DBRef)o)._id;
if ( o == null )
o = new JSObjectBase();
if ( o instanceof JSFunction && ((JSFunction)o).isCallable() && ((JSFunction)o).getSourceCode() != null ){
JSObjectBase obj = new JSObjectBase();
obj.set( "$where" , o );
o = obj;
}
if ( o instanceof String || o instanceof JSString ){
String str = o.toString();
if ( ObjectId.isValid( str ) )
o = new ObjectId( str );
else
throw new IllegalArgumentException( "can't call find() with a string that is not a valid ObjectId" );
}
if ( o instanceof ObjectId )
return find( (ObjectId)o );
if ( o instanceof JSObject ){
JSObject key = (JSObject)o;
checkForIDIndex( key );
return new DBCursor( DBCollection.this , key , (JSObject)fieldsWantedO , _constructor );
}
throw new RuntimeException( "wtf : " + o.getClass() );
}
};
_entries.put( "find" , _find );
_entries.put( "findOne" ,
new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
Object res = _find.call( s , o , foo );
if ( res == null )
return null;
if ( res instanceof DBCursor )
((DBCursor)res).limit( 1 );
if ( res instanceof JSArray ){
JSArray a = (JSArray)res;
if ( a.size() == 0 )
return null;
return a.getInt( 0 );
}
if ( res instanceof Iterator ){
Iterator<JSObject> it = (Iterator<JSObject>)res;
if ( ! it.hasNext() )
return null;
return it.next();
}
if ( res instanceof JSObject )
return res;
throw new RuntimeException( "wtf : " + res.getClass() );
}
} );
_entries.put( "tojson" ,
new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return "{DBCollection:" + DBCollection.this._fullName + "}";
}
} );
}
| protected DBCollection( DBBase base , String name ){
_base = base;
_name = name;
_fullName = _base.getName() + "." + name;
_entries.put( "base" , _base.getName() );
_entries.put( "name" , _name );
_save = new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object fooasd[] ){
_anyUpdateSave = true;
return save( s , o );
}
};
_entries.put( "save" , _save );
_update = new JSFunctionCalls4(){
public Object call( Scope s , Object q , Object o , Object options , Object seen , Object foo[] ){
if ( checkReadOnly( true ) ) return o;
_anyUpdateSave = true;
_checkObject( q , false );
_checkObject( o , false );
if ( s != null )
_findSubObject( s , (JSObject)o , (IdentitySet)seen );
boolean upsert = false;
boolean apply = true;
/* this is for $inc and $set: we don't add an object id then. see struct Mod in p/db/query.cpp */
if ( o instanceof JSObject ) {
apply = false;
for( String key : ((JSObject)o).keySet() ){
if ( ! key.startsWith( "$" ) ){
apply = true;
break;
}
}
}
// if ( o instanceof JSObject && ((JSObject)o).containsKey( "$inc" ) )
// apply = false;
if ( options instanceof JSObject ){
JSObject params = (JSObject)options;
upsert = JSInternalFunctions.JS_evalToBool( params.get( "upsert" ) );
if ( params.get( "ids" ) != null )
apply = JSInternalFunctions.JS_evalToBool( params.get( "ids" ) );
}
return update( (JSObject)q , (JSObject)o , upsert , apply );
}
};
_entries.put( "update" , _update );
_entries.put( "remove" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object o , Object foo[] ){
if ( checkReadOnly( true ) ) return o;
o = _handleThis( s , o );
if ( o == null )
throw new NullPointerException( "can't pass null to collection.remove. if you mean to remove everything, do remove( {} ) " );
if ( ! ( o instanceof JSObject ) )
throw new RuntimeException( "have to pass collection.remove a javascript object" );
return remove( (JSObject)o );
}
} );
_apply = new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
return apply( o );
}
};
_entries.put( "apply" , _apply );
_find = new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object fieldsWantedO , Object foo[] ){
if ( o instanceof DBRef )
o = ((DBRef)o)._id;
if ( o == null )
o = new JSObjectBase();
if ( o instanceof JSFunction && ((JSFunction)o).isCallable() && ((JSFunction)o).getSourceCode() != null ){
JSObjectBase obj = new JSObjectBase();
obj.set( "$where" , o );
o = obj;
}
if ( o instanceof String || o instanceof JSString ){
String str = o.toString();
if ( ObjectId.isValid( str ) )
o = new ObjectId( str );
else
throw new IllegalArgumentException( "can't call find() with a string that is not a valid ObjectId" );
}
if ( o instanceof ObjectId ){
if ( fieldsWantedO == null )
return find( (ObjectId)o );
JSObjectBase obj = new JSObjectBase();
obj.set( "_id" , o );
o = obj;
}
if ( o instanceof JSObject ){
JSObject key = (JSObject)o;
checkForIDIndex( key );
return new DBCursor( DBCollection.this , key , (JSObject)fieldsWantedO , _constructor );
}
throw new RuntimeException( "wtf : " + o.getClass() );
}
};
_entries.put( "find" , _find );
_entries.put( "findOne" ,
new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
Object res = _find.call( s , o , foo );
if ( res == null )
return null;
if ( res instanceof DBCursor )
((DBCursor)res).limit( 1 );
if ( res instanceof JSArray ){
JSArray a = (JSArray)res;
if ( a.size() == 0 )
return null;
return a.getInt( 0 );
}
if ( res instanceof Iterator ){
Iterator<JSObject> it = (Iterator<JSObject>)res;
if ( ! it.hasNext() )
return null;
return it.next();
}
if ( res instanceof JSObject )
return res;
throw new RuntimeException( "wtf : " + res.getClass() );
}
} );
_entries.put( "tojson" ,
new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return "{DBCollection:" + DBCollection.this._fullName + "}";
}
} );
}
|
diff --git a/src/powercrystals/minefactoryreloaded/core/TileEntityFactoryPowered.java b/src/powercrystals/minefactoryreloaded/core/TileEntityFactoryPowered.java
index 3e0fa998..5a27b338 100644
--- a/src/powercrystals/minefactoryreloaded/core/TileEntityFactoryPowered.java
+++ b/src/powercrystals/minefactoryreloaded/core/TileEntityFactoryPowered.java
@@ -1,298 +1,302 @@
package powercrystals.minefactoryreloaded.core;
import powercrystals.core.util.Util;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.liquids.LiquidTank;
import ic2.api.Direction;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import ic2.api.energy.tile.IEnergySink;
import buildcraft.api.power.IPowerProvider;
import buildcraft.api.power.IPowerReceptor;
import buildcraft.api.power.PowerFramework;
/*
* There are three pieces of information tracked - energy, work, and idle ticks.
*
* Energy is stored and used when the machine activates. The energy stored must be >= energyActivation for the activateMachine() method to be called.
* If activateMachine() returns true, energy will be drained.
*
* Work is built up and then when at 100% something happens. This is tracked/used entirely by the derived class. If not used (f.ex. harvester), return max 1.
*
* Idle ticks cause an artificial delay before activateMachine() is called again. Max should be the highest value the machine will use, to draw the
* progress bar correctly.
*/
public abstract class TileEntityFactoryPowered extends TileEntityFactory implements IPowerReceptor, IEnergySink
{
private static int energyPerEU = 4;
private static int energyPerMJ = 10;
private int _energyStored;
private int _energyActivation;
private int _workDone;
private int _idleTicks;
// buildcraft-related fields
private IPowerProvider _powerProvider;
// IC2-related fields
private boolean _isAddedToIC2EnergyNet;
private boolean _addToNetOnNextTick;
// constructors
protected TileEntityFactoryPowered()
{
this(100);
}
protected TileEntityFactoryPowered(int energyActivation)
{
this._energyActivation = energyActivation;
if(PowerFramework.currentFramework != null)
{
_powerProvider = PowerFramework.currentFramework.createPowerProvider();
_powerProvider.configure(25, 10, 10, 1, 1000);
}
setIsActive(false);
}
// local methods
public abstract String getInvName();
protected boolean pumpLiquid()
{
return false;
}
@Override
public void updateEntity()
{
super.updateEntity();
if(_addToNetOnNextTick)
{
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
_addToNetOnNextTick = false;
_isAddedToIC2EnergyNet = true;
}
if(getPowerProvider() != null)
{
getPowerProvider().update(this);
if(_energyStored < getEnergyStoredMax() && getPowerProvider().useEnergy(1, 100, false) > 0)
{
int mjGained = (int)(getPowerProvider().useEnergy(1, 100, true));
_energyStored += mjGained * energyPerMJ;
}
}
if(_idleTicks > 0)
{
_idleTicks--;
}
else if(Util.isRedstonePowered(this))
{
setIdleTicks(getIdleTicksMax());
}
else if(_energyStored >= _energyActivation)
{
if(activateMachine())
{
_energyStored -= _energyActivation;
setIsActive(true);
}
else
{
setIsActive(false);
}
}
+ else
+ {
+ setIsActive(false);
+ }
if(pumpLiquid())
{
MFRUtil.pumpLiquid(getTank(), this);
}
}
@Override
public void validate()
{
super.validate();
if(!_isAddedToIC2EnergyNet)
{
_addToNetOnNextTick = true;
}
}
@Override
public void invalidate()
{
if(_isAddedToIC2EnergyNet)
{
_isAddedToIC2EnergyNet = false;
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
}
super.invalidate();
}
protected abstract boolean activateMachine();
public void onBlockBroken()
{
if(_isAddedToIC2EnergyNet)
{
_isAddedToIC2EnergyNet = false;
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
}
}
public int getEnergyStored()
{
return _energyStored;
}
public abstract int getEnergyStoredMax();
public void setEnergyStored(int energy)
{
_energyStored = energy;
}
public int getWorkDone()
{
return _workDone;
}
public abstract int getWorkMax();
public void setWorkDone(int work)
{
_workDone = work;
}
public int getIdleTicks()
{
return _idleTicks;
}
public abstract int getIdleTicksMax();
public void setIdleTicks(int ticks)
{
_idleTicks = ticks;
}
public ILiquidTank getTank()
{
return null;
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
super.writeToNBT(nbttagcompound);
nbttagcompound.setInteger("energyStored", _energyStored);
nbttagcompound.setInteger("workDone", _workDone);
if(getTank() != null && getTank().getLiquid() != null)
{
nbttagcompound.setInteger("tankAmount", getTank().getLiquid().amount);
nbttagcompound.setInteger("tankItemId", getTank().getLiquid().itemID);
nbttagcompound.setInteger("tankMeta", getTank().getLiquid().itemMeta);
}
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
super.readFromNBT(nbttagcompound);
_energyStored = nbttagcompound.getInteger("energyStored");
_workDone = nbttagcompound.getInteger("workDone");
if(getTank() != null)
{
((LiquidTank)getTank()).setLiquid(new LiquidStack(nbttagcompound.getInteger("tankItemId"), nbttagcompound.getInteger("tankAmount"), nbttagcompound.getInteger("tankItemMeta")));
}
}
// IPowerReceptor methods
@Override
public void setPowerProvider(IPowerProvider provider)
{
_powerProvider = provider;
}
@Override
public IPowerProvider getPowerProvider()
{
return _powerProvider;
}
@Override
public int powerRequest()
{
//return (energyStoredMax - energyStored) / energyPerMJ;
return 10;
}
@Override
public final void doWork()
{
}
// IEnergySink methods
/**
* Determine whether the sink requires energy.
*
* @return max accepted input in eu
*/
public int demandsEnergy()
{
return ((getEnergyStoredMax() - _energyStored) / energyPerEU);
}
/**
* Transfer energy to the sink.
*
* @param directionFrom direction from which the energy comes from
* @param amount energy to be transferred
* @return Energy not consumed (leftover)
*/
public int injectEnergy(Direction directionFrom, int amount)
{
int maxEnergyInjectable = (getEnergyStoredMax() - _energyStored) / energyPerEU;
int euInjected = Math.min(maxEnergyInjectable, amount);
_energyStored += euInjected * energyPerEU;
return amount - euInjected;
}
public boolean acceptsEnergyFrom(TileEntity emitter, Direction direction)
{
return true;
}
public boolean isAddedToEnergyNet()
{
return _isAddedToIC2EnergyNet;
}
@Override
public int getMaxSafeInput()
{
return 128;
}
}
| true | true | public void updateEntity()
{
super.updateEntity();
if(_addToNetOnNextTick)
{
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
_addToNetOnNextTick = false;
_isAddedToIC2EnergyNet = true;
}
if(getPowerProvider() != null)
{
getPowerProvider().update(this);
if(_energyStored < getEnergyStoredMax() && getPowerProvider().useEnergy(1, 100, false) > 0)
{
int mjGained = (int)(getPowerProvider().useEnergy(1, 100, true));
_energyStored += mjGained * energyPerMJ;
}
}
if(_idleTicks > 0)
{
_idleTicks--;
}
else if(Util.isRedstonePowered(this))
{
setIdleTicks(getIdleTicksMax());
}
else if(_energyStored >= _energyActivation)
{
if(activateMachine())
{
_energyStored -= _energyActivation;
setIsActive(true);
}
else
{
setIsActive(false);
}
}
if(pumpLiquid())
{
MFRUtil.pumpLiquid(getTank(), this);
}
}
| public void updateEntity()
{
super.updateEntity();
if(_addToNetOnNextTick)
{
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
_addToNetOnNextTick = false;
_isAddedToIC2EnergyNet = true;
}
if(getPowerProvider() != null)
{
getPowerProvider().update(this);
if(_energyStored < getEnergyStoredMax() && getPowerProvider().useEnergy(1, 100, false) > 0)
{
int mjGained = (int)(getPowerProvider().useEnergy(1, 100, true));
_energyStored += mjGained * energyPerMJ;
}
}
if(_idleTicks > 0)
{
_idleTicks--;
}
else if(Util.isRedstonePowered(this))
{
setIdleTicks(getIdleTicksMax());
}
else if(_energyStored >= _energyActivation)
{
if(activateMachine())
{
_energyStored -= _energyActivation;
setIsActive(true);
}
else
{
setIsActive(false);
}
}
else
{
setIsActive(false);
}
if(pumpLiquid())
{
MFRUtil.pumpLiquid(getTank(), this);
}
}
|
diff --git a/src/org/red5/server/stream/consumer/ConnectionConsumer.java b/src/org/red5/server/stream/consumer/ConnectionConsumer.java
index 69ed04a0..edae760f 100644
--- a/src/org/red5/server/stream/consumer/ConnectionConsumer.java
+++ b/src/org/red5/server/stream/consumer/ConnectionConsumer.java
@@ -1,188 +1,191 @@
package org.red5.server.stream.consumer;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006 by respective authors (see below). All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation; either version 2.1 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.red5.server.api.service.IServiceCall;
import org.red5.server.api.stream.IClientStream;
import org.red5.server.messaging.IMessage;
import org.red5.server.messaging.IMessageComponent;
import org.red5.server.messaging.IPipe;
import org.red5.server.messaging.IPipeConnectionListener;
import org.red5.server.messaging.IPushableConsumer;
import org.red5.server.messaging.OOBControlMessage;
import org.red5.server.messaging.PipeConnectionEvent;
import org.red5.server.net.rtmp.Channel;
import org.red5.server.net.rtmp.RTMPConnection;
import org.red5.server.net.rtmp.event.AudioData;
import org.red5.server.net.rtmp.event.ChunkSize;
import org.red5.server.net.rtmp.event.IRTMPEvent;
import org.red5.server.net.rtmp.event.Notify;
import org.red5.server.net.rtmp.event.Ping;
import org.red5.server.net.rtmp.event.BytesRead;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.net.rtmp.message.Constants;
import org.red5.server.net.rtmp.message.Header;
import org.red5.server.stream.message.RTMPMessage;
import org.red5.server.stream.message.StatusMessage;
public class ConnectionConsumer implements IPushableConsumer,
IPipeConnectionListener {
private static final Log log = LogFactory.getLog(ConnectionConsumer.class);
public static final String KEY = ConnectionConsumer.class.getName();
private RTMPConnection conn;
private Channel video;
private Channel audio;
private Channel data;
private int audioTime;
private boolean videoReceived;
private long index;
private int chunkSize = -1;
public ConnectionConsumer(RTMPConnection conn, byte videoChannel, byte audioChannel, byte dataChannel) {
this.conn = conn;
this.video = conn.getChannel(videoChannel);
this.audio = conn.getChannel(audioChannel);
this.data = conn.getChannel(dataChannel);
this.audioTime = 0;
this.videoReceived = false;
this.index = 0;
}
private long totalAudio = 0;
private long totalVideo = 0;
public void pushMessage(IPipe pipe, IMessage message) {
if (message instanceof StatusMessage) {
StatusMessage statusMsg = (StatusMessage) message;
data.sendStatus(statusMsg.getBody());
}
else if (message instanceof RTMPMessage) {
RTMPMessage rtmpMsg = (RTMPMessage) message;
IRTMPEvent msg = rtmpMsg.getBody();
if (msg.getHeader() == null) {
msg.setHeader(new Header());
}
msg.getHeader().setTimerRelative(rtmpMsg.isTimerRelative());
// log.debug("ts :" + msg.getTimestamp());
switch(msg.getDataType()){
case Constants.TYPE_STREAM_METADATA:
Notify notify = new Notify(((Notify) msg).getData().asReadOnlyBuffer());
notify.setHeader(msg.getHeader());
notify.setTimestamp(msg.getTimestamp());
video.write(notify);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_VIDEO_DATA:
VideoData videoData = new VideoData(((VideoData) msg).getData().asReadOnlyBuffer());
videoData.setHeader(msg.getHeader());
if (audioTime > 0) {
msg.setTimestamp(msg.getTimestamp() + audioTime);
if (msg.getTimestamp() < 0)
msg.setTimestamp(0);
videoData.getHeader().setTimer(msg.getTimestamp());
audioTime = 0;
}
videoData.setTimestamp(msg.getTimestamp());
videoReceived = true;
video.write(videoData);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_AUDIO_DATA:
AudioData audioData = new AudioData(((AudioData) msg).getData().asReadOnlyBuffer());
audioData.setHeader(msg.getHeader());
audioData.setTimestamp(msg.getTimestamp());
// Low-tech audio lag fix
+ // XXX: This can only applied for live streams otherwise audio in VOD streams is delayed
+ /*
if (index > 0 && index % 5 != 0 && msg.getTimestamp() > 0) {
audioData.setTimestamp(msg.getTimestamp() - 1);
msg.getHeader().setTimer(audioData.getTimestamp());
}
+ */
index++;
audio.write(audioData);
if (!videoReceived)
if (msg.getHeader().isTimerRelative())
audioTime += msg.getTimestamp();
else
audioTime = msg.getTimestamp();
if (msg.getHeader().isTimerRelative())
totalAudio += msg.getTimestamp();
else
totalAudio = msg.getTimestamp();
break;
case Constants.TYPE_PING:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.ping((Ping) msg);
break;
case Constants.TYPE_BYTES_READ:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.getChannel((byte) 2).write((BytesRead) msg);
break;
default:
data.write(msg);
break;
}
//System.err.println("Audio: " + totalAudio + ", Video: " + totalVideo + ", Diff: " + (totalAudio - totalVideo));
}
}
public void onPipeConnectionEvent(PipeConnectionEvent event) {
// TODO close channels on pipe disconnect
}
public void onOOBControlMessage(IMessageComponent source, IPipe pipe, OOBControlMessage oobCtrlMsg) {
if (!"ConnectionConsumer".equals(oobCtrlMsg.getTarget()))
return;
if ("pendingCount".equals(oobCtrlMsg.getServiceName())) {
oobCtrlMsg.setResult(conn.getPendingMessages());
} else if ("streamSend".equals(oobCtrlMsg.getServiceName())) {
IServiceCall call = null;
if (oobCtrlMsg.getServiceParamMap() != null)
call = (IServiceCall) oobCtrlMsg.getServiceParamMap().get("call");
if (call != null)
// Call method on the stream
conn.notify(call, data.getId());
} else if ("pendingVideoCount".equals(oobCtrlMsg.getServiceName())) {
IClientStream stream = conn.getStreamByChannelId(video.getId());
oobCtrlMsg.setResult(conn.getPendingVideoMessages(stream.getStreamId()));
} else if ("chunkSize".equals(oobCtrlMsg.getServiceName())) {
int newSize = (Integer) oobCtrlMsg.getServiceParamMap().get("chunkSize");
if (newSize != chunkSize) {
chunkSize = newSize;
ChunkSize chunkSizeMsg = new ChunkSize(chunkSize);
conn.getChannel((byte) 2).write(chunkSizeMsg);
}
}
}
}
| false | true | public void pushMessage(IPipe pipe, IMessage message) {
if (message instanceof StatusMessage) {
StatusMessage statusMsg = (StatusMessage) message;
data.sendStatus(statusMsg.getBody());
}
else if (message instanceof RTMPMessage) {
RTMPMessage rtmpMsg = (RTMPMessage) message;
IRTMPEvent msg = rtmpMsg.getBody();
if (msg.getHeader() == null) {
msg.setHeader(new Header());
}
msg.getHeader().setTimerRelative(rtmpMsg.isTimerRelative());
// log.debug("ts :" + msg.getTimestamp());
switch(msg.getDataType()){
case Constants.TYPE_STREAM_METADATA:
Notify notify = new Notify(((Notify) msg).getData().asReadOnlyBuffer());
notify.setHeader(msg.getHeader());
notify.setTimestamp(msg.getTimestamp());
video.write(notify);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_VIDEO_DATA:
VideoData videoData = new VideoData(((VideoData) msg).getData().asReadOnlyBuffer());
videoData.setHeader(msg.getHeader());
if (audioTime > 0) {
msg.setTimestamp(msg.getTimestamp() + audioTime);
if (msg.getTimestamp() < 0)
msg.setTimestamp(0);
videoData.getHeader().setTimer(msg.getTimestamp());
audioTime = 0;
}
videoData.setTimestamp(msg.getTimestamp());
videoReceived = true;
video.write(videoData);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_AUDIO_DATA:
AudioData audioData = new AudioData(((AudioData) msg).getData().asReadOnlyBuffer());
audioData.setHeader(msg.getHeader());
audioData.setTimestamp(msg.getTimestamp());
// Low-tech audio lag fix
if (index > 0 && index % 5 != 0 && msg.getTimestamp() > 0) {
audioData.setTimestamp(msg.getTimestamp() - 1);
msg.getHeader().setTimer(audioData.getTimestamp());
}
index++;
audio.write(audioData);
if (!videoReceived)
if (msg.getHeader().isTimerRelative())
audioTime += msg.getTimestamp();
else
audioTime = msg.getTimestamp();
if (msg.getHeader().isTimerRelative())
totalAudio += msg.getTimestamp();
else
totalAudio = msg.getTimestamp();
break;
case Constants.TYPE_PING:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.ping((Ping) msg);
break;
case Constants.TYPE_BYTES_READ:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.getChannel((byte) 2).write((BytesRead) msg);
break;
default:
data.write(msg);
break;
}
//System.err.println("Audio: " + totalAudio + ", Video: " + totalVideo + ", Diff: " + (totalAudio - totalVideo));
}
}
| public void pushMessage(IPipe pipe, IMessage message) {
if (message instanceof StatusMessage) {
StatusMessage statusMsg = (StatusMessage) message;
data.sendStatus(statusMsg.getBody());
}
else if (message instanceof RTMPMessage) {
RTMPMessage rtmpMsg = (RTMPMessage) message;
IRTMPEvent msg = rtmpMsg.getBody();
if (msg.getHeader() == null) {
msg.setHeader(new Header());
}
msg.getHeader().setTimerRelative(rtmpMsg.isTimerRelative());
// log.debug("ts :" + msg.getTimestamp());
switch(msg.getDataType()){
case Constants.TYPE_STREAM_METADATA:
Notify notify = new Notify(((Notify) msg).getData().asReadOnlyBuffer());
notify.setHeader(msg.getHeader());
notify.setTimestamp(msg.getTimestamp());
video.write(notify);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_VIDEO_DATA:
VideoData videoData = new VideoData(((VideoData) msg).getData().asReadOnlyBuffer());
videoData.setHeader(msg.getHeader());
if (audioTime > 0) {
msg.setTimestamp(msg.getTimestamp() + audioTime);
if (msg.getTimestamp() < 0)
msg.setTimestamp(0);
videoData.getHeader().setTimer(msg.getTimestamp());
audioTime = 0;
}
videoData.setTimestamp(msg.getTimestamp());
videoReceived = true;
video.write(videoData);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_AUDIO_DATA:
AudioData audioData = new AudioData(((AudioData) msg).getData().asReadOnlyBuffer());
audioData.setHeader(msg.getHeader());
audioData.setTimestamp(msg.getTimestamp());
// Low-tech audio lag fix
// XXX: This can only applied for live streams otherwise audio in VOD streams is delayed
/*
if (index > 0 && index % 5 != 0 && msg.getTimestamp() > 0) {
audioData.setTimestamp(msg.getTimestamp() - 1);
msg.getHeader().setTimer(audioData.getTimestamp());
}
*/
index++;
audio.write(audioData);
if (!videoReceived)
if (msg.getHeader().isTimerRelative())
audioTime += msg.getTimestamp();
else
audioTime = msg.getTimestamp();
if (msg.getHeader().isTimerRelative())
totalAudio += msg.getTimestamp();
else
totalAudio = msg.getTimestamp();
break;
case Constants.TYPE_PING:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.ping((Ping) msg);
break;
case Constants.TYPE_BYTES_READ:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.getChannel((byte) 2).write((BytesRead) msg);
break;
default:
data.write(msg);
break;
}
//System.err.println("Audio: " + totalAudio + ", Video: " + totalVideo + ", Diff: " + (totalAudio - totalVideo));
}
}
|
diff --git a/raven/src/main/java/net/kencochrane/raven/RavenFactory.java b/raven/src/main/java/net/kencochrane/raven/RavenFactory.java
index 3f825254..f28abf24 100644
--- a/raven/src/main/java/net/kencochrane/raven/RavenFactory.java
+++ b/raven/src/main/java/net/kencochrane/raven/RavenFactory.java
@@ -1,104 +1,104 @@
package net.kencochrane.raven;
import com.google.common.collect.Iterables;
import net.kencochrane.raven.dsn.Dsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
/**
* Factory in charge of creating {@link Raven} instances.
* <p>
* The factories register themselves through the {@link ServiceLoader} system.
* </p>
*/
public abstract class RavenFactory {
private static final ServiceLoader<RavenFactory> AUTO_REGISTERED_FACTORIES = ServiceLoader.load(RavenFactory.class);
private static final Set<RavenFactory> MANUALLY_REGISTERED_FACTORIES = new HashSet<RavenFactory>();
private static final Logger logger = LoggerFactory.getLogger(RavenFactory.class);
/**
* Manually adds a RavenFactory to the system.
* <p>
* Usually RavenFactories are automatically detected with the {@link ServiceLoader} system, but some systems
* such as Android do not provide a fully working ServiceLoader.<br />
* If the factory isn't detected automatically, it's possible to add it through this method.
* </p>
*
* @param ravenFactory ravenFactory to support.
*/
public static void registerFactory(RavenFactory ravenFactory) {
MANUALLY_REGISTERED_FACTORIES.add(ravenFactory);
}
private static Iterable<RavenFactory> getRegisteredFactories() {
return Iterables.concat(MANUALLY_REGISTERED_FACTORIES, AUTO_REGISTERED_FACTORIES);
}
/**
* Creates an instance of Raven using the DSN obtain through {@link net.kencochrane.raven.dsn.Dsn#dsnLookup()}.
*
* @return an instance of Raven.
*/
public static Raven ravenInstance() {
return ravenInstance(Dsn.dsnLookup());
}
/**
* Creates an instance of Raven using the provided DSN.
*
* @param dsn Data Source Name of the Sentry server.
* @return an instance of Raven.
*/
public static Raven ravenInstance(String dsn) {
return ravenInstance(new Dsn(dsn));
}
/**
* Creates an instance of Raven using the provided DSN.
*
* @param dsn Data Source Name of the Sentry server.
* @return an instance of Raven.
*/
public static Raven ravenInstance(Dsn dsn) {
return ravenInstance(dsn, null);
}
/**
* Creates an instance of Raven using the provided DSN and the specified factory.
*
* @param dsn Data Source Name of the Sentry server.
* @param ravenFactoryName name of the raven factory to use to generate an instance of Raven.
* @return an instance of Raven.
* @throws IllegalStateException when no instance of Raven has been created.
*/
public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) {
//Loop through registered factories
logger.info("Attempting to find a working Raven factory");
for (RavenFactory ravenFactory : getRegisteredFactories()) {
if (ravenFactoryName != null && !ravenFactoryName.equals(ravenFactory.getClass().getName()))
continue;
logger.debug("Attempting to use '{}' as a Raven factory.", ravenFactory);
- try{
+ try {
return ravenFactory.createRavenInstance(dsn);
- } catch (RuntimeException e){
+ } catch (RuntimeException e) {
logger.warn("The raven factory '{}' couldn't create an instance of Raven.", ravenFactory, e);
}
}
throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'");
}
/**
* Creates an instance of Raven given a DSN.
*
* @param dsn Data Source Name of the Sentry server.
* @return an instance of Raven.
* @throws RuntimeException when an instance couldn't be created.
*/
public abstract Raven createRavenInstance(Dsn dsn);
}
| false | true | public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) {
//Loop through registered factories
logger.info("Attempting to find a working Raven factory");
for (RavenFactory ravenFactory : getRegisteredFactories()) {
if (ravenFactoryName != null && !ravenFactoryName.equals(ravenFactory.getClass().getName()))
continue;
logger.debug("Attempting to use '{}' as a Raven factory.", ravenFactory);
try{
return ravenFactory.createRavenInstance(dsn);
} catch (RuntimeException e){
logger.warn("The raven factory '{}' couldn't create an instance of Raven.", ravenFactory, e);
}
}
throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'");
}
| public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) {
//Loop through registered factories
logger.info("Attempting to find a working Raven factory");
for (RavenFactory ravenFactory : getRegisteredFactories()) {
if (ravenFactoryName != null && !ravenFactoryName.equals(ravenFactory.getClass().getName()))
continue;
logger.debug("Attempting to use '{}' as a Raven factory.", ravenFactory);
try {
return ravenFactory.createRavenInstance(dsn);
} catch (RuntimeException e) {
logger.warn("The raven factory '{}' couldn't create an instance of Raven.", ravenFactory, e);
}
}
throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'");
}
|
diff --git a/src/d2rq/generate_mapping.java b/src/d2rq/generate_mapping.java
index 83f0835..8bb52a1 100644
--- a/src/d2rq/generate_mapping.java
+++ b/src/d2rq/generate_mapping.java
@@ -1,115 +1,117 @@
package d2rq;
import java.io.*;
import com.hp.hpl.jena.rdf.model.Model;
import jena.cmdline.ArgDecl;
import jena.cmdline.CommandLine;
import de.fuberlin.wiwiss.d2rq.map.Database;
import de.fuberlin.wiwiss.d2rq.mapgen.MappingGenerator;
/**
* Command line interface for {@link MappingGenerator}.
*
* @author Richard Cyganiak ([email protected])
* @version $Id: generate_mapping.java,v 1.5 2010/01/26 13:28:18 fatorange Exp $
*/
public class generate_mapping {
private final static String[] includedDrivers = {
"com.mysql.jdbc.Driver"
};
private final static String DEFAULT_BASE_URI = "http://localhost:2020/";
public static void main(String[] args) {
for (int i = 0; i < includedDrivers.length; i++) {
Database.registerJDBCDriverIfPresent(includedDrivers[i]);
}
CommandLine cmd = new CommandLine();
ArgDecl userArg = new ArgDecl(true, "u", "user", "username");
ArgDecl passArg = new ArgDecl(true, "p", "pass", "password");
ArgDecl schemaArg = new ArgDecl(true, "s", "schema");
ArgDecl driverArg = new ArgDecl(true, "d", "driver");
ArgDecl vocabModelFileArg = new ArgDecl(true, "v", "vocabfile");
ArgDecl outfileArg = new ArgDecl(true, "o", "out", "outfile");
ArgDecl baseUriArg = new ArgDecl(true, "b", "base", "baseuri");
cmd.add(userArg);
cmd.add(passArg);
cmd.add(schemaArg);
cmd.add(driverArg);
cmd.add(vocabModelFileArg);
cmd.add(outfileArg);
cmd.add(baseUriArg);
cmd.process(args);
if (cmd.numItems() == 0) {
usage();
System.exit(1);
}
if (cmd.numItems() > 1) {
System.err.println("too many arguments");
usage();
System.exit(1);
}
String jdbc = cmd.getItem(0);
MappingGenerator gen = new MappingGenerator(jdbc);
if (cmd.contains(userArg)) {
gen.setDatabaseUser(cmd.getArg(userArg).getValue());
}
if (cmd.contains(passArg)) {
gen.setDatabasePassword(cmd.getArg(passArg).getValue());
}
if (cmd.contains(schemaArg)) {
gen.setDatabaseSchema(cmd.getArg(schemaArg).getValue());
}
if (cmd.contains(driverArg)) {
gen.setJDBCDriverClass(cmd.getArg(driverArg).getValue());
}
File vocabModelOutfile = null;
if(cmd.contains(vocabModelFileArg)) {
vocabModelOutfile = new File(cmd.getArg(vocabModelFileArg).getValue());
}
File outputFile = null;
+ String mapUriEnding;
if (cmd.contains(outfileArg)) {
outputFile = new File(cmd.getArg(outfileArg).getValue());
- gen.setMapNamespaceURI(outputFile.toURI().toString() + "#");
+ mapUriEnding = outputFile.getName();
} else {
- gen.setMapNamespaceURI("file:///stdout#");
+ mapUriEnding = "stdout";
}
if(vocabModelOutfile != null && outputFile != null) {
System.err.println("either -o or -v are permitted, but not both");
usage();
System.exit(1);
}
gen.setInstanceNamespaceURI("");
String baseURI = cmd.contains(baseUriArg) ? cmd.getArg(baseUriArg).getValue()
: DEFAULT_BASE_URI;
gen.setVocabNamespaceURI(baseURI + "vocab/resource/");
+ gen.setMapNamespaceURI("d2r-mappings/" + mapUriEnding + "#");
try {
if(vocabModelOutfile != null) {
Model model = gen.vocabularyModel(System.err);
OutputStream vocabStream = new FileOutputStream(vocabModelOutfile);
model.write(vocabStream, "N3");
} else {
PrintStream out = (outputFile == null)
? System.out
: new PrintStream(new FileOutputStream(outputFile));
gen.writeMapping(out, System.err);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
}
private static void usage() {
String usageBegin = "generate-mapping [-u username] [-p password] [-s database schema] [-d driverclass] ";
String usageEnd = " [-b base uri] jdbcURL";
String outfileUsage = "usage: " + usageBegin + "[-o outfile.n3]" + usageEnd;
String vocabUsage = " " + usageBegin + "[-v vocabfile.n3]" + usageEnd;
System.err.println(outfileUsage);
System.err.println(vocabUsage);
}
}
| false | true | public static void main(String[] args) {
for (int i = 0; i < includedDrivers.length; i++) {
Database.registerJDBCDriverIfPresent(includedDrivers[i]);
}
CommandLine cmd = new CommandLine();
ArgDecl userArg = new ArgDecl(true, "u", "user", "username");
ArgDecl passArg = new ArgDecl(true, "p", "pass", "password");
ArgDecl schemaArg = new ArgDecl(true, "s", "schema");
ArgDecl driverArg = new ArgDecl(true, "d", "driver");
ArgDecl vocabModelFileArg = new ArgDecl(true, "v", "vocabfile");
ArgDecl outfileArg = new ArgDecl(true, "o", "out", "outfile");
ArgDecl baseUriArg = new ArgDecl(true, "b", "base", "baseuri");
cmd.add(userArg);
cmd.add(passArg);
cmd.add(schemaArg);
cmd.add(driverArg);
cmd.add(vocabModelFileArg);
cmd.add(outfileArg);
cmd.add(baseUriArg);
cmd.process(args);
if (cmd.numItems() == 0) {
usage();
System.exit(1);
}
if (cmd.numItems() > 1) {
System.err.println("too many arguments");
usage();
System.exit(1);
}
String jdbc = cmd.getItem(0);
MappingGenerator gen = new MappingGenerator(jdbc);
if (cmd.contains(userArg)) {
gen.setDatabaseUser(cmd.getArg(userArg).getValue());
}
if (cmd.contains(passArg)) {
gen.setDatabasePassword(cmd.getArg(passArg).getValue());
}
if (cmd.contains(schemaArg)) {
gen.setDatabaseSchema(cmd.getArg(schemaArg).getValue());
}
if (cmd.contains(driverArg)) {
gen.setJDBCDriverClass(cmd.getArg(driverArg).getValue());
}
File vocabModelOutfile = null;
if(cmd.contains(vocabModelFileArg)) {
vocabModelOutfile = new File(cmd.getArg(vocabModelFileArg).getValue());
}
File outputFile = null;
if (cmd.contains(outfileArg)) {
outputFile = new File(cmd.getArg(outfileArg).getValue());
gen.setMapNamespaceURI(outputFile.toURI().toString() + "#");
} else {
gen.setMapNamespaceURI("file:///stdout#");
}
if(vocabModelOutfile != null && outputFile != null) {
System.err.println("either -o or -v are permitted, but not both");
usage();
System.exit(1);
}
gen.setInstanceNamespaceURI("");
String baseURI = cmd.contains(baseUriArg) ? cmd.getArg(baseUriArg).getValue()
: DEFAULT_BASE_URI;
gen.setVocabNamespaceURI(baseURI + "vocab/resource/");
try {
if(vocabModelOutfile != null) {
Model model = gen.vocabularyModel(System.err);
OutputStream vocabStream = new FileOutputStream(vocabModelOutfile);
model.write(vocabStream, "N3");
} else {
PrintStream out = (outputFile == null)
? System.out
: new PrintStream(new FileOutputStream(outputFile));
gen.writeMapping(out, System.err);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
}
| public static void main(String[] args) {
for (int i = 0; i < includedDrivers.length; i++) {
Database.registerJDBCDriverIfPresent(includedDrivers[i]);
}
CommandLine cmd = new CommandLine();
ArgDecl userArg = new ArgDecl(true, "u", "user", "username");
ArgDecl passArg = new ArgDecl(true, "p", "pass", "password");
ArgDecl schemaArg = new ArgDecl(true, "s", "schema");
ArgDecl driverArg = new ArgDecl(true, "d", "driver");
ArgDecl vocabModelFileArg = new ArgDecl(true, "v", "vocabfile");
ArgDecl outfileArg = new ArgDecl(true, "o", "out", "outfile");
ArgDecl baseUriArg = new ArgDecl(true, "b", "base", "baseuri");
cmd.add(userArg);
cmd.add(passArg);
cmd.add(schemaArg);
cmd.add(driverArg);
cmd.add(vocabModelFileArg);
cmd.add(outfileArg);
cmd.add(baseUriArg);
cmd.process(args);
if (cmd.numItems() == 0) {
usage();
System.exit(1);
}
if (cmd.numItems() > 1) {
System.err.println("too many arguments");
usage();
System.exit(1);
}
String jdbc = cmd.getItem(0);
MappingGenerator gen = new MappingGenerator(jdbc);
if (cmd.contains(userArg)) {
gen.setDatabaseUser(cmd.getArg(userArg).getValue());
}
if (cmd.contains(passArg)) {
gen.setDatabasePassword(cmd.getArg(passArg).getValue());
}
if (cmd.contains(schemaArg)) {
gen.setDatabaseSchema(cmd.getArg(schemaArg).getValue());
}
if (cmd.contains(driverArg)) {
gen.setJDBCDriverClass(cmd.getArg(driverArg).getValue());
}
File vocabModelOutfile = null;
if(cmd.contains(vocabModelFileArg)) {
vocabModelOutfile = new File(cmd.getArg(vocabModelFileArg).getValue());
}
File outputFile = null;
String mapUriEnding;
if (cmd.contains(outfileArg)) {
outputFile = new File(cmd.getArg(outfileArg).getValue());
mapUriEnding = outputFile.getName();
} else {
mapUriEnding = "stdout";
}
if(vocabModelOutfile != null && outputFile != null) {
System.err.println("either -o or -v are permitted, but not both");
usage();
System.exit(1);
}
gen.setInstanceNamespaceURI("");
String baseURI = cmd.contains(baseUriArg) ? cmd.getArg(baseUriArg).getValue()
: DEFAULT_BASE_URI;
gen.setVocabNamespaceURI(baseURI + "vocab/resource/");
gen.setMapNamespaceURI("d2r-mappings/" + mapUriEnding + "#");
try {
if(vocabModelOutfile != null) {
Model model = gen.vocabularyModel(System.err);
OutputStream vocabStream = new FileOutputStream(vocabModelOutfile);
model.write(vocabStream, "N3");
} else {
PrintStream out = (outputFile == null)
? System.out
: new PrintStream(new FileOutputStream(outputFile));
gen.writeMapping(out, System.err);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
}
|
diff --git a/jsf-api/src/main/java/javax/faces/component/UIData.java b/jsf-api/src/main/java/javax/faces/component/UIData.java
index 8ffce66ff..dc16efb33 100644
--- a/jsf-api/src/main/java/javax/faces/component/UIData.java
+++ b/jsf-api/src/main/java/javax/faces/component/UIData.java
@@ -1,1877 +1,1877 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package javax.faces.component;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitHint;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.FacesEvent;
import javax.faces.event.FacesListener;
import javax.faces.event.PhaseId;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.ResultDataModel;
import javax.faces.model.ResultSetDataModel;
import javax.faces.model.ScalarDataModel;
import javax.servlet.jsp.jstl.sql.Result;
import java.io.IOException;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
// ------------------------------------------------------------- Private Classes
// Private class to represent saved state information
/**
* <p><strong>UIData</strong> is a {@link UIComponent} that supports data
* binding to a collection of data objects represented by a {@link DataModel}
* instance, which is the current value of this component itself (typically
* established via a {@link ValueExpression}). During iterative processing over
* the rows of data in the data model, the object for the current row is exposed
* as a request attribute under the key specified by the <code>var</code>
* property.</p>
* <p/>
* <p>Only children of type {@link UIColumn} should be processed by renderers
* associated with this component.</p>
* <p/>
* <p>By default, the <code>rendererType</code> property is set to
* <code>javax.faces.Table</code>. This value can be changed by calling the
* <code>setRendererType()</code> method.</p>
*/
public class UIData extends UIComponentBase
implements NamingContainer, UniqueIdVendor {
// ------------------------------------------------------ Manifest Constants
/**
* <p>The standard component type for this component.</p>
*/
public static final String COMPONENT_TYPE = "javax.faces.Data";
/**
* <p>The standard component family for this component.</p>
*/
public static final String COMPONENT_FAMILY = "javax.faces.Data";
// ------------------------------------------------------------ Constructors
/**
* <p>Create a new {@link UIData} instance with default property
* values.</p>
*/
public UIData() {
super();
setRendererType("javax.faces.Table");
}
// ------------------------------------------------------ Instance Variables
/**
* Properties that are tracked by state saving.
*/
enum PropertyKeys {
/**
* <p>The first row number (zero-relative) to be displayed.</p>
*/
first,
/**
* <p>The zero-relative index of the current row number, or -1 for no
* current row association.</p>
*/
rowIndex,
/**
* <p>The number of rows to display, or zero for all remaining rows in the
* table.</p>
*/
rows,
/**
* <p>This map contains <code>SavedState</code> instances for each
* descendant component, keyed by the client identifier of the descendant.
* Because descendant client identifiers will contain the
* <code>rowIndex</code> value of the parent, per-row state information is
* actually preserved.</p>
*/
saved,
/**
* <p>The local value of this {@link UIComponent}.</p>
*/
value,
/**
* <p>The request scope attribute under which the data object for the
* current row will be exposed when iterating.</p>
*/
var,
/**
* <p>Last id vended by {@link UIData#createUniqueId(javax.faces.context.FacesContext, String)}.</p>
*/
lastId
}
/**
* <p>The {@link DataModel} associated with this component, lazily
* instantiated if requested. This object is not part of the saved and
* restored state of the component.</p>
*/
private DataModel model = null;
/**
* <p> During iteration through the rows of this table, This ivar is used to
* store the previous "var" value for this instance. When the row iteration
* is complete, this value is restored to the request map.
*/
private Object oldVar;
/**
* <p>Holds the base client ID that will be used to generate per-row
* client IDs (this will be null if this UIData is nested within another).</p>
*
* <p>This is not part of the component state.</p>
*/
private String baseClientId = null;
/**
* <p> Length of the cached <code>baseClientId</code> plus one for
* the {@link UINamingContainer#getSeparatorChar}. </p>
*
* <p>This is not part of the component state.</p>
*/
private int baseClientIdLength;
/**
* <p>StringBuilder used to build per-row client IDs.</p>
*
* <p>This is not part of the component state.</p>
*/
private StringBuilder clientIdBuilder = null;
/**
* <p>Flag indicating whether or not this UIData instance is nested
* within another UIData instance</p>
*
* <p>This is not part of the component state.</p>
*/
private Boolean isNested = null;
// -------------------------------------------------------------- Properties
public String getFamily() {
return (COMPONENT_FAMILY);
}
/**
* <p>Return the zero-relative row number of the first row to be
* displayed.</p>
*/
public int getFirst() {
return (Integer) getStateHelper().eval(PropertyKeys.first, 0);
}
/**
* <p>Set the zero-relative row number of the first row to be
* displayed.</p>
*
* @param first New first row number
*
* @throws IllegalArgumentException if <code>first</code> is negative
*/
public void setFirst(int first) {
if (first < 0) {
throw new IllegalArgumentException(String.valueOf(first));
}
getStateHelper().put(PropertyKeys.first, first);
}
/**
* <p>Return the footer facet of this component (if any). A convenience
* method for <code>getFacet("footer")</code>.</p>
*/
public UIComponent getFooter() {
return getFacet("footer");
}
/**
* <p>Set the footer facet of this component. A convenience method for
* <code>getFacets().put("footer", footer)</code>.</p>
*
* @param footer the new footer facet
*
* @throws NullPointerException if <code>footer</code> is <code>null</code>
*/
public void setFooter(UIComponent footer) {
getFacets().put("footer", footer);
}
/**
* <p>Return the header facet of this component (if any). A convenience
* method for <code>getFacet("header")</code>.</p>
*/
public UIComponent getHeader() {
return getFacet("header");
}
/**
* <p>Set the header facet of this component. A convenience method for
* <code>getFacets().put("header", header)</code>.</p>
*
* @param header the new header facet
*
* @throws NullPointerException if <code>header</code> is <code>null</code>
*/
public void setHeader(UIComponent header) {
getFacets().put("header", header);
}
/**
* <p>Return a flag indicating whether there is <code>rowData</code>
* available at the current <code>rowIndex</code>. If no
* <code>wrappedData</code> is available, return <code>false</code>.</p>
*
* @throws FacesException if an error occurs getting the row availability
*/
public boolean isRowAvailable() {
return (getDataModel().isRowAvailable());
}
/**
* <p>Return the number of rows in the underlying data model. If the number
* of available rows is unknown, return -1.</p>
*
* @throws FacesException if an error occurs getting the row count
*/
public int getRowCount() {
return (getDataModel().getRowCount());
}
/**
* <p>Return the data object representing the data for the currently
* selected row index, if any.</p>
*
* @throws FacesException if an error occurs getting the row data
* @throws IllegalArgumentException if now row data is available at the
* currently specified row index
*/
public Object getRowData() {
return (getDataModel().getRowData());
}
/**
* <p>Return the zero-relative index of the currently selected row. If we
* are not currently positioned on a row, return -1. This property is
* <strong>not</strong> enabled for value binding expressions.</p>
*
* @throws FacesException if an error occurs getting the row index
*/
public int getRowIndex() {
return (Integer) getStateHelper().eval(PropertyKeys.rowIndex, -1);
}
/**
* <p>Set the zero relative index of the current row, or -1 to indicate that
* no row is currently selected, by implementing the following algorithm.
* It is possible to set the row index at a value for which the underlying
* data collection does not contain any row data. Therefore, callers may
* use the <code>isRowAvailable()</code> method to detect whether row data
* will be available for use by the <code>getRowData()</code> method.</p>
*</p>
* <ul>
* <li>Save current state information for all descendant components (as
* described below).
* <li>Store the new row index, and pass it on to the {@link DataModel}
* associated with this {@link UIData} instance.</li>
* <li>If the new <code>rowIndex</code> value is -1:
* <ul>
* <li>If the <code>var</code> property is not null,
* remove the corresponding request scope attribute (if any).</li>
* <li>Reset the state information for all descendant components
* (as described below).</li>
* </ul></li>
* <li>If the new <code>rowIndex</code> value is not -1:
* <ul>
* <li>If the <code>var</code> property is not null, call
* <code>getRowData()</code> and expose the resulting data object
* as a request scope attribute whose key is the <code>var</code>
* property value.</li>
* <li>Reset the state information for all descendant components
* (as described below).
* </ul></li>
* </ul>
*
* <p>To save current state information for all descendant components,
* {@link UIData} must maintain per-row information for each descendant
* as follows:<p>
* <ul>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>, save
* the state of its <code>localValue</code> property.</li>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>,
* save the state of the <code>localValueSet</code> property.</li>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>, save
* the state of the <code>valid</code> property.</li>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>,
* save the state of the <code>submittedValue</code> property.</li>
* </ul>
*
* <p>To restore current state information for all descendant components,
* {@link UIData} must reference its previously stored information for the
* current <code>rowIndex</code> and call setters for each descendant
* as follows:</p>
* <ul>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>,
* restore the <code>value</code> property.</li>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>,
* restore the state of the <code>localValueSet</code> property.</li>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>,
* restore the state of the <code>valid</code> property.</li>
* <li>If the descendant is an instance of <code>EditableValueHolder</code>,
* restore the state of the <code>submittedValue</code> property.</li>
* </ul>
*
* @param rowIndex The new row index value, or -1 for no associated row
*
* @throws FacesException if an error occurs setting the row index
* @throws IllegalArgumentException if <code>rowIndex</code>
* is less than -1
*/
public void setRowIndex(int rowIndex) {
// Save current state for the previous row index
saveDescendantState();
// Update to the new row index
//this.rowIndex = rowIndex;
getStateHelper().put(PropertyKeys.rowIndex, rowIndex);
DataModel localModel = getDataModel();
localModel.setRowIndex(rowIndex);
// if rowIndex is -1, clear the cache
if (rowIndex == -1) {
setDataModel(null);
}
// Clear or expose the current row data as a request scope attribute
String var = (String) getStateHelper().get(PropertyKeys.var);
if (var != null) {
Map<String, Object> requestMap =
getFacesContext().getExternalContext().getRequestMap();
if (rowIndex == -1) {
oldVar = requestMap.remove(var);
} else if (isRowAvailable()) {
requestMap.put(var, getRowData());
} else {
requestMap.remove(var);
if (null != oldVar) {
requestMap.put(var, oldVar);
oldVar = null;
}
}
}
// Reset current state information for the new row index
restoreDescendantState();
}
/**
* <p>Return the number of rows to be displayed, or zero for all remaining
* rows in the table. The default value of this property is zero.</p>
*/
public int getRows() {
return (Integer) getStateHelper().eval(PropertyKeys.rows, 0);
}
/**
* <p>Set the number of rows to be displayed, or zero for all remaining rows
* in the table.</p>
*
* @param rows New number of rows
*
* @throws IllegalArgumentException if <code>rows</code> is negative
*/
public void setRows(int rows) {
if (rows < 0) {
throw new IllegalArgumentException(String.valueOf(rows));
}
getStateHelper().put(PropertyKeys.rows, rows);
}
/**
* <p>Return the request-scope attribute under which the data object for the
* current row will be exposed when iterating. This property is
* <strong>not</strong> enabled for value binding expressions.</p>
*/
public String getVar() {
return (String) getStateHelper().get(PropertyKeys.var);
}
/**
* <p>Set the request-scope attribute under which the data object for the
* current row wil be exposed when iterating.</p>
*
* @param var The new request-scope attribute name
*/
public void setVar(String var) {
getStateHelper().put(PropertyKeys.var, var);
}
// ----------------------------------------------------- StateHolder Methods
/**
* <p>Return the value of the UIData. This value must either be
* be of type {@link DataModel}, or a type that can be adapted
* into a {@link DataModel}. <code>UIData</code> will automatically
* adapt the following types:</p>
* <ul>
* <li>Arrays</li>
* <li><code>java.util.List</code></li>
* <li><code>java.sql.ResultSet</code></li>
* <li><code>javax.servlet.jsp.jstl.sql.Result</code></li>
* </ul>
* <p>All other types will be adapted using the {@link ScalarDataModel}
* class, which will treat the object as a single row of data.</p>
*/
public Object getValue() {
return getStateHelper().eval(PropertyKeys.value);
}
/**
* <p>Set the value of the <code>UIData</code>. This value must either be
* be of type {@link DataModel}, or a type that can be adapted into a {@link
* DataModel}.</p>
*
* @param value the new value
*/
public void setValue(Object value) {
setDataModel(null);
getStateHelper().put(PropertyKeys.value, value);
}
// ----------------------------------------------------- UIComponent Methods
/**
* <p>If "name" is something other than "value", "var", or "rowIndex", rely
* on the superclass conversion from <code>ValueBinding</code> to
* <code>ValueExpression</code>.</p>
*
* @param name Name of the attribute or property for which to set a
* {@link ValueBinding}
* @param binding The {@link ValueBinding} to set, or <code>null</code> to
* remove any currently set {@link ValueBinding}
*
* @throws IllegalArgumentException if <code>name</code> is one of
* <code>id</code>, <code>parent</code>,
* <code>var</code>, or <code>rowIndex</code>
* @throws NullPointerException if <code>name</code> is <code>null</code>
* @deprecated This has been replaced by {@link #setValueExpression(java.lang.String,
*javax.el.ValueExpression)}.
*/
public void setValueBinding(String name, ValueBinding binding) {
if ("value".equals(name)) {
setDataModel(null);
} else if ("var".equals(name) || "rowIndex".equals(name)) {
throw new IllegalArgumentException();
}
super.setValueBinding(name, binding);
}
/**
* <p>Set the {@link ValueExpression} used to calculate the value for the
* specified attribute or property name, if any. In addition, if a {@link
* ValueExpression} is set for the <code>value</code> property, remove any
* synthesized {@link DataModel} for the data previously bound to this
* component.</p>
*
* @param name Name of the attribute or property for which to set a
* {@link ValueExpression}
* @param binding The {@link ValueExpression} to set, or <code>null</code>
* to remove any currently set {@link ValueExpression}
*
* @throws IllegalArgumentException if <code>name</code> is one of
* <code>id</code>, <code>parent</code>,
* <code>var</code>, or <code>rowIndex</code>
* @throws NullPointerException if <code>name</code> is <code>null</code>
* @since 1.2
*/
public void setValueExpression(String name, ValueExpression binding) {
if ("value".equals(name)) {
this.model = null;
} else if ("var".equals(name) || "rowIndex".equals(name)) {
throw new IllegalArgumentException();
}
super.setValueExpression(name, binding);
}
/**
* <p>Return a client identifier for this component that includes the
* current value of the <code>rowIndex</code> property, if it is not set to
* -1. This implies that multiple calls to <code>getClientId()</code> may
* return different results, but ensures that child components can
* themselves generate row-specific client identifiers (since {@link UIData}
* is a {@link NamingContainer}).</p>
*
* @throws NullPointerException if <code>context</code> is <code>null</code>
*/
public String getClientId(FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
// If baseClientId and clientIdBuilder are both null, this is the
// first time that getClientId() has been called.
// If we're not nested within another UIData, then:
// - create a new StringBuilder assigned to clientIdBuilder containing
// our client ID.
// - toString() the builder - this result will be our baseClientId
// for the duration of the component
// - append UINamingContainer.getSeparatorChar() to the builder
// If we are nested within another UIData, then:
// - create an empty StringBuilder that will be used to build
// this instance's ID
if (baseClientId == null && clientIdBuilder == null) {
if (!isNestedWithinUIData()) {
clientIdBuilder = new StringBuilder(super.getClientId(context));
baseClientId = clientIdBuilder.toString();
baseClientIdLength = (baseClientId.length() + 1);
clientIdBuilder.append(UINamingContainer.getSeparatorChar(context));
clientIdBuilder.setLength(baseClientIdLength);
} else {
clientIdBuilder = new StringBuilder();
}
}
int rowIndex = getRowIndex();
if (rowIndex >= 0) {
String cid;
if (!isNestedWithinUIData()) {
// we're not nested, so the clientIdBuilder is already
// primed with clientID +
// UINamingContainer.getSeparatorChar(). Append the
// current rowIndex, and toString() the builder. reset
// the builder to it's primed state.
cid = clientIdBuilder.append(rowIndex).toString();
clientIdBuilder.setLength(baseClientIdLength);
} else {
// we're nested, so we have to build the ID from scratch
// each time. Reuse the same clientIdBuilder instance
// for each call by resetting the length to 0 after
// the ID has been computed.
cid = clientIdBuilder.append(super.getClientId(context))
.append(UINamingContainer.getSeparatorChar(context)).append(rowIndex)
.toString();
clientIdBuilder.setLength(0);
}
return (cid);
} else {
if (!isNestedWithinUIData()) {
// Not nested and no row available, so just return our baseClientId
return (baseClientId);
} else {
// nested and no row available, return the result of getClientId().
// this is necessary as the client ID will reflect the row that
// this table represents
return super.getClientId(context);
}
}
}
/**
* <p>Override behavior from {@link
* UIComponentBase#invokeOnComponent} to provide special care for
* positioning the data properly before finding the component and
* invoking the callback on it. If the argument
* <code>clientId</code> is equal to <code>this.getClientId()</code>
* simply invoke the <code>contextCallback</code>, passing the
* <code>context</code> argument and <b>this</b> as arguments, and
* return <code>true.</code> If the argument <code>clientId</code>
* is not equal to <code>this.getClientId()</code>, inspect each of
* the facet children of this <code>UIData</code> instance and for
* each one, compare its <code>clientId</code> with the argument
* <code>clientId</code>. If there is a match, invoke the
* <code>contextCallback</code>, passing the <code>context</code>
* argument and <b>this</b> as arguments, and return
* <code>true</code>. Otherwise, attempt to extract a rowIndex from
* the <code>clientId</code>. For example, if the argument
* <code>clientId</code> was <code>form:data:3:customerHeader</code>
* the rowIndex would be <code>3</code>. Let this value be called
* <code>newIndex</code>. The current rowIndex of this instance must
* be saved aside and restored before returning in all cases,
* regardless of the outcome of the search or if any exceptions are
* thrown in the process.</p>
*
* <p>The implementation of this method must never return <code>true</code>
* if setting the rowIndex of this instance to be equal to
* <code>newIndex</code> causes this instance to return <code>false</code>
* from {@link #isRowAvailable}.</p>
*
* @throws NullPointerException {@inheritDoc}
* @throws FacesException {@inheritDoc} Also throws <code>FacesException</code>
* if any exception is thrown when deriving the
* rowIndex from the argument <code>clientId</code>.
* @since 1.2
*/
public boolean invokeOnComponent(FacesContext context, String clientId,
ContextCallback callback)
throws FacesException {
if (null == context || null == clientId || null == callback) {
throw new NullPointerException();
}
String myId = super.getClientId(context);
boolean found = false;
if (clientId.equals(myId)) {
try {
callback.invokeContextCallback(context, this);
return true;
}
catch (Exception e) {
throw new FacesException(e);
}
}
// check the facets, if any, of UIData
if (this.getFacetCount() > 0) {
for (UIComponent c : this.getFacets().values()) {
c.invokeOnComponent(context, clientId, callback);
}
}
// check column level facets, if any
if (this.getChildCount() > 0) {
for (UIComponent column : this.getChildren()) {
- if (column instanceof UIComponent) {
+ if (column instanceof UIColumn) {
if (column.getFacetCount() > 0) {
for (UIComponent facet : column.getFacets().values()) {
facet.invokeOnComponent(context, clientId, callback);
}
}
}
}
}
int lastSep, newRow, savedRowIndex = this.getRowIndex();
try {
char sepChar = UINamingContainer.getSeparatorChar(context);
// If we need to strip out the rowIndex from our id
// PENDING(edburns): is this safe with respect to I18N?
if (myId.endsWith(sepChar + Integer.toString(savedRowIndex, 10))) {
lastSep = myId.lastIndexOf(sepChar);
assert (-1 != lastSep);
myId = myId.substring(0, lastSep);
}
// myId will be something like form:outerData for a non-nested table,
// and form:outerData:3:data for a nested table.
// clientId will be something like form:outerData:3:outerColumn
// for a non-nested table. clientId will be something like
// outerData:3:data:3:input for a nested table.
if (clientId.startsWith(myId)) {
int preRowIndexSep, postRowIndexSep;
if (-1 != (preRowIndexSep =
clientId.indexOf(sepChar,
myId.length()))) {
// Check the length
if (++preRowIndexSep < clientId.length()) {
if (-1 != (postRowIndexSep =
clientId.indexOf(sepChar,
preRowIndexSep + 1))) {
try {
newRow = Integer
.valueOf(clientId.substring(preRowIndexSep,
postRowIndexSep))
.intValue();
} catch (NumberFormatException ex) {
// PENDING(edburns): I18N
String message =
"Trying to extract rowIndex from clientId \'"
+
clientId
+ "\' "
+ ex.getMessage();
throw new NumberFormatException(message);
}
this.setRowIndex(newRow);
if (this.isRowAvailable()) {
found = super.invokeOnComponent(context,
clientId,
callback);
}
}
}
}
}
}
catch (FacesException fe) {
throw fe;
}
catch (Exception e) {
throw new FacesException(e);
}
finally {
this.setRowIndex(savedRowIndex);
}
return found;
}
/**
* <p>Override the default {@link UIComponentBase#queueEvent} processing to
* wrap any queued events in a wrapper so that we can reset the current row
* index in <code>broadcast()</code>.</p>
*
* @param event {@link FacesEvent} to be queued
*
* @throws IllegalStateException if this component is not a descendant of a
* {@link UIViewRoot}
* @throws NullPointerException if <code>event</code> is <code>null</code>
*/
public void queueEvent(FacesEvent event) {
super.queueEvent(new WrapperEvent(this, event, getRowIndex()));
}
/**
* <p>Override the default {@link UIComponentBase#broadcast} processing to
* unwrap any wrapped {@link FacesEvent} and reset the current row index,
* before the event is actually broadcast. For events that we did not wrap
* (in <code>queueEvent()</code>), default processing will occur.</p>
*
* @param event The {@link FacesEvent} to be broadcast
*
* @throws AbortProcessingException Signal the JavaServer Faces
* implementation that no further
* processing on the current event should
* be performed
* @throws IllegalArgumentException if the implementation class of this
* {@link FacesEvent} is not supported by
* this component
* @throws NullPointerException if <code>event</code> is <code>null</code>
*/
public void broadcast(FacesEvent event)
throws AbortProcessingException {
if (!(event instanceof WrapperEvent)) {
super.broadcast(event);
return;
}
FacesContext context = FacesContext.getCurrentInstance();
// Set up the correct context and fire our wrapped event
WrapperEvent revent = (WrapperEvent) event;
if (isNestedWithinUIData()) {
setDataModel(null);
}
int oldRowIndex = getRowIndex();
setRowIndex(revent.getRowIndex());
FacesEvent rowEvent = revent.getFacesEvent();
UIComponent source = rowEvent.getComponent();
UIComponent compositeParent = null;
try {
if (!UIComponent.isCompositeComponent(source)) {
compositeParent = UIComponent.getCompositeComponentParent(source);
}
if (compositeParent != null) {
compositeParent.pushComponentToEL(context, null);
}
source.pushComponentToEL(context, null);
source.broadcast(rowEvent);
} finally {
source.popComponentFromEL(context);
if (compositeParent != null) {
compositeParent.popComponentFromEL(context);
}
}
setRowIndex(oldRowIndex);
}
/**
* <p>In addition to the default behavior, ensure that any saved per-row
* state for our child input components is discarded unless it is needed to
* rerender the current page with errors.
*
* @param context FacesContext for the current request
*
* @throws IOException if an input/output error occurs while
* rendering
* @throws NullPointerException if <code>context</code> is <code>null</code>
*/
public void encodeBegin(FacesContext context) throws IOException {
preEncode(context);
super.encodeBegin(context);
}
/**
* <p>Override the default {@link UIComponentBase#processDecodes} processing
* to perform the following steps.</p> <ul> <li>If the <code>rendered</code>
* property of this {@link UIComponent} is <code>false</code>, skip further
* processing.</li> <li>Set the current <code>rowIndex</code> to -1.</li>
* <li>Call the <code>processDecodes()</code> method of all facets of this
* {@link UIData}, in the order determined by a call to
* <code>getFacets().keySet().iterator()</code>.</li> <li>Call the
* <code>processDecodes()</code> method of all facets of the {@link
* UIColumn} children of this {@link UIData}.</li> <li>Iterate over the set
* of rows that were included when this component was rendered (i.e. those
* defined by the <code>first</code> and <code>rows</code> properties),
* performing the following processing for each row: <ul> <li>Set the
* current <code>rowIndex</code> to the appropriate value for this row.</li>
* <li>If <code>isRowAvailable()</code> returns <code>true</code>, iterate
* over the children components of each {@link UIColumn} child of this
* {@link UIData} component, calling the <code>processDecodes()</code>
* method for each such child.</li> </ul></li> <li>Set the current
* <code>rowIndex</code> to -1.</li> <li>Call the <code>decode()</code>
* method of this component.</li> <li>If a <code>RuntimeException</code> is
* thrown during decode processing, call {@link FacesContext#renderResponse}
* and re-throw the exception.</li> </ul>
*
* @param context {@link FacesContext} for the current request
*
* @throws NullPointerException if <code>context</code> is <code>null</code>
*/
public void processDecodes(FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
if (!isRendered()) {
return;
}
preDecode(context);
iterate(context, PhaseId.APPLY_REQUEST_VALUES);
decode(context);
}
/**
* <p>Override the default {@link UIComponentBase#processValidators}
* processing to perform the following steps.</p> <ul> <li>If the
* <code>rendered</code> property of this {@link UIComponent} is
* <code>false</code>, skip further processing.</li> <li>Set the current
* <code>rowIndex</code> to -1.</li> <li>Call the <code>processValidators()</code>
* method of all facets of this {@link UIData}, in the order determined by a
* call to <code>getFacets().keySet().iterator()</code>.</li> <li>Call the
* <code>processValidators()</code> method of all facets of the {@link
* UIColumn} children of this {@link UIData}.</li> <li>Iterate over the set
* of rows that were included when this component was rendered (i.e. those
* defined by the <code>first</code> and <code>rows</code> properties),
* performing the following processing for each row: <ul> <li>Set the
* current <code>rowIndex</code> to the appropriate value for this row.</li>
* <li>If <code>isRowAvailable()</code> returns <code>true</code>, iterate
* over the children components of each {@link UIColumn} child of this
* {@link UIData} component, calling the <code>processValidators()</code>
* method for each such child.</li> </ul></li> <li>Set the current
* <code>rowIndex</code> to -1.</li> </ul>
*
* @param context {@link FacesContext} for the current request
*
* @throws NullPointerException if <code>context</code> is <code>null</code>
*/
public void processValidators(FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
if (!isRendered()) {
return;
}
preValidate(context);
iterate(context, PhaseId.PROCESS_VALIDATIONS);
// This is not a EditableValueHolder, so no further processing is required
}
/**
* <p>Override the default {@link UIComponentBase#processUpdates}
* processing to perform the following steps.</p>
* <ul>
* <li>If the <code>rendered</code> property of this {@link UIComponent}
* is <code>false</code>, skip further processing.</li>
* <li>Set the current <code>rowIndex</code> to -1.</li>
* <li>Call the <code>processUpdates()</code> method of all facets
* of this {@link UIData}, in the order determined
* by a call to <code>getFacets().keySet().iterator()</code>.</li>
* <li>Call the <code>processUpdates()</code> method of all facets
* of the {@link UIColumn} children of this {@link UIData}.</li>
* <li>Iterate over the set of rows that were included when this
* component was rendered (i.e. those defined by the <code>first</code>
* and <code>rows</code> properties), performing the following
* processing for each row:
* <ul>
* <li>Set the current <code>rowIndex</code> to the appropriate
* value for this row.</li>
* <li>If <code>isRowAvailable()</code> returns <code>true</code>,
* iterate over the children components of each {@link UIColumn}
* child of this {@link UIData} component, calling the
* <code>processUpdates()</code> method for each such child.</li>
* </ul></li>
* <li>Set the current <code>rowIndex</code> to -1.</li>
* </ul>
*
* @param context {@link FacesContext} for the current request
*
* @throws NullPointerException if <code>context</code> is <code>null</code>
*/
public void processUpdates(FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
if (!isRendered()) {
return;
}
preUpdate(context);
iterate(context, PhaseId.UPDATE_MODEL_VALUES);
// This is not a EditableValueHolder, so no further processing is required
}
public String createUniqueId(FacesContext context, String seed) {
Integer i = (Integer) getStateHelper().get(PropertyKeys.lastId);
int lastId = ((i != null) ? i : 0);
getStateHelper().put(PropertyKeys.lastId, ++lastId);
return UIViewRoot.UNIQUE_ID_PREFIX + (seed == null ? lastId : seed);
}
/**
* <p class="changed_added_2_0">Override the behavior in {@link
* UIComponent#visitTree} to handle iteration correctly.</p>
*
* <div class="changed_added_2_0">
* <p>If the {@link UIComponent#isVisitable} method of this instance
* returns <code>false</code>, take no action and return.</p>
* <p>Otherwise, save aside the result of a call to {@link
* #getRowIndex}. Call {@link UIComponent#pushComponentToEL} and
* invoke the visit callback on this <code>UIData</code> instance as
* described in {@link UIComponent#visitTree}. Let the result of
* the invoctaion be <em>visitResult</em>. If <em>visitResult</em>
* is {@link VisitResult#COMPLETE}, take no further action and
* return <code>true</code>. Otherwise, determine if we need to
* visit our children. The default implementation calls {@link
* VisitContext#getSubtreeIdsToVisit} passing <code>this</code> as
* the argument. If the result of that call is non-empty, let
* <em>doVisitChildren</em> be <code>true</code>. If
* <em>doVisitChildren</em> is <code>true</code> and
* <em>visitResult</em> is {@link VisitResult#ACCEPT}, take the
* following action.<p>
* <ul>
* <li><p>If this component has facets, call {@link
* UIComponent#getFacets} on this instance and invoke the
* <code>values()</code> method. For each
* <code>UIComponent</code> in the returned <code>Map</code>,
* call {@link UIComponent#visitTree}.</p></li>
* <li><p>If this component has children, for each child
* <code>UIComponent</code> retured from calling {@link
* #getChildren} on this instance, if the child has facets, call
* {@link UIComponent#getFacets} on the child instance and invoke
* the <code>values()</code> method. For each
* <code>UIComponent</code> in the returned <code>Map</code>,
* call {@link UIComponent#visitTree}.</p></li>
* <li><p>Iterate over the columns and rows.</p>
* <ul>
* <li><p>Let <em>rowsToProcess</em> be the return from {@link
* #getRows}. </p></li>
* <li><p>Let <em>rowIndex</em> be the return from {@link
* #getFirst} - 1.</p></li>
* <li><p>While the number of rows processed is less than
* <em>rowsToProcess</em>, take the following actions.</p>
* <p>Call {@link #setRowIndex}, passing the current row index.</p>
* <p>If {@link #isRowAvailable} returns <code>false</code>, take no
* further action and return <code>false</code>.</p>
* <p>For each child component of this <code>UIData</code> that is
* also an instance of {@link UIColumn}, call {@link
* UIComponent#visitTree} on the child. If such a call returns
* <code>true</code>, terminate iteration and return
* <code>true</code>. Take no action on non <code>UIColumn</code>
* children.</p>
* </li>
* </ul>
* </li>
* </ul>
* <p>Call {@link #popComponentFromEL} and restore the saved row
* index with a call to {@link #setRowIndex}.</p>
* <p>Return <code>false</code> to allow the visiting to
* continue.</p>
* </div>
*
* @param context the <code>VisitContext</code> that provides
* context for performing the visit.
*
* @param callback the callback to be invoked for each node
* encountered in the visit.
* @throws NullPointerException if any of the parameters are
* <code>null</code>.
*
*/
@Override
public boolean visitTree(VisitContext context,
VisitCallback callback) {
// First check to see whether we are visitable. If not
// short-circuit out of this subtree, though allow the
// visit to proceed through to other subtrees.
if (!isVisitable(context))
return false;
// Clear out the row index is one is set so that
// we start from a clean slate.
int oldRowIndex = getRowIndex();
setRowIndex(-1);
// Push ourselves to EL
FacesContext facesContext = context.getFacesContext();
pushComponentToEL(facesContext, null);
try {
// Visit ourselves. Note that we delegate to the
// VisitContext to actually perform the visit.
VisitResult result = context.invokeVisitCallback(this, callback);
// If the visit is complete, short-circuit out and end the visit
if (result == VisitResult.COMPLETE)
return true;
// Visit children, short-circuiting as necessary
if ((result == VisitResult.ACCEPT) && doVisitChildren(context)) {
// First visit facets
if (visitFacets(context, callback))
return true;
// Next column facets
if (visitColumnFacets(context, callback))
return true;
// And finally, visit rows
if (visitColumnsAndRows(context, callback))
return true;
}
}
finally {
// Clean up - pop EL and restore old row index
popComponentFromEL(facesContext);
setRowIndex(oldRowIndex);
}
// Return false to allow the visit to continue
return false;
}
// --------------------------------------------------------- Protected Methods
/**
* <p>Return the internal {@link DataModel} object representing the data
* objects that we will iterate over in this component's rendering.</p>
* <p/>
* <p>If the model has been cached by a previous call to {@link
* #setDataModel}, return it. Otherwise call {@link #getValue}. If the
* result is null, create an empty {@link ListDataModel} and return it. If
* the result is an instance of {@link DataModel}, return it. Otherwise,
* adapt the result as described in {@link #getValue} and return it.</p>
*/
protected DataModel getDataModel() {
// Return any previously cached DataModel instance
if (this.model != null) {
return (model);
}
// Synthesize a DataModel around our current value if possible
Object current = getValue();
if (current == null) {
setDataModel(new ListDataModel(Collections.EMPTY_LIST));
} else if (current instanceof DataModel) {
setDataModel((DataModel) current);
} else if (current instanceof List) {
setDataModel(new ListDataModel((List) current));
} else if (Object[].class.isAssignableFrom(current.getClass())) {
setDataModel(new ArrayDataModel((Object[]) current));
} else if (current instanceof ResultSet) {
setDataModel(new ResultSetDataModel((ResultSet) current));
} else if (current instanceof Result) {
setDataModel(new ResultDataModel((Result) current));
} else {
setDataModel(new ScalarDataModel(current));
}
return (model);
}
/**
* <p>Set the internal DataModel. This <code>UIData</code> instance must
* use the given {@link DataModel} as its internal value representation from
* now until the next call to <code>setDataModel</code>. If the given
* <code>DataModel</code> is <code>null</code>, the internal
* <code>DataModel</code> must be reset in a manner so that the next call to
* {@link #getDataModel} causes lazy instantion of a newly refreshed
* <code>DataModel</code>.</p>
* <p/>
* <p>Subclasses might call this method if they either want to restore the
* internal <code>DataModel</code> during the <em>Restore View</em> phase or
* if they want to explicitly refresh the current <code>DataModel</code> for
* the <em>Render Response</em> phase.</p>
*
* @param dataModel the new <code>DataModel</code> or <code>null</code> to
* cause the model to be refreshed.
*/
protected void setDataModel(DataModel dataModel) {
this.model = dataModel;
}
// ---------------------------------------------------- Private Methods
// Perform pre-decode initialization work. Note that this
// initialization may be performed either during a normal decode
// (ie. processDecodes()) or during a tree visit (ie. visitTree()).
private void preDecode(FacesContext context) {
setDataModel(null); // Re-evaluate even with server-side state saving
Map<String, SavedState> saved =
(Map<String, SavedState>) getStateHelper().get(PropertyKeys.saved);
if (null == saved || !keepSaved(context)) {
//noinspection CollectionWithoutInitialCapacity
getStateHelper().remove(PropertyKeys.saved);
}
}
// Perform pre-validation initialization work. Note that this
// initialization may be performed either during a normal validation
// (ie. processValidators()) or during a tree visit (ie. visitTree()).
private void preValidate(FacesContext context) {
if (isNestedWithinUIData()) {
setDataModel(null);
}
}
// Perform pre-update initialization work. Note that this
// initialization may be performed either during normal update
// (ie. processUpdates()) or during a tree visit (ie. visitTree()).
private void preUpdate(FacesContext context) {
if (isNestedWithinUIData()) {
setDataModel(null);
}
}
// Perform pre-encode initialization work. Note that this
// initialization may be performed either during a normal encode
// (ie. encodeBegin()) or during a tree visit (ie. visitTree()).
private void preEncode(FacesContext context) {
setDataModel(null); // re-evaluate even with server-side state saving
if (!keepSaved(context)) {
////noinspection CollectionWithoutInitialCapacity
//saved = new HashMap<String, SavedState>();
getStateHelper().remove(PropertyKeys.saved);
}
}
/**
* <p>Perform the appropriate phase-specific processing and per-row
* iteration for the specified phase, as follows:
* <ul>
* <li>Set the <code>rowIndex</code> property to -1, and process the facets
* of this {@link UIData} component exactly once.</li>
* <li>Set the <code>rowIndex</code> property to -1, and process the facets
* of the {@link UIColumn} children of this {@link UIData} component
* exactly once.</li>
* <li>Iterate over the relevant rows, based on the <code>first</code>
* and <code>row</code> properties, and process the children
* of the {@link UIColumn} children of this {@link UIData} component
* once per row.</li>
* </ul>
*
* @param context {@link FacesContext} for the current request
* @param phaseId {@link PhaseId} of the phase we are currently running
*/
private void iterate(FacesContext context, PhaseId phaseId) {
// Process each facet of this component exactly once
setRowIndex(-1);
if (getFacetCount() > 0) {
for (UIComponent facet : getFacets().values()) {
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
facet.processDecodes(context);
} else if (phaseId == PhaseId.PROCESS_VALIDATIONS) {
facet.processValidators(context);
} else if (phaseId == PhaseId.UPDATE_MODEL_VALUES) {
facet.processUpdates(context);
} else {
throw new IllegalArgumentException();
}
}
}
// Process each facet of our child UIColumn components exactly once
setRowIndex(-1);
if (getChildCount() > 0) {
for (UIComponent column : getChildren()) {
if (!(column instanceof UIColumn) || !column.isRendered()) {
continue;
}
if (column.getFacetCount() > 0) {
for (UIComponent columnFacet : column.getFacets().values()) {
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
columnFacet.processDecodes(context);
} else if (phaseId == PhaseId.PROCESS_VALIDATIONS) {
columnFacet.processValidators(context);
} else if (phaseId == PhaseId.UPDATE_MODEL_VALUES) {
columnFacet.processUpdates(context);
} else {
throw new IllegalArgumentException();
}
}
}
}
}
// Iterate over our UIColumn children, once per row
int processed = 0;
int rowIndex = getFirst() - 1;
int rows = getRows();
while (true) {
// Have we processed the requested number of rows?
if ((rows > 0) && (++processed > rows)) {
break;
}
// Expose the current row in the specified request attribute
setRowIndex(++rowIndex);
if (!isRowAvailable()) {
break; // Scrolled past the last row
}
// Perform phase-specific processing as required
// on the *children* of the UIColumn (facets have
// been done a single time with rowIndex=-1 already)
if (getChildCount() > 0) {
for (UIComponent kid : getChildren()) {
if (!(kid instanceof UIColumn) || !kid.isRendered()) {
continue;
}
if (kid.getChildCount() > 0) {
for (UIComponent grandkid : kid.getChildren()) {
if (!grandkid.isRendered()) {
continue;
}
if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
grandkid.processDecodes(context);
} else if (phaseId == PhaseId.PROCESS_VALIDATIONS) {
grandkid.processValidators(context);
} else if (phaseId == PhaseId.UPDATE_MODEL_VALUES) {
grandkid.processUpdates(context);
} else {
throw new IllegalArgumentException();
}
}
}
}
}
}
// Clean up after ourselves
setRowIndex(-1);
}
// Tests whether we need to visit our children as part of
// a tree visit
private boolean doVisitChildren(VisitContext context) {
// Just need to check whether there are any ids under this
// subtree. Make sure row index is cleared out since
// getSubtreeIdsToVisit() needs our row-less client id.
setRowIndex(-1);
Collection<String> idsToVisit = context.getSubtreeIdsToVisit(this);
assert(idsToVisit != null);
// All ids or non-empty collection means we need to visit our children.
return (!idsToVisit.isEmpty());
}
// Performs pre-phase initialization before visiting children
// (if necessary).
private void preVisitChildren(VisitContext visitContext) {
// If EXECUTE_LIFECYCLE hint is set, we need to do
// lifecycle-related initialization before visiting children
if (visitContext.getHints().contains(VisitHint.EXECUTE_LIFECYCLE)) {
FacesContext facesContext = visitContext.getFacesContext();
PhaseId phaseId = facesContext.getCurrentPhaseId();
if (phaseId == PhaseId.APPLY_REQUEST_VALUES)
preDecode(facesContext);
else if (phaseId == PhaseId.PROCESS_VALIDATIONS)
preValidate(facesContext);
else if (phaseId == PhaseId.UPDATE_MODEL_VALUES)
preUpdate(facesContext);
else if (phaseId == PhaseId.RENDER_RESPONSE)
preEncode(facesContext);
}
}
// Visit each facet of this component exactly once
private boolean visitFacets(VisitContext context, VisitCallback callback) {
setRowIndex(-1);
if (getFacetCount() > 0) {
for (UIComponent facet : getFacets().values()) {
if (facet.visitTree(context, callback))
return true;
}
}
return false;
}
// Visit each facet of our child UIColumn components exactly once
private boolean visitColumnFacets(VisitContext context,
VisitCallback callback) {
setRowIndex(-1);
if (getChildCount() > 0) {
for (UIComponent column : getChildren()) {
if (column.getFacetCount() > 0) {
for (UIComponent columnFacet : column.getFacets().values()) {
if (columnFacet.visitTree(context, callback))
return true;
}
}
}
}
return false;
}
// Visit each column and row
private boolean visitColumnsAndRows(VisitContext context, VisitCallback callback) {
// first, visit all columns
if (getChildCount() > 0) {
for (UIComponent kid : getChildren()) {
if (!(kid instanceof UIColumn)) {
continue;
}
if (kid.visitTree(context, callback)) {
return true;
}
}
}
// Iterate over our UIColumn children, once per row
int processed = 0;
int rowIndex = getFirst() - 1;
int rows = getRows();
while (true) {
// Have we processed the requested number of rows?
if ((rows > 0) && (++processed > rows)) {
break;
}
// Expose the current row in the specified request attribute
setRowIndex(++rowIndex);
if (!isRowAvailable()) {
break; // Scrolled past the last row
}
// Visit as required on the *children* of the UIColumn
// (facets have been done a single time with rowIndex=-1 already)
if (getChildCount() > 0) {
for (UIComponent kid : getChildren()) {
if (!(kid instanceof UIColumn)) {
continue;
}
if (kid.getChildCount() > 0) {
for (UIComponent grandkid : kid.getChildren()) {
if (grandkid.visitTree(context, callback)) {
return true;
}
}
}
}
}
}
return false;
}
/**
* <p>Return <code>true</code> if we need to keep the saved
* per-child state information. This will be the case if any of the
* following are true:</p>
*
* <ul>
*
* <li>there are messages queued with severity ERROR or FATAL.</li>
*
* <li>this <code>UIData</code> instance is nested inside of another
* <code>UIData</code> instance</li>
*
* </ul>
*
* @param context {@link FacesContext} for the current request
*/
private boolean keepSaved(FacesContext context) {
return (contextHasErrorMessages(context) || isNestedWithinUIData());
}
private Boolean isNestedWithinUIData() {
if (isNested == null) {
UIComponent parent = this;
while (null != (parent = parent.getParent())) {
if (parent instanceof UIData) {
isNested = Boolean.TRUE;
break;
}
}
if (isNested == null) {
isNested = Boolean.FALSE;
}
return isNested;
} else {
return isNested;
}
}
private boolean contextHasErrorMessages(FacesContext context) {
FacesMessage.Severity sev = context.getMaximumSeverity();
return (sev != null && (FacesMessage.SEVERITY_ERROR.compareTo(sev) >= 0));
}
/**
* <p>Restore state information for all descendant components, as described
* for <code>setRowIndex()</code>.</p>
*/
private void restoreDescendantState() {
FacesContext context = getFacesContext();
if (getChildCount() > 0) {
for (UIComponent kid : getChildren()) {
if (kid instanceof UIColumn) {
restoreDescendantState(kid, context);
}
}
}
}
/**
* <p>Restore state information for the specified component and its
* descendants.</p>
*
* @param component Component for which to restore state information
* @param context {@link FacesContext} for the current request
*/
private void restoreDescendantState(UIComponent component,
FacesContext context) {
// Reset the client identifier for this component
String id = component.getId();
component.setId(id); // Forces client id to be reset
Map<String, SavedState> saved = (Map<String,SavedState>)
getStateHelper().get(PropertyKeys.saved);
// Restore state for this component (if it is a EditableValueHolder)
if (component instanceof EditableValueHolder) {
EditableValueHolder input = (EditableValueHolder) component;
String clientId = component.getClientId(context);
SavedState state = saved.get(clientId);
if (state == null) {
state = new SavedState();
}
input.setValue(state.getValue());
input.setValid(state.isValid());
input.setSubmittedValue(state.getSubmittedValue());
// This *must* be set after the call to setValue(), since
// calling setValue() always resets "localValueSet" to true.
input.setLocalValueSet(state.isLocalValueSet());
} else if (component instanceof UIForm) {
UIForm form = (UIForm) component;
String clientId = component.getClientId(context);
SavedState state = saved.get(clientId);
if (state == null) {
state = new SavedState();
}
form.setSubmitted(state.getSubmitted());
state.setSubmitted(form.isSubmitted());
}
// Restore state for children of this component
if (component.getChildCount() > 0) {
for (UIComponent kid : component.getChildren()) {
restoreDescendantState(kid, context);
}
}
// Restore state for facets of this component
if (component.getFacetCount() > 0) {
for (UIComponent facet : component.getFacets().values()) {
restoreDescendantState(facet, context);
}
}
}
/**
* <p>Save state information for all descendant components, as described for
* <code>setRowIndex()</code>.</p>
*/
private void saveDescendantState() {
FacesContext context = getFacesContext();
if (getChildCount() > 0) {
for (UIComponent kid : getChildren()) {
if (kid instanceof UIColumn) {
saveDescendantState(kid, context);
}
}
}
}
/**
* <p>Save state information for the specified component and its
* descendants.</p>
*
* @param component Component for which to save state information
* @param context {@link FacesContext} for the current request
*/
private void saveDescendantState(UIComponent component,
FacesContext context) {
// Save state for this component (if it is a EditableValueHolder)
Map<String, SavedState> saved = (Map<String, SavedState>)
getStateHelper().get(PropertyKeys.saved);
if (component instanceof EditableValueHolder) {
EditableValueHolder input = (EditableValueHolder) component;
SavedState state = null;
String clientId = component.getClientId(context);
if (saved == null) {
state = new SavedState();
getStateHelper().put(PropertyKeys.saved, clientId, state);
}
if (state == null) {
state = saved.get(clientId);
if (state == null) {
state = new SavedState();
//saved.put(clientId, state);
getStateHelper().put(PropertyKeys.saved, clientId, state);
}
}
state.setValue(input.getLocalValue());
state.setValid(input.isValid());
state.setSubmittedValue(input.getSubmittedValue());
state.setLocalValueSet(input.isLocalValueSet());
} else if (component instanceof UIForm) {
UIForm form = (UIForm) component;
String clientId = component.getClientId(context);
SavedState state = null;
if (saved == null) {
state = new SavedState();
getStateHelper().put(PropertyKeys.saved, clientId, state);
}
if (state == null) {
state = saved.get(clientId);
if (state == null) {
state = new SavedState();
//saved.put(clientId, state);
getStateHelper().put(PropertyKeys.saved, clientId, state);
}
}
state.setSubmitted(form.isSubmitted());
}
// Save state for children of this component
if (component.getChildCount() > 0) {
for (UIComponent uiComponent : component.getChildren()) {
saveDescendantState(uiComponent, context);
}
}
// Save state for facets of this component
if (component.getFacetCount() > 0) {
for (UIComponent facet : component.getFacets().values()) {
saveDescendantState(facet, context);
}
}
}
}
@SuppressWarnings({"SerializableHasSerializationMethods",
"NonSerializableFieldInSerializableClass"})
class SavedState implements Serializable {
private static final long serialVersionUID = 2920252657338389849L;
private Object submittedValue;
private boolean submitted;
Object getSubmittedValue() {
return (this.submittedValue);
}
void setSubmittedValue(Object submittedValue) {
this.submittedValue = submittedValue;
}
private boolean valid = true;
boolean isValid() {
return (this.valid);
}
void setValid(boolean valid) {
this.valid = valid;
}
private Object value;
Object getValue() {
return (this.value);
}
public void setValue(Object value) {
this.value = value;
}
private boolean localValueSet;
boolean isLocalValueSet() {
return (this.localValueSet);
}
public void setLocalValueSet(boolean localValueSet) {
this.localValueSet = localValueSet;
}
public boolean getSubmitted() {
return this.submitted;
}
public void setSubmitted(boolean submitted) {
this.submitted = submitted;
}
public String toString() {
return ("submittedValue: " + submittedValue +
" value: " + value +
" localValueSet: " + localValueSet);
}
}
// Private class to wrap an event with a row index
class WrapperEvent extends FacesEvent {
public WrapperEvent(UIComponent component, FacesEvent event, int rowIndex) {
super(component);
this.event = event;
this.rowIndex = rowIndex;
}
private FacesEvent event = null;
private int rowIndex = -1;
public FacesEvent getFacesEvent() {
return (this.event);
}
public int getRowIndex() {
return (this.rowIndex);
}
public PhaseId getPhaseId() {
return (this.event.getPhaseId());
}
public void setPhaseId(PhaseId phaseId) {
this.event.setPhaseId(phaseId);
}
public boolean isAppropriateListener(FacesListener listener) {
return (false);
}
public void processListener(FacesListener listener) {
throw new IllegalStateException();
}
}
| true | true | public boolean invokeOnComponent(FacesContext context, String clientId,
ContextCallback callback)
throws FacesException {
if (null == context || null == clientId || null == callback) {
throw new NullPointerException();
}
String myId = super.getClientId(context);
boolean found = false;
if (clientId.equals(myId)) {
try {
callback.invokeContextCallback(context, this);
return true;
}
catch (Exception e) {
throw new FacesException(e);
}
}
// check the facets, if any, of UIData
if (this.getFacetCount() > 0) {
for (UIComponent c : this.getFacets().values()) {
c.invokeOnComponent(context, clientId, callback);
}
}
// check column level facets, if any
if (this.getChildCount() > 0) {
for (UIComponent column : this.getChildren()) {
if (column instanceof UIComponent) {
if (column.getFacetCount() > 0) {
for (UIComponent facet : column.getFacets().values()) {
facet.invokeOnComponent(context, clientId, callback);
}
}
}
}
}
int lastSep, newRow, savedRowIndex = this.getRowIndex();
try {
char sepChar = UINamingContainer.getSeparatorChar(context);
// If we need to strip out the rowIndex from our id
// PENDING(edburns): is this safe with respect to I18N?
if (myId.endsWith(sepChar + Integer.toString(savedRowIndex, 10))) {
lastSep = myId.lastIndexOf(sepChar);
assert (-1 != lastSep);
myId = myId.substring(0, lastSep);
}
// myId will be something like form:outerData for a non-nested table,
// and form:outerData:3:data for a nested table.
// clientId will be something like form:outerData:3:outerColumn
// for a non-nested table. clientId will be something like
// outerData:3:data:3:input for a nested table.
if (clientId.startsWith(myId)) {
int preRowIndexSep, postRowIndexSep;
if (-1 != (preRowIndexSep =
clientId.indexOf(sepChar,
myId.length()))) {
// Check the length
if (++preRowIndexSep < clientId.length()) {
if (-1 != (postRowIndexSep =
clientId.indexOf(sepChar,
preRowIndexSep + 1))) {
try {
newRow = Integer
.valueOf(clientId.substring(preRowIndexSep,
postRowIndexSep))
.intValue();
} catch (NumberFormatException ex) {
// PENDING(edburns): I18N
String message =
"Trying to extract rowIndex from clientId \'"
+
clientId
+ "\' "
+ ex.getMessage();
throw new NumberFormatException(message);
}
this.setRowIndex(newRow);
if (this.isRowAvailable()) {
found = super.invokeOnComponent(context,
clientId,
callback);
}
}
}
}
}
}
catch (FacesException fe) {
throw fe;
}
catch (Exception e) {
throw new FacesException(e);
}
finally {
this.setRowIndex(savedRowIndex);
}
return found;
}
| public boolean invokeOnComponent(FacesContext context, String clientId,
ContextCallback callback)
throws FacesException {
if (null == context || null == clientId || null == callback) {
throw new NullPointerException();
}
String myId = super.getClientId(context);
boolean found = false;
if (clientId.equals(myId)) {
try {
callback.invokeContextCallback(context, this);
return true;
}
catch (Exception e) {
throw new FacesException(e);
}
}
// check the facets, if any, of UIData
if (this.getFacetCount() > 0) {
for (UIComponent c : this.getFacets().values()) {
c.invokeOnComponent(context, clientId, callback);
}
}
// check column level facets, if any
if (this.getChildCount() > 0) {
for (UIComponent column : this.getChildren()) {
if (column instanceof UIColumn) {
if (column.getFacetCount() > 0) {
for (UIComponent facet : column.getFacets().values()) {
facet.invokeOnComponent(context, clientId, callback);
}
}
}
}
}
int lastSep, newRow, savedRowIndex = this.getRowIndex();
try {
char sepChar = UINamingContainer.getSeparatorChar(context);
// If we need to strip out the rowIndex from our id
// PENDING(edburns): is this safe with respect to I18N?
if (myId.endsWith(sepChar + Integer.toString(savedRowIndex, 10))) {
lastSep = myId.lastIndexOf(sepChar);
assert (-1 != lastSep);
myId = myId.substring(0, lastSep);
}
// myId will be something like form:outerData for a non-nested table,
// and form:outerData:3:data for a nested table.
// clientId will be something like form:outerData:3:outerColumn
// for a non-nested table. clientId will be something like
// outerData:3:data:3:input for a nested table.
if (clientId.startsWith(myId)) {
int preRowIndexSep, postRowIndexSep;
if (-1 != (preRowIndexSep =
clientId.indexOf(sepChar,
myId.length()))) {
// Check the length
if (++preRowIndexSep < clientId.length()) {
if (-1 != (postRowIndexSep =
clientId.indexOf(sepChar,
preRowIndexSep + 1))) {
try {
newRow = Integer
.valueOf(clientId.substring(preRowIndexSep,
postRowIndexSep))
.intValue();
} catch (NumberFormatException ex) {
// PENDING(edburns): I18N
String message =
"Trying to extract rowIndex from clientId \'"
+
clientId
+ "\' "
+ ex.getMessage();
throw new NumberFormatException(message);
}
this.setRowIndex(newRow);
if (this.isRowAvailable()) {
found = super.invokeOnComponent(context,
clientId,
callback);
}
}
}
}
}
}
catch (FacesException fe) {
throw fe;
}
catch (Exception e) {
throw new FacesException(e);
}
finally {
this.setRowIndex(savedRowIndex);
}
return found;
}
|
diff --git a/src/Main.java b/src/Main.java
index f874fab..0f401ae 100644
--- a/src/Main.java
+++ b/src/Main.java
@@ -1,30 +1,30 @@
import edu.uci.ics.jung.graph.*;
import edu.uci.ics.jung.graph.util.*;
class Main{
public static void main(String[] args){
// Graph<V, E> where V is the type of the vertices
// // and E is the type of the edges
Graph<Integer, String> g = new SparseMultigraph<Integer, String>();
// // Add some vertices. From above we defined these to be type Integer.
g.addVertex((Integer)1);
g.addVertex((Integer)2);
g.addVertex((Integer)3);
// // Add some edges. From above we defined these to be of type String
// // Note that the default is for undirected edges.
g.addEdge("Edge-A", 1, 2); // Note that Java 1.5 auto-boxes primitives
g.addEdge("Edge-B", 2, 3);
// // Let's see what we have. Note the nice output from the
// // SparseMultigraph<V,E> toString() method
System.out.println("The graph g = " + g.toString());
// // Note that we can use the same nodes and edges in two different graphs.
- // Graph<Integer, String> g2 = new SparseMultigraph<Integer, String>();
- // g2.addVertex((Integer)1);
- // g2.addVertex((Integer)2);
- // g2.addVertex((Integer)3);
- // g2.addEdge("Edge-A", 1,3);
- // g2.addEdge("Edge-B", 2,3, EdgeType.DIRECTED);
- // g2.addEdge("Edge-C", 3, 2, EdgeType.DIRECTED);
- // g2.addEdge("Edge-P", 2,3); // A parallel edge
- // System.out.println("The graph g2 = " + g2.toString());
+ Graph<Integer, String> g2 = new SparseMultigraph<Integer, String>();
+ g2.addVertex((Integer)1);
+ g2.addVertex((Integer)2);
+ g2.addVertex((Integer)3);
+ g2.addEdge("Edge-A", 1,3);
+ g2.addEdge("Edge-B", 2,3, EdgeType.DIRECTED);
+ g2.addEdge("Edge-C", 3, 2, EdgeType.DIRECTED);
+ g2.addEdge("Edge-P", 2,3); // A parallel edge
+ System.out.println("The graph g2 = " + g2.toString());
}
}
| true | true | public static void main(String[] args){
// Graph<V, E> where V is the type of the vertices
// // and E is the type of the edges
Graph<Integer, String> g = new SparseMultigraph<Integer, String>();
// // Add some vertices. From above we defined these to be type Integer.
g.addVertex((Integer)1);
g.addVertex((Integer)2);
g.addVertex((Integer)3);
// // Add some edges. From above we defined these to be of type String
// // Note that the default is for undirected edges.
g.addEdge("Edge-A", 1, 2); // Note that Java 1.5 auto-boxes primitives
g.addEdge("Edge-B", 2, 3);
// // Let's see what we have. Note the nice output from the
// // SparseMultigraph<V,E> toString() method
System.out.println("The graph g = " + g.toString());
// // Note that we can use the same nodes and edges in two different graphs.
// Graph<Integer, String> g2 = new SparseMultigraph<Integer, String>();
// g2.addVertex((Integer)1);
// g2.addVertex((Integer)2);
// g2.addVertex((Integer)3);
// g2.addEdge("Edge-A", 1,3);
// g2.addEdge("Edge-B", 2,3, EdgeType.DIRECTED);
// g2.addEdge("Edge-C", 3, 2, EdgeType.DIRECTED);
// g2.addEdge("Edge-P", 2,3); // A parallel edge
// System.out.println("The graph g2 = " + g2.toString());
}
| public static void main(String[] args){
// Graph<V, E> where V is the type of the vertices
// // and E is the type of the edges
Graph<Integer, String> g = new SparseMultigraph<Integer, String>();
// // Add some vertices. From above we defined these to be type Integer.
g.addVertex((Integer)1);
g.addVertex((Integer)2);
g.addVertex((Integer)3);
// // Add some edges. From above we defined these to be of type String
// // Note that the default is for undirected edges.
g.addEdge("Edge-A", 1, 2); // Note that Java 1.5 auto-boxes primitives
g.addEdge("Edge-B", 2, 3);
// // Let's see what we have. Note the nice output from the
// // SparseMultigraph<V,E> toString() method
System.out.println("The graph g = " + g.toString());
// // Note that we can use the same nodes and edges in two different graphs.
Graph<Integer, String> g2 = new SparseMultigraph<Integer, String>();
g2.addVertex((Integer)1);
g2.addVertex((Integer)2);
g2.addVertex((Integer)3);
g2.addEdge("Edge-A", 1,3);
g2.addEdge("Edge-B", 2,3, EdgeType.DIRECTED);
g2.addEdge("Edge-C", 3, 2, EdgeType.DIRECTED);
g2.addEdge("Edge-P", 2,3); // A parallel edge
System.out.println("The graph g2 = " + g2.toString());
}
|
diff --git a/src/com/untamedears/xppylons/Pylon.java b/src/com/untamedears/xppylons/Pylon.java
index faa3e3f..e5ea7fb 100644
--- a/src/com/untamedears/xppylons/Pylon.java
+++ b/src/com/untamedears/xppylons/Pylon.java
@@ -1,120 +1,120 @@
package com.untamedears.xppylons;
import java.util.ArrayList;
import rtree.AABB;
import rtree.BoundedObject;
public class Pylon implements BoundedObject {
private PylonSet cluster;
private int x, y, z;
private double radius;
private int height;
private Pylon.EffectBounds influence;
public Pylon(PylonSet cluster, int x, int y, int z, int height) {
this.cluster = cluster;
this.x = x;
this.y = y;
this.z = z;
this.height = height;
this.influence = new Pylon.EffectBounds(this);
double maxHeight = cluster.getConfig().getMaxPylonHeight();
double maxRadius = cluster.getConfig().getMaximumRadius();
this.radius = Math.sqrt(height / maxHeight) * maxRadius;
}
public AABB getBounds() {
AABB boundingBox = new AABB();
boundingBox.setMinCorner((double) x - 2, (double) y - 1, (double) z - 2);
boundingBox.setMaxCorner((double) x + 2, (double) y + 2 + height, (double) z + 2);
return boundingBox;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
public int getHeight() {
return height;
}
public PylonSet getCluster() {
return cluster;
}
public double getRadiusOfEffect() {
return radius;
}
public Pylon.EffectBounds getInfluence() {
return influence;
}
public class EffectBounds implements BoundedObject {
private Pylon pylon;
public EffectBounds(Pylon pylon) {
this.pylon = pylon;
}
public Pylon getPylon() {
return pylon;
}
public boolean affects(double x, double z) {
return getStrengthAt(x, z) > 0;
}
public double getStrengthAt(double x, double z) {
double radius = pylon.getRadiusOfEffect();
double radiusSq = radius * radius;
double dx = pylon.getX() - x;
double dz = pylon.getZ() - z;
double distSq = dx * dx + dz * dz;
if (distSq > radiusSq) {
return 0;
} else {
double dist = Math.sqrt(radius);
double depletionScale = pylon.getCluster().getConfig().getPylonDepletion();
double strength = depletionScale * Math.sqrt(dist / radius);
return strength;
}
}
public double getShareAt(double x, double z) {
double totalStrength = 0.0;
double residual = 1.0;
for (Pylon other : pylon.getCluster().pylonsInfluencing(x, z)) {
double strengthAtPoint = other.getInfluence().getStrengthAt(x, z);
totalStrength += strengthAtPoint;
residual = residual * (1.0 - strengthAtPoint);
}
if (totalStrength <= 0.0 || residual <= 0.0 || residual > 1.0) {
return 0.0;
}
double draw = 1.0 - residual;
- double share = getStrengthAt(x, z) * (draw / totalStrength);
+ double share = (getStrengthAt(x, z) / totalStrength) * draw;
return share;
}
public AABB getBounds() {
double radius = pylon.getRadiusOfEffect();
AABB boundingBox = new AABB();
boundingBox.setMinCorner(x - radius, 0, z - radius);
boundingBox.setMaxCorner(x + radius, 256, z + radius);
return boundingBox;
}
}
}
| true | true | public double getShareAt(double x, double z) {
double totalStrength = 0.0;
double residual = 1.0;
for (Pylon other : pylon.getCluster().pylonsInfluencing(x, z)) {
double strengthAtPoint = other.getInfluence().getStrengthAt(x, z);
totalStrength += strengthAtPoint;
residual = residual * (1.0 - strengthAtPoint);
}
if (totalStrength <= 0.0 || residual <= 0.0 || residual > 1.0) {
return 0.0;
}
double draw = 1.0 - residual;
double share = getStrengthAt(x, z) * (draw / totalStrength);
return share;
}
| public double getShareAt(double x, double z) {
double totalStrength = 0.0;
double residual = 1.0;
for (Pylon other : pylon.getCluster().pylonsInfluencing(x, z)) {
double strengthAtPoint = other.getInfluence().getStrengthAt(x, z);
totalStrength += strengthAtPoint;
residual = residual * (1.0 - strengthAtPoint);
}
if (totalStrength <= 0.0 || residual <= 0.0 || residual > 1.0) {
return 0.0;
}
double draw = 1.0 - residual;
double share = (getStrengthAt(x, z) / totalStrength) * draw;
return share;
}
|
diff --git a/core/src/visad/trunk/formula/Postfix.java b/core/src/visad/trunk/formula/Postfix.java
index 85394fbc7..13c7e7142 100644
--- a/core/src/visad/trunk/formula/Postfix.java
+++ b/core/src/visad/trunk/formula/Postfix.java
@@ -1,351 +1,351 @@
//
// Postfix.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 1998 Bill Hibbard, Curtis Rueden, Tom
Rink and Dave Glowacki.
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 1, 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 in file NOTICE 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 visad.formula;
import java.util.*;
/** represents a formula in postfix notation.<P> */
class Postfix {
/** code for binary operator */
static final int BINARY = 0;
/** code for unary operator */
static final int UNARY = 1;
/** code for function name */
static final int FUNC = 2;
/** code for constant that represents number of function arguments */
static final int FUNCCONST = 3;
/** code for variable, constant, or other */
static final int OTHER = 4;
/** String representation of an implicit function */
private static final String IMPLICIT = " ";
/** postfix tokens */
String[] tokens = null;
/** postfix codes representing token types */
int[] codes = null;
/** construct a Postfix object by converting infix formula */
Postfix(String formula, FormulaManager fm) throws FormulaException {
// convert expression to postfix notation
String[] postfix = null;
int[] pfixcode = null;
String infix;
// convert string to char array
char[] charStr = formula.toCharArray();
// remove spaces and check parentheses
int numSpaces = 0;
int paren = 0;
for (int i=0; i<charStr.length; i++) {
if (charStr[i] == ' ') numSpaces++;
if (charStr[i] == '(') paren++;
if (charStr[i] == ')') paren--;
if (paren < 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"illegal placement of parentheses");
}
}
if (paren != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"parentheses are mismatched!");
}
int j = 0;
int newlen = charStr.length - numSpaces;
if (newlen == 0) return;
char[] exp = new char[newlen];
for (int i=0; i<charStr.length; i++) {
if (charStr[i] != ' ') exp[j++] = charStr[i];
}
infix = new String(exp);
// tokenize string
String ops = "(,)";
for (int i=0; i<fm.uOps.length; i++) ops = ops + fm.uOps[i];
for (int i=0; i<fm.bOps.length; i++) ops = ops + fm.bOps[i];
StringTokenizer tokenizer = new StringTokenizer(infix, ops, true);
int numTokens = tokenizer.countTokens();
// set up stacks
String[] funcStack = new String[numTokens]; // function stack
String[] opStack = new String[numTokens]; // operator stack
int[] opCodes = new int[numTokens]; // operator code stack
String[] pfix = new String[numTokens]; // final postfix ordering
int[] pcode = new int[numTokens]; // final postfix codes
int opPt = 0; // pointer into opStack
int funcPt = 0; // pointer into funcStack
int pfixlen = 0; // pointer into pfix
// flag for detecting unary operators
boolean unary = true;
// flag for detecting no-argument functions (e.g., x())
boolean zero = false;
// flag for detecting floating point numbers
boolean numeral = false;
// convert to postfix
String ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
String token = ntoken;
while (token != null) {
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (token.equals(")")) {
// right paren - pop ops until left paren reached (inclusive)
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[--opPt];
String op = opStack[opPt];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[--opPt];
}
if (opcode == FUNC) {
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
String f = funcStack[--funcPt];
boolean implicit;
if (zero) {
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "0";
}
else {
int n = 1;
while (f.equals(",")) {
n++;
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
f = funcStack[--funcPt];
}
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "" + n;
}
if (!implicit) {
pcode[pfixlen] = FUNC;
pfix[pfixlen++] = f;
}
}
unary = false;
zero = false;
numeral = false;
}
if (token.equals("(")) {
// left paren - push onto operator stack
opCodes[opPt] = OTHER;
opStack[opPt++] = "(";
unary = true;
zero = false;
numeral = false;
}
else if (token.equals(",")) {
// comma - pop ops until left paren reached (exclusive), push comma
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[opPt-1];
String op = opStack[opPt-1];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
+ opPt--;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
- opPt--;
opcode = opCodes[opPt-1];
op = opStack[opPt-1];
}
funcStack[funcPt++] = ",";
unary = true;
zero = false;
numeral = false;
}
else if ((unary && fm.isUnaryOp(token)) || fm.isBinaryOp(token)) {
int num = -1;
if (numeral && token.equals(".") && ntoken != null) {
// special case for detecting floating point numbers
try {
num = Integer.parseInt(ntoken);
}
catch (NumberFormatException exc) { }
}
if (num > 0) {
pfix[pfixlen-1] = pfix[pfixlen-1] + "." + ntoken;
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = false;
zero = false;
numeral = false;
}
else {
// operator - pop ops with higher precedence, push op
boolean isUnary = (unary && fm.isUnaryOp(token));
int prec = (isUnary ? fm.getUnaryPrec(token)
: fm.getBinaryPrec(token));
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
prec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
opCodes[opPt] = (isUnary ? UNARY : BINARY);
opStack[opPt++] = token;
unary = true;
zero = false;
numeral = false;
}
}
else if (ntoken != null && ntoken.equals("(")) {
// function - push function name and left paren
if (fm.isFunction(token)) funcStack[funcPt++] = token;
else {
// implicit function - append token to postfix expression
funcStack[funcPt++] = IMPLICIT;
if (!token.equals(")")) {
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
}
// pop ops with higher precedence
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
fm.iPrec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
}
opCodes[opPt] = FUNC;
opStack[opPt++] = "(";
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = true;
zero = true;
numeral = false;
}
else if (!token.equals(")")) {
// variable - append token to postfix expression
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
unary = false;
zero = false;
try {
int num = Integer.parseInt(token);
numeral = true;
}
catch (NumberFormatException exc) {
numeral = false;
}
}
token = ntoken;
}
// pop remaining ops from stack
while (opPt > 0) {
pcode[pfixlen] = opCodes[opPt-1];
pfix[pfixlen++] = "" + opStack[--opPt];
}
// make sure stacks are empty
if (opPt != 0 || funcPt != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"stacks are not empty");
}
// return postfix array of tokens
tokens = new String[pfixlen];
codes = new int[pfixlen];
System.arraycopy(pfix, 0, tokens, 0, pfixlen);
System.arraycopy(pcode, 0, codes, 0, pfixlen);
}
}
| false | true | Postfix(String formula, FormulaManager fm) throws FormulaException {
// convert expression to postfix notation
String[] postfix = null;
int[] pfixcode = null;
String infix;
// convert string to char array
char[] charStr = formula.toCharArray();
// remove spaces and check parentheses
int numSpaces = 0;
int paren = 0;
for (int i=0; i<charStr.length; i++) {
if (charStr[i] == ' ') numSpaces++;
if (charStr[i] == '(') paren++;
if (charStr[i] == ')') paren--;
if (paren < 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"illegal placement of parentheses");
}
}
if (paren != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"parentheses are mismatched!");
}
int j = 0;
int newlen = charStr.length - numSpaces;
if (newlen == 0) return;
char[] exp = new char[newlen];
for (int i=0; i<charStr.length; i++) {
if (charStr[i] != ' ') exp[j++] = charStr[i];
}
infix = new String(exp);
// tokenize string
String ops = "(,)";
for (int i=0; i<fm.uOps.length; i++) ops = ops + fm.uOps[i];
for (int i=0; i<fm.bOps.length; i++) ops = ops + fm.bOps[i];
StringTokenizer tokenizer = new StringTokenizer(infix, ops, true);
int numTokens = tokenizer.countTokens();
// set up stacks
String[] funcStack = new String[numTokens]; // function stack
String[] opStack = new String[numTokens]; // operator stack
int[] opCodes = new int[numTokens]; // operator code stack
String[] pfix = new String[numTokens]; // final postfix ordering
int[] pcode = new int[numTokens]; // final postfix codes
int opPt = 0; // pointer into opStack
int funcPt = 0; // pointer into funcStack
int pfixlen = 0; // pointer into pfix
// flag for detecting unary operators
boolean unary = true;
// flag for detecting no-argument functions (e.g., x())
boolean zero = false;
// flag for detecting floating point numbers
boolean numeral = false;
// convert to postfix
String ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
String token = ntoken;
while (token != null) {
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (token.equals(")")) {
// right paren - pop ops until left paren reached (inclusive)
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[--opPt];
String op = opStack[opPt];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[--opPt];
}
if (opcode == FUNC) {
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
String f = funcStack[--funcPt];
boolean implicit;
if (zero) {
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "0";
}
else {
int n = 1;
while (f.equals(",")) {
n++;
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
f = funcStack[--funcPt];
}
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "" + n;
}
if (!implicit) {
pcode[pfixlen] = FUNC;
pfix[pfixlen++] = f;
}
}
unary = false;
zero = false;
numeral = false;
}
if (token.equals("(")) {
// left paren - push onto operator stack
opCodes[opPt] = OTHER;
opStack[opPt++] = "(";
unary = true;
zero = false;
numeral = false;
}
else if (token.equals(",")) {
// comma - pop ops until left paren reached (exclusive), push comma
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[opPt-1];
String op = opStack[opPt-1];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opPt--;
opcode = opCodes[opPt-1];
op = opStack[opPt-1];
}
funcStack[funcPt++] = ",";
unary = true;
zero = false;
numeral = false;
}
else if ((unary && fm.isUnaryOp(token)) || fm.isBinaryOp(token)) {
int num = -1;
if (numeral && token.equals(".") && ntoken != null) {
// special case for detecting floating point numbers
try {
num = Integer.parseInt(ntoken);
}
catch (NumberFormatException exc) { }
}
if (num > 0) {
pfix[pfixlen-1] = pfix[pfixlen-1] + "." + ntoken;
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = false;
zero = false;
numeral = false;
}
else {
// operator - pop ops with higher precedence, push op
boolean isUnary = (unary && fm.isUnaryOp(token));
int prec = (isUnary ? fm.getUnaryPrec(token)
: fm.getBinaryPrec(token));
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
prec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
opCodes[opPt] = (isUnary ? UNARY : BINARY);
opStack[opPt++] = token;
unary = true;
zero = false;
numeral = false;
}
}
else if (ntoken != null && ntoken.equals("(")) {
// function - push function name and left paren
if (fm.isFunction(token)) funcStack[funcPt++] = token;
else {
// implicit function - append token to postfix expression
funcStack[funcPt++] = IMPLICIT;
if (!token.equals(")")) {
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
}
// pop ops with higher precedence
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
fm.iPrec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
}
opCodes[opPt] = FUNC;
opStack[opPt++] = "(";
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = true;
zero = true;
numeral = false;
}
else if (!token.equals(")")) {
// variable - append token to postfix expression
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
unary = false;
zero = false;
try {
int num = Integer.parseInt(token);
numeral = true;
}
catch (NumberFormatException exc) {
numeral = false;
}
}
token = ntoken;
}
// pop remaining ops from stack
while (opPt > 0) {
pcode[pfixlen] = opCodes[opPt-1];
pfix[pfixlen++] = "" + opStack[--opPt];
}
// make sure stacks are empty
if (opPt != 0 || funcPt != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"stacks are not empty");
}
// return postfix array of tokens
tokens = new String[pfixlen];
codes = new int[pfixlen];
System.arraycopy(pfix, 0, tokens, 0, pfixlen);
System.arraycopy(pcode, 0, codes, 0, pfixlen);
}
| Postfix(String formula, FormulaManager fm) throws FormulaException {
// convert expression to postfix notation
String[] postfix = null;
int[] pfixcode = null;
String infix;
// convert string to char array
char[] charStr = formula.toCharArray();
// remove spaces and check parentheses
int numSpaces = 0;
int paren = 0;
for (int i=0; i<charStr.length; i++) {
if (charStr[i] == ' ') numSpaces++;
if (charStr[i] == '(') paren++;
if (charStr[i] == ')') paren--;
if (paren < 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"illegal placement of parentheses");
}
}
if (paren != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"parentheses are mismatched!");
}
int j = 0;
int newlen = charStr.length - numSpaces;
if (newlen == 0) return;
char[] exp = new char[newlen];
for (int i=0; i<charStr.length; i++) {
if (charStr[i] != ' ') exp[j++] = charStr[i];
}
infix = new String(exp);
// tokenize string
String ops = "(,)";
for (int i=0; i<fm.uOps.length; i++) ops = ops + fm.uOps[i];
for (int i=0; i<fm.bOps.length; i++) ops = ops + fm.bOps[i];
StringTokenizer tokenizer = new StringTokenizer(infix, ops, true);
int numTokens = tokenizer.countTokens();
// set up stacks
String[] funcStack = new String[numTokens]; // function stack
String[] opStack = new String[numTokens]; // operator stack
int[] opCodes = new int[numTokens]; // operator code stack
String[] pfix = new String[numTokens]; // final postfix ordering
int[] pcode = new int[numTokens]; // final postfix codes
int opPt = 0; // pointer into opStack
int funcPt = 0; // pointer into funcStack
int pfixlen = 0; // pointer into pfix
// flag for detecting unary operators
boolean unary = true;
// flag for detecting no-argument functions (e.g., x())
boolean zero = false;
// flag for detecting floating point numbers
boolean numeral = false;
// convert to postfix
String ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
String token = ntoken;
while (token != null) {
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (token.equals(")")) {
// right paren - pop ops until left paren reached (inclusive)
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[--opPt];
String op = opStack[opPt];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[--opPt];
}
if (opcode == FUNC) {
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
String f = funcStack[--funcPt];
boolean implicit;
if (zero) {
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "0";
}
else {
int n = 1;
while (f.equals(",")) {
n++;
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
f = funcStack[--funcPt];
}
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "" + n;
}
if (!implicit) {
pcode[pfixlen] = FUNC;
pfix[pfixlen++] = f;
}
}
unary = false;
zero = false;
numeral = false;
}
if (token.equals("(")) {
// left paren - push onto operator stack
opCodes[opPt] = OTHER;
opStack[opPt++] = "(";
unary = true;
zero = false;
numeral = false;
}
else if (token.equals(",")) {
// comma - pop ops until left paren reached (exclusive), push comma
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[opPt-1];
String op = opStack[opPt-1];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
opPt--;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[opPt-1];
}
funcStack[funcPt++] = ",";
unary = true;
zero = false;
numeral = false;
}
else if ((unary && fm.isUnaryOp(token)) || fm.isBinaryOp(token)) {
int num = -1;
if (numeral && token.equals(".") && ntoken != null) {
// special case for detecting floating point numbers
try {
num = Integer.parseInt(ntoken);
}
catch (NumberFormatException exc) { }
}
if (num > 0) {
pfix[pfixlen-1] = pfix[pfixlen-1] + "." + ntoken;
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = false;
zero = false;
numeral = false;
}
else {
// operator - pop ops with higher precedence, push op
boolean isUnary = (unary && fm.isUnaryOp(token));
int prec = (isUnary ? fm.getUnaryPrec(token)
: fm.getBinaryPrec(token));
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
prec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
opCodes[opPt] = (isUnary ? UNARY : BINARY);
opStack[opPt++] = token;
unary = true;
zero = false;
numeral = false;
}
}
else if (ntoken != null && ntoken.equals("(")) {
// function - push function name and left paren
if (fm.isFunction(token)) funcStack[funcPt++] = token;
else {
// implicit function - append token to postfix expression
funcStack[funcPt++] = IMPLICIT;
if (!token.equals(")")) {
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
}
// pop ops with higher precedence
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
fm.iPrec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
}
opCodes[opPt] = FUNC;
opStack[opPt++] = "(";
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = true;
zero = true;
numeral = false;
}
else if (!token.equals(")")) {
// variable - append token to postfix expression
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
unary = false;
zero = false;
try {
int num = Integer.parseInt(token);
numeral = true;
}
catch (NumberFormatException exc) {
numeral = false;
}
}
token = ntoken;
}
// pop remaining ops from stack
while (opPt > 0) {
pcode[pfixlen] = opCodes[opPt-1];
pfix[pfixlen++] = "" + opStack[--opPt];
}
// make sure stacks are empty
if (opPt != 0 || funcPt != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"stacks are not empty");
}
// return postfix array of tokens
tokens = new String[pfixlen];
codes = new int[pfixlen];
System.arraycopy(pfix, 0, tokens, 0, pfixlen);
System.arraycopy(pcode, 0, codes, 0, pfixlen);
}
|
diff --git a/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/RegisterCWCMobileUploadTest.java b/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/RegisterCWCMobileUploadTest.java
index 1490cc94..ff60e12b 100644
--- a/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/RegisterCWCMobileUploadTest.java
+++ b/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/RegisterCWCMobileUploadTest.java
@@ -1,237 +1,238 @@
package org.motechproject.ghana.national.functional.mobile;
import org.apache.commons.collections.MapUtils;
import org.joda.time.LocalDate;
import org.junit.runner.RunWith;
import org.motechproject.ghana.national.domain.CwcCareHistory;
import org.motechproject.ghana.national.domain.RegistrationToday;
import org.motechproject.ghana.national.functional.OpenMRSAwareFunctionalTest;
import org.motechproject.ghana.national.functional.data.TestCWCEnrollment;
import org.motechproject.ghana.national.functional.data.TestMobileMidwifeEnrollment;
import org.motechproject.ghana.national.functional.data.TestPatient;
import org.motechproject.ghana.national.functional.framework.OpenMRSDB;
import org.motechproject.ghana.national.functional.framework.ScheduleTracker;
import org.motechproject.ghana.national.functional.framework.XformHttpClient;
import org.motechproject.ghana.national.functional.helper.ScheduleHelper;
import org.motechproject.ghana.national.functional.mobileforms.MobileForm;
import org.motechproject.ghana.national.functional.pages.openmrs.OpenMRSEncounterPage;
import org.motechproject.ghana.national.functional.pages.openmrs.OpenMRSPatientPage;
import org.motechproject.ghana.national.functional.pages.openmrs.vo.OpenMRSObservationVO;
import org.motechproject.ghana.national.functional.pages.patient.CWCEnrollmentPage;
import org.motechproject.ghana.national.functional.pages.patient.MobileMidwifeEnrollmentPage;
import org.motechproject.ghana.national.functional.pages.patient.PatientEditPage;
import org.motechproject.ghana.national.functional.pages.patient.SearchPatientPage;
import org.motechproject.ghana.national.functional.util.DataGenerator;
import org.motechproject.ghana.national.tools.Utility;
import org.motechproject.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static ch.lambdaj.Lambda.join;
import static ch.lambdaj.Lambda.on;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.motechproject.ghana.national.configuration.ScheduleNames.*;
import static org.motechproject.ghana.national.functional.data.TestPatient.PATIENT_TYPE.CHILD_UNDER_FIVE;
import static org.motechproject.util.DateUtil.today;
import static org.testng.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext-functional-tests.xml"})
public class RegisterCWCMobileUploadTest extends OpenMRSAwareFunctionalTest {
@Autowired
private OpenMRSDB openMRSDB;
@Autowired
ScheduleTracker scheduleTracker;
@Test
public void shouldCheckForAllMandatoryDetails() throws Exception {
final XformHttpClient.XformResponse xformResponse = mobile.upload(MobileForm.registerCWCForm(), MapUtils.EMPTY_MAP);
final List<XformHttpClient.Error> errors = xformResponse.getErrors();
assertEquals(errors.size(), 1);
final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors();
assertThat(errorsMap.get("staffId"), hasItem("is mandatory"));
assertThat(errorsMap.get("facilityId"), hasItem("is mandatory"));
assertThat(errorsMap.get("motechId"), hasItem("is mandatory"));
assertThat(errorsMap.get("registrationToday"), hasItem("is mandatory"));
assertThat(errorsMap.get("registrationDate"), hasItem("is mandatory"));
assertThat(errorsMap.get("serialNumber"), hasItem("is mandatory"));
}
@Test
public void shouldValidateIfRegistrationIsDoneByAProperUserForAnExistingPatientAndFacility() throws Exception {
final XformHttpClient.XformResponse xformResponse = mobile.upload(MobileForm.registerCWCForm(), new HashMap<String, String>() {{
put("motechId", "-1");
put("facilityId", "-1");
put("staffId", "-1");
put("registrationToday", RegistrationToday.TODAY.toString());
put("registrationDate", "2012-01-03");
put("serialNumber", "1234243243");
}});
final List<XformHttpClient.Error> errors = xformResponse.getErrors();
assertEquals(errors.size(), 1);
final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors();
assertThat(errorsMap.get("staffId"), hasItem("not found"));
assertThat(errorsMap.get("facilityId"), hasItem("not found"));
assertThat(errorsMap.get("motechId"), hasItem("not found"));
}
@Test
public void shouldRegisterAPatientForCWCAndMobileMidwifeProgramUsingMobileDeviceAndSearchForItInWeb() {
DataGenerator dataGenerator = new DataGenerator();
String staffId = staffGenerator.createStaff(browser, homePage);
TestPatient testPatient = TestPatient.with("First Name" + dataGenerator.randomString(5), staffId)
.patientType(TestPatient.PATIENT_TYPE.CHILD_UNDER_FIVE)
.estimatedDateOfBirth(false)
.dateOfBirth(DateUtil.newDate(DateUtil.today().getYear() - 1, 11, 11));
String patientId = patientGenerator.createPatient(testPatient, browser, homePage);
- TestCWCEnrollment cwcEnrollment = TestCWCEnrollment.create().withMotechPatientId(patientId).withStaffId(staffId);
+ LocalDate registrationDate = DateUtil.today().plusDays(10);
+ TestCWCEnrollment cwcEnrollment = TestCWCEnrollment.create().withMotechPatientId(patientId).withStaffId(staffId).withRegistrationDate(registrationDate);
TestMobileMidwifeEnrollment mmEnrollmentDetails = TestMobileMidwifeEnrollment.with(staffId, testPatient.facilityId()).patientId(patientId);
Map<String, String> data = cwcEnrollment.withMobileMidwifeEnrollmentThroughMobile(mmEnrollmentDetails);
- data.put("registrationDate", Utility.nullSafeToString(DateUtil.today().plusDays(10), "yyyy-MM-dd"));
+ data.put("registrationDate", Utility.nullSafeToString(registrationDate, "yyyy-MM-dd"));
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), data);
assertEquals(1, response.getSuccessCount());
PatientEditPage patientEditPage = toPatientEditPage(testPatient);
CWCEnrollmentPage cwcEnrollmentPage = browser.toEnrollCWCPage(patientEditPage);
cwcEnrollmentPage.displaying(cwcEnrollment);
patientEditPage = toPatientEditPage(testPatient);
MobileMidwifeEnrollmentPage mobileMidwifeEnrollmentPage = browser.toMobileMidwifeEnrollmentForm(patientEditPage);
assertThat(mobileMidwifeEnrollmentPage.details(), is(equalTo(mmEnrollmentDetails)));
OpenMRSPatientPage openMRSPatientPage = openMRSBrowser.toOpenMRSPatientPage(openMRSDB.getOpenMRSId(patientId));
String encounterId = openMRSPatientPage.chooseEncounter("CWCREGVISIT");
OpenMRSEncounterPage openMRSEncounterPage = openMRSBrowser.toOpenMRSEncounterPage(encounterId);
openMRSEncounterPage.displaying(asList(
new OpenMRSObservationVO("PENTA VACCINATION DOSE", "3.0"),
new OpenMRSObservationVO("INTERMITTENT PREVENTATIVE TREATMENT INFANTS DOSE", "2.0"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "VITAMIN A"),
new OpenMRSObservationVO("SERIAL NUMBER", "serialNumber"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "MEASLES VACCINATION"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "BACILLE CAMILE-GUERIN VACCINATION"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "YELLOW FEVER VACCINATION"),
new OpenMRSObservationVO("ORAL POLIO VACCINATION DOSE", "1.0")
));
}
@Test
public void shouldUnRegisterExistingMobileMidWifeWhileCWCRegistration() {
DataGenerator dataGenerator = new DataGenerator();
String staffId = staffGenerator.createStaff(browser, homePage);
TestPatient testPatient = TestPatient.with("First Name" + dataGenerator.randomString(5), staffId)
.patientType(TestPatient.PATIENT_TYPE.CHILD_UNDER_FIVE)
.estimatedDateOfBirth(false)
.dateOfBirth(DateUtil.newDate(DateUtil.today().getYear() - 1, 11, 11));
String patientId = patientGenerator.createPatient(testPatient, browser, homePage);
PatientEditPage patientEditPage = toPatientEditPage(testPatient);
MobileMidwifeEnrollmentPage mobileMidwifeEnrollmentPage = browser.toMobileMidwifeEnrollmentForm(patientEditPage);
mobileMidwifeEnrollmentPage.enroll(TestMobileMidwifeEnrollment.with(staffId));
TestCWCEnrollment cwcEnrollment = TestCWCEnrollment.create().withMotechPatientId(patientId).withStaffId(staffId);
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), cwcEnrollment.withoutMobileMidwifeEnrollmentThroughMobile());
assertEquals(1, response.getSuccessCount());
PatientEditPage patientPageAfterEdit = toPatientEditPage(testPatient);
mobileMidwifeEnrollmentPage = browser.toMobileMidwifeEnrollmentForm(patientPageAfterEdit);
assertThat(mobileMidwifeEnrollmentPage.status(),is("INACTIVE"));
}
@Test
public void shouldCreatePentaScheduleDuringCWCRegistrationIfTheTodayFallsWithin10WeeksFromDateOfBirth() {
String staffId = staffGenerator.createStaff(browser, homePage);
TestPatient patient = TestPatient.with("name", staffId).dateOfBirth(today().minusWeeks(5)).patientType(CHILD_UNDER_FIVE);
String patientId = patientGenerator.createPatient(patient, browser, homePage);
String openMRSId = openMRSDB.getOpenMRSId(patientId);
LocalDate registrationDate = DateUtil.today();
TestCWCEnrollment testCWCEnrollment = TestCWCEnrollment.createWithoutHistory().withMotechPatientId(patientId).withStaffId(staffId)
.withRegistrationDate(registrationDate);
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), testCWCEnrollment.withoutMobileMidwifeEnrollmentThroughMobile());
assertThat(join(response.getErrors(), on(XformHttpClient.Error.class).toString()), response.getErrors().size(), is(equalTo(0)));
ScheduleHelper.assertAlertDate(scheduleTracker.firstAlertScheduledFor(openMRSId, CWC_PENTA).getAlertAsLocalDate(), expectedFirstAlertDate(CWC_PENTA, patient.dateOfBirth())
);
}
@Test
public void shouldNotCreatePentaScheduleDuringCWCRegistrationIfTheTodayFallsAfter10WeeksFromDateOfBirth() {
String staffId = staffGenerator.createStaff(browser, homePage);
TestPatient patient = TestPatient.with("name-new", staffId).dateOfBirth(today().minusWeeks(11)).patientType(CHILD_UNDER_FIVE);
String patientId = patientGenerator.createPatient(patient, browser, homePage);
String openMRSId = openMRSDB.getOpenMRSId(patientId);
LocalDate registrationDate = DateUtil.today();
TestCWCEnrollment testCWCEnrollment = TestCWCEnrollment.createWithoutHistory().withMotechPatientId(patientId).withStaffId(staffId)
.withRegistrationDate(registrationDate);
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), testCWCEnrollment.withoutMobileMidwifeEnrollmentThroughMobile());
assertThat(join(response.getErrors(), on(XformHttpClient.Error.class).toString()), response.getErrors().size(), is(equalTo(0)));
assertNull(scheduleTracker.activeEnrollment(openMRSId, CWC_PENTA));
}
@Test
public void shouldCreateScheduleFromAppropriateMilestoneIfHistoryIsProvided(){
String staffId = staffGenerator.createStaff(browser, homePage);
LocalDate dateOfBirth = DateUtil.newDate(2012, 4, 3);
TestPatient patient = TestPatient.with("name-new", staffId).dateOfBirth(dateOfBirth).patientType(CHILD_UNDER_FIVE);
String patientId = patientGenerator.createPatient(patient, browser, homePage);
String openMRSId = openMRSDB.getOpenMRSId(patientId);
LocalDate registrationDate = DateUtil.newDate(2012, 4, 18);
TestCWCEnrollment testCWCEnrollment = TestCWCEnrollment.create().withMotechPatientId(patientId).withStaffId(staffId)
.withRegistrationDate(registrationDate).withAddHistory(true).withAddCareHistory(asList(CwcCareHistory.PENTA,CwcCareHistory.IPTI,CwcCareHistory.OPV))
.withLastIPTi("1").withLastIPTiDate(DateUtil.newDate(2012, 4, 16)).withLastPenta("1").withLastPentaDate(DateUtil.newDate(2012, 4, 16)).withLastOPV("1").withLastOPVDate(DateUtil.newDate(2012, 4, 16));
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), testCWCEnrollment.withoutMobileMidwifeEnrollmentThroughMobile());
assertThat(join(response.getErrors(), on(XformHttpClient.Error.class).toString()), response.getErrors().size(), is(equalTo(0)));
ScheduleHelper.assertAlertDate(scheduleTracker.firstAlertScheduledFor(openMRSId, CWC_PENTA).getAlertAsLocalDate(), expectedAlertDateFor(CWC_PENTA, testCWCEnrollment.getLastPentaDate(), "Penta2"));
ScheduleHelper.assertAlertDate(scheduleTracker.firstAlertScheduledFor(openMRSId, CWC_IPT_VACCINE).getAlertAsLocalDate(), expectedAlertDateFor(CWC_IPT_VACCINE, testCWCEnrollment.getLastIPTiDate(), "IPTi2"));
ScheduleHelper.assertAlertDate(scheduleTracker.firstAlertScheduledFor(openMRSId, CWC_OPV_OTHERS).getAlertAsLocalDate(), expectedAlertDateFor(CWC_OPV_OTHERS, testCWCEnrollment.getLastOPVDate(), "OPV2"));
}
private LocalDate expectedFirstAlertDate(String scheduleName, LocalDate referenceDate) {
return scheduleTracker.firstAlert(scheduleName, referenceDate);
}
private LocalDate expectedAlertDateFor(String scheduleName, LocalDate referenceDate, String milestoneName) {
return scheduleTracker.alertFor(scheduleName, referenceDate, milestoneName);
}
private PatientEditPage toPatientEditPage(TestPatient testPatient) {
SearchPatientPage searchPatientPage = browser.toSearchPatient();
searchPatientPage.searchWithName(testPatient.firstName());
searchPatientPage.displaying(testPatient);
return browser.toPatientEditPage(searchPatientPage, testPatient);
}
}
| false | true | public void shouldRegisterAPatientForCWCAndMobileMidwifeProgramUsingMobileDeviceAndSearchForItInWeb() {
DataGenerator dataGenerator = new DataGenerator();
String staffId = staffGenerator.createStaff(browser, homePage);
TestPatient testPatient = TestPatient.with("First Name" + dataGenerator.randomString(5), staffId)
.patientType(TestPatient.PATIENT_TYPE.CHILD_UNDER_FIVE)
.estimatedDateOfBirth(false)
.dateOfBirth(DateUtil.newDate(DateUtil.today().getYear() - 1, 11, 11));
String patientId = patientGenerator.createPatient(testPatient, browser, homePage);
TestCWCEnrollment cwcEnrollment = TestCWCEnrollment.create().withMotechPatientId(patientId).withStaffId(staffId);
TestMobileMidwifeEnrollment mmEnrollmentDetails = TestMobileMidwifeEnrollment.with(staffId, testPatient.facilityId()).patientId(patientId);
Map<String, String> data = cwcEnrollment.withMobileMidwifeEnrollmentThroughMobile(mmEnrollmentDetails);
data.put("registrationDate", Utility.nullSafeToString(DateUtil.today().plusDays(10), "yyyy-MM-dd"));
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), data);
assertEquals(1, response.getSuccessCount());
PatientEditPage patientEditPage = toPatientEditPage(testPatient);
CWCEnrollmentPage cwcEnrollmentPage = browser.toEnrollCWCPage(patientEditPage);
cwcEnrollmentPage.displaying(cwcEnrollment);
patientEditPage = toPatientEditPage(testPatient);
MobileMidwifeEnrollmentPage mobileMidwifeEnrollmentPage = browser.toMobileMidwifeEnrollmentForm(patientEditPage);
assertThat(mobileMidwifeEnrollmentPage.details(), is(equalTo(mmEnrollmentDetails)));
OpenMRSPatientPage openMRSPatientPage = openMRSBrowser.toOpenMRSPatientPage(openMRSDB.getOpenMRSId(patientId));
String encounterId = openMRSPatientPage.chooseEncounter("CWCREGVISIT");
OpenMRSEncounterPage openMRSEncounterPage = openMRSBrowser.toOpenMRSEncounterPage(encounterId);
openMRSEncounterPage.displaying(asList(
new OpenMRSObservationVO("PENTA VACCINATION DOSE", "3.0"),
new OpenMRSObservationVO("INTERMITTENT PREVENTATIVE TREATMENT INFANTS DOSE", "2.0"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "VITAMIN A"),
new OpenMRSObservationVO("SERIAL NUMBER", "serialNumber"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "MEASLES VACCINATION"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "BACILLE CAMILE-GUERIN VACCINATION"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "YELLOW FEVER VACCINATION"),
new OpenMRSObservationVO("ORAL POLIO VACCINATION DOSE", "1.0")
));
}
| public void shouldRegisterAPatientForCWCAndMobileMidwifeProgramUsingMobileDeviceAndSearchForItInWeb() {
DataGenerator dataGenerator = new DataGenerator();
String staffId = staffGenerator.createStaff(browser, homePage);
TestPatient testPatient = TestPatient.with("First Name" + dataGenerator.randomString(5), staffId)
.patientType(TestPatient.PATIENT_TYPE.CHILD_UNDER_FIVE)
.estimatedDateOfBirth(false)
.dateOfBirth(DateUtil.newDate(DateUtil.today().getYear() - 1, 11, 11));
String patientId = patientGenerator.createPatient(testPatient, browser, homePage);
LocalDate registrationDate = DateUtil.today().plusDays(10);
TestCWCEnrollment cwcEnrollment = TestCWCEnrollment.create().withMotechPatientId(patientId).withStaffId(staffId).withRegistrationDate(registrationDate);
TestMobileMidwifeEnrollment mmEnrollmentDetails = TestMobileMidwifeEnrollment.with(staffId, testPatient.facilityId()).patientId(patientId);
Map<String, String> data = cwcEnrollment.withMobileMidwifeEnrollmentThroughMobile(mmEnrollmentDetails);
data.put("registrationDate", Utility.nullSafeToString(registrationDate, "yyyy-MM-dd"));
XformHttpClient.XformResponse response = mobile.upload(MobileForm.registerCWCForm(), data);
assertEquals(1, response.getSuccessCount());
PatientEditPage patientEditPage = toPatientEditPage(testPatient);
CWCEnrollmentPage cwcEnrollmentPage = browser.toEnrollCWCPage(patientEditPage);
cwcEnrollmentPage.displaying(cwcEnrollment);
patientEditPage = toPatientEditPage(testPatient);
MobileMidwifeEnrollmentPage mobileMidwifeEnrollmentPage = browser.toMobileMidwifeEnrollmentForm(patientEditPage);
assertThat(mobileMidwifeEnrollmentPage.details(), is(equalTo(mmEnrollmentDetails)));
OpenMRSPatientPage openMRSPatientPage = openMRSBrowser.toOpenMRSPatientPage(openMRSDB.getOpenMRSId(patientId));
String encounterId = openMRSPatientPage.chooseEncounter("CWCREGVISIT");
OpenMRSEncounterPage openMRSEncounterPage = openMRSBrowser.toOpenMRSEncounterPage(encounterId);
openMRSEncounterPage.displaying(asList(
new OpenMRSObservationVO("PENTA VACCINATION DOSE", "3.0"),
new OpenMRSObservationVO("INTERMITTENT PREVENTATIVE TREATMENT INFANTS DOSE", "2.0"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "VITAMIN A"),
new OpenMRSObservationVO("SERIAL NUMBER", "serialNumber"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "MEASLES VACCINATION"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "BACILLE CAMILE-GUERIN VACCINATION"),
new OpenMRSObservationVO("IMMUNIZATIONS ORDERED", "YELLOW FEVER VACCINATION"),
new OpenMRSObservationVO("ORAL POLIO VACCINATION DOSE", "1.0")
));
}
|
diff --git a/Goobi/src/de/sub/goobi/config/DigitalCollections.java b/Goobi/src/de/sub/goobi/config/DigitalCollections.java
index 1df835090..7c9607955 100644
--- a/Goobi/src/de/sub/goobi/config/DigitalCollections.java
+++ b/Goobi/src/de/sub/goobi/config/DigitalCollections.java
@@ -1,77 +1,77 @@
/*
* This file is part of the Goobi Application - a Workflow tool for the support of
* mass digitization.
*
* Visit the websites for more information.
* - http://gdz.sub.uni-goettingen.de
* - http://www.goobi.org
* - http://launchpad.net/goobi-production
*
* 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.sub.goobi.config;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import de.sub.goobi.beans.Prozess;
public class DigitalCollections {
@SuppressWarnings("unchecked")
public static List<String> possibleDigitalCollectionsForProcess(
Prozess process) throws JDOMException, IOException {
List<String> result = new ArrayList<String>();
- String filename = ConfigMain.getParameter("KonfigurationVerzeichnis") + "digitalCollections.xml";
+ String filename = ConfigMain.getParameter("KonfigurationVerzeichnis") + "goobi_digitalCollections.xml";
if (!(new File(filename).exists())) {
throw new FileNotFoundException("File not found: " + filename);
}
/* Datei einlesen und Root ermitteln */
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));
Element root = doc.getRootElement();
/* alle Projekte durchlaufen */
List<Element> projekte = root.getChildren();
for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
Element projekt = (Element) iter.next();
List<Element> projektnamen = projekt.getChildren("name");
for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
Element projektname = (Element) iterator.next();
/*
* wenn der Projektname aufgeführt wird, dann alle Digitalen Collectionen in die Liste
*/
if (projektname.getText().equalsIgnoreCase(process.getProjekt().getTitel())) {
List<Element> myCols = projekt.getChildren("DigitalCollection");
for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
Element col = (Element) it2.next();
result.add(col.getText());
}
}
}
}
return result;
}
}
| true | true | public static List<String> possibleDigitalCollectionsForProcess(
Prozess process) throws JDOMException, IOException {
List<String> result = new ArrayList<String>();
String filename = ConfigMain.getParameter("KonfigurationVerzeichnis") + "digitalCollections.xml";
if (!(new File(filename).exists())) {
throw new FileNotFoundException("File not found: " + filename);
}
/* Datei einlesen und Root ermitteln */
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));
Element root = doc.getRootElement();
/* alle Projekte durchlaufen */
List<Element> projekte = root.getChildren();
for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
Element projekt = (Element) iter.next();
List<Element> projektnamen = projekt.getChildren("name");
for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
Element projektname = (Element) iterator.next();
/*
* wenn der Projektname aufgeführt wird, dann alle Digitalen Collectionen in die Liste
*/
if (projektname.getText().equalsIgnoreCase(process.getProjekt().getTitel())) {
List<Element> myCols = projekt.getChildren("DigitalCollection");
for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
Element col = (Element) it2.next();
result.add(col.getText());
}
}
}
}
return result;
}
| public static List<String> possibleDigitalCollectionsForProcess(
Prozess process) throws JDOMException, IOException {
List<String> result = new ArrayList<String>();
String filename = ConfigMain.getParameter("KonfigurationVerzeichnis") + "goobi_digitalCollections.xml";
if (!(new File(filename).exists())) {
throw new FileNotFoundException("File not found: " + filename);
}
/* Datei einlesen und Root ermitteln */
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));
Element root = doc.getRootElement();
/* alle Projekte durchlaufen */
List<Element> projekte = root.getChildren();
for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
Element projekt = (Element) iter.next();
List<Element> projektnamen = projekt.getChildren("name");
for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
Element projektname = (Element) iterator.next();
/*
* wenn der Projektname aufgeführt wird, dann alle Digitalen Collectionen in die Liste
*/
if (projektname.getText().equalsIgnoreCase(process.getProjekt().getTitel())) {
List<Element> myCols = projekt.getChildren("DigitalCollection");
for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
Element col = (Element) it2.next();
result.add(col.getText());
}
}
}
}
return result;
}
|
diff --git a/src/main/java/cellHTS/classes/RInterface.java b/src/main/java/cellHTS/classes/RInterface.java
index 1c6dcea..15845fb 100755
--- a/src/main/java/cellHTS/classes/RInterface.java
+++ b/src/main/java/cellHTS/classes/RInterface.java
@@ -1,781 +1,781 @@
/*
* //
* // Copyright (C) 2009 Boutros-Labs(German cancer research center) [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
* //
* // 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 cellHTS.classes;
import java.io.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipOutputStream;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.rosuda.REngine.Rserve.*;
import org.apache.tapestry5.ioc.internal.util.TapestryException;
import org.apache.tapestry5.Link;
import cellHTS.dao.Semaphore;
import javax.mail.MessagingException;
//the R program is running in the background
/**
*
* this class represents a R cellHTS2 run on the Rserve. It contains the complete cellHTS script and results zipping and
* sending of the results
* we have to make a new thread out of it that we can access the progressPercentage variable to update an progress bar while
*
* Created by IntelliJ IDEA.
* User: oliverpelz
* Date: 27.03.2009
* Time: 15:50:35
*
*/
public class RInterface extends Thread {
private HashMap<String, String> stringParams;
//we need this for a call by reference..we will read (only) this variable from outside this thread
//you can only emulate call by reference with an arry
private String[] progressPercentage;
//call by refernce will return true only if R cellHTS2 was successful
private Boolean[] successBool;
private String link;
private ArrayList<Pattern> patterns;
private ArrayList<Integer> patternPercentage;
private String completeOutput;
private RConnection rConnection;
private String rOutputFile;
private String rOutputScriptFile;
private Semaphore semaphore;
private boolean emailNotification;
private String resultZipFile;
private String emailAddress;
private long threadID;
private boolean sendErrorEmail;
//these two if we use email notification
MailTools postMailTools;
//get the hostname
private String hostname;
//send notification mails to the maintainer(s) of this tool in case of error
private String maintainEmailAddress;
/**
*
* Constructor
*
* @param map a HashMap structure with all the important R input parameters and presetted variables
* @param progressPercentage the progressPercentage, this is packed into a array obj to simulate call by reference because we want to see this progress percentage outside of this thread
* @param successBool call by reference (therefore packed into a array object) if the run was successful or not
* @param resultZipFile filename of the results zipped into a file
* @param semaphore this is a semaphore object to control how many instances are allowed to run in parallel
* @param eMailNotification should emails be sent or not
* @param emailAddress name of the recipient for the notification
* @param maintainEmailAddress email adress which occurs in the email in the from section and where to send questions etc to
* @param sendErrorEmail should a email sent to the developer if Rserve reported a error?
*/
public RInterface(HashMap<String, String> map, String[] progressPercentage,Boolean [] successBool,String resultZipFile,Semaphore semaphore,boolean eMailNotification,String emailAddress,String maintainEmailAddress,boolean sendErrorEmail) {
this.stringParams = map;
this.progressPercentage = progressPercentage;
this.completeOutput = new String("");
this.successBool=successBool;
this.semaphore = semaphore;
this.emailNotification=eMailNotification;
this.resultZipFile=resultZipFile;
this.emailAddress=emailAddress;
this.sendErrorEmail=sendErrorEmail;
if(this.emailNotification) {
postMailTools = new MailTools();
try {
InetAddress addr = InetAddress.getLocalHost();
// Get hostname
hostname = addr.getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
this.maintainEmailAddress=maintainEmailAddress;
}
}
public RInterface() {
}
/**
*
* get the cellHTS2 version from the R server
*
* @return a string containing the R version
*/
public String getCellHTS2Version() {
String version="not found";
String rVersion="not found";
RConnection c=null;
try {
c = new RConnection();
c.voidEval("library(cellHTS2)");
String output=c.eval("paste(capture.output(print(sessionInfo())),collapse=\"\\n\")").asString();
Pattern p1 = Pattern.compile("R version ([\\d\\.]+) ");
Matcher m1 = p1.matcher(output);
if(m1.find()) {
rVersion = m1.group(1);
}
Pattern p2 = Pattern.compile("cellHTS2_([\\d\\.]+)");
Matcher m2 = p2.matcher(output);
if(m2.find()) {
version = m2.group(1);
version = version+" (R:"+rVersion+")";
}
c.close();
}catch(Exception e) {e.printStackTrace();}
return version;
}
/**
*
* threads run method
*
*/
public void run() {
String queueFullMsg;
queueFullMsg="99_queue is full, waiting for a free slot...hold on! (dont close the window)!";
threadID = getId();
//check if we still have place before running
semaphore.p(progressPercentage,queueFullMsg,threadID);
String jobID = stringParams.get("jobName");
//make a new connection to the R server Rserve
try {
RConnection c = new RConnection();
setRengine(c);
}catch(Exception e) {
String exceptionText = "failed making connection to Rserver maybe you forgot to start it \"R CMD Rserve\" ";//)+e.printStackTrace());
exceptionText+="Note: this currently only works starting the RServer on the same server as this java is started from";
progressPercentage[0]="101_"+exceptionText;
e.printStackTrace();
sendNotificationToMaintainer(e.getMessage(),jobID);
sendNotificationToUser("General server problems. Please get in contact with program maintainers",jobID);
return;
//throw new TapestryException(exceptionText, null);
}
String debugString="";
String cmdString;
String outputDir = stringParams.get("runNameDir");
try {
//TODO: this code is ugly and not elegant. Better: write the R Script into a file with VARIABLE SPACERS, load it here and replace all the spacers with the settings here
//store original location where we started r
cmdString= "orgDir=getwd()";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//first we have to change to the Indir in order to make the R cellHTS script working
cmdString= "setwd(\""+Configuration.UPLOAD_PATH+stringParams.get("jobName")+"\")";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//assign java variables to our R interface
cmdString="Indir=\""+Configuration.UPLOAD_PATH+stringParams.get("jobName")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Indir", Configuration.UPLOAD_PATH+stringParams.get("jobName"));
//create a outputfile for the results under the "root" out dir ..thats the only location where it is sure
//that we have rite permissions!
stringParams.put("outputDir",outputDir);
String evalOutput = "dir.create(\""+outputDir+"\", recursive = TRUE)";
getRengine().voidEval(evalOutput);
rOutputFile=outputDir+"/R_OUTPUT.TXT";
rOutputScriptFile=outputDir+"/R_OUTPUT.SCRIPT";
//getRengine().voidEval("options(warn=1)");
String openFile = "zz <- file(\""+rOutputFile+"\", open=\"w\")";
cmdString=openFile ;
debugString+=cmdString+"\n";
getRengine().voidEval(openFile);
//comment the next three lines for debugging
//get messages not the output!
String sinkMsg= "sink(file=zz,type=\"message\" )";
cmdString=sinkMsg ;
debugString+=cmdString+"\n";
getRengine().voidEval(sinkMsg);
//how to call the htmls result page
cmdString="Name=\""+stringParams.get("htmlResultName")+"\"";
debugString+=cmdString+"\n";
getRengine().assign("Name", stringParams.get("htmlResultName"));
cmdString="Outdir_report=\""+outputDir+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Outdir_report", outputDir);
//R has boolean support which is TRUE and FALSE and NOT! Strings "TRUE" or "FALSE"
if(stringParams.get("logTransform").equals("NO")) {
cmdString="LogTransform=FALSE" ;
debugString+=cmdString+"\n";
getRengine().voidEval("LogTransform=FALSE");
}
else {
cmdString="LogTransform=TRUE" ;
debugString+=cmdString+"\n";
getRengine().voidEval("LogTransform=TRUE");
}
cmdString= "PlateList=\""+stringParams.get("plateList")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("PlateList", stringParams.get("plateList"));
cmdString="Plateconf=\""+stringParams.get("plateConf")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Plateconf", stringParams.get("plateConf"));
cmdString="Description=\""+stringParams.get("descriptionFile")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Description", stringParams.get("descriptionFile")); //if we did not submit one we will generate one automaically
cmdString="NormalizationMethod=\""+stringParams.get("normalMethod")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("NormalizationMethod", stringParams.get("normalMethod"));
cmdString="NormalizationScaling=\""+stringParams.get("normalScaling")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("NormalizationScaling", stringParams.get("normalScaling"));
cmdString= "VarianceAdjust=\""+stringParams.get("varianceAdjust")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("VarianceAdjust", stringParams.get("varianceAdjust"));
cmdString="SummaryMethod=\""+stringParams.get("summaryMethod")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("SummaryMethod", stringParams.get("summaryMethod"));
cmdString= "Screenlog=\""+stringParams.get("screenLogFile")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Screenlog",stringParams.get("screenLogFile"));
//this should not be selected from the menue ...TODO: maybe we should add it later
cmdString="Score=\""+Configuration.scoreReplicates+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Score",Configuration.scoreReplicates);
if (stringParams.get("annotFile") != null) {
cmdString="Annotation=\""+stringParams.get("annotFile") +"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Annotation", stringParams.get("annotFile"));
}
//TODO:make case here single channel or dual channel script
try {
if (stringParams.get("channelTypes").equals("single")) {
//TODO: this is somehow ugly code and could be more beautiful..it was written under time pressure :-(
//TODO: check if the REXP isnull checking works at all
progressPercentage[0]="15_loading cellHTS2 lib";
cmdString="library(cellHTS2)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="20_reading plate list";
cmdString="x=readPlateList(PlateList, name = Name, path = Indir)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="25_configuring layout";
cmdString="x=configure(x, descripFile=Description, confFile=Plateconf, logFile=Screenlog)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="45_normalizing plates";
cmdString="xn=normalizePlates(x, scale =NormalizationScaling , log =LogTransform,method=NormalizationMethod, varianceAdjust=VarianceAdjust)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="47_comparing to cellHTS";
cmdString="comp=compare2cellHTS(x, xn)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="50_scoring replicates";
cmdString="xsc=scoreReplicates(xn, sign = \"-\", method = Score)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="60_summerizing replicates";
cmdString="xsc=summarizeReplicates(xsc, summary = SummaryMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="65_scoring data";
cmdString="scores=Data(xsc)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="80_quantiling";
cmdString="ylim=quantile(scores, c(0.001, 0.999), na.rm = TRUE)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="81_writing the report....";
if (stringParams.get("annotFile") != null) {
progressPercentage[0]="82_annotating data";
cmdString="xsc=annotate(xsc, geneIDFile = Annotation)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
progressPercentage[0]="85_writing the output";
//this is for cellHTS2 < 2.7.9
// getRengine().voidEval("out = writeReport(cellHTSlist = list(raw = x, normalized = xn, scored = xsc), outdir = Outdir_report, force = TRUE, plotPlateArgs = list(xrange = c(0.5,3)), imageScreenArgs = list(zrange = c(-4, 8), ar = 1),,progressReport=FALSE)");
//this is for the new cellHTS2 >= 2.7.9
cmdString="out=writeReport(raw = x, normalized = xn, scored = xsc, outdir = Outdir_report, force = TRUE, settings = list(xrange = c(0.5,3),zrange = c(-4, 8), ar = 1))";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="100_successfully done";
successBool[0]=true;
} else {
//this is the path for dual channel scripts
progressPercentage[0]="15_loading cellHTS2 lib";
cmdString="library(\"cellHTS2\")";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="20_reading plate list";
cmdString="x = readPlateList(PlateList,name=Name,path=Indir)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="25_configuring layout";
cmdString="x = configure(x , descripFile=Description, confFile=Plateconf, logFile=Screenlog)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="45_normalizing plates";
cmdString="xp = normalizePlates(x, log=LogTransform, scale=NormalizationScaling, method=NormalizationMethod, varianceAdjust=VarianceAdjust)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="60_summerizing channels";
if(stringParams.get("viabilityChannel").equals("NO")) {
cmdString="xs = summarizeChannels(xp)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
else {
if(stringParams.get("viabilityFunction")!=null) {
cmdString ="ViabilityMethod = "+stringParams.get("viabilityFunction");
}
else {
//this is our standard viability function
cmdString="ViabilityMethod = function(r1, r2) {ifelse(r2>(-1), -r1, NA)}";
}
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
cmdString="xs = summarizeChannels(xp, fun = ViabilityMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
cmdString="xn = xs";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
cmdString="xn@state[\"normalized\"] = TRUE";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="65_scoring replicates";
cmdString="xsc = scoreReplicates(xn, sign = \"-\", method = Score)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="70_summerizing replicates";
cmdString="xsc = summarizeReplicates(xsc, summary = SummaryMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="75_writing the report....";
if (stringParams.get("annotFile") != null) {
progressPercentage[0]="78_annotating data";
cmdString="xsc = annotate(xsc, geneIDFile = Annotation)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
progressPercentage[0]="76_writing the output";
//this is for cellHTS2 < 2.7.9
//getRengine().voidEval("out = writeReport(cellHTSlist = list(raw = x, normalized = xn, scored = xsc),imageScreenArgs = list(zrange = c(-4, 4)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE ,progressReport=FALSE)");
//this is for the new cellHTS2 >= 2.7.9
- cmdString="out = writeReport(raw = x, normalized = xn, scored = xsc,settings = list(zrange = c(-4, 4)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE )";
+ cmdString="out = writeReport(raw = x, normalized = xn, scored = xsc,settings = list(zrange = c(-4, 4),xrange = c(0.5,3)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE )";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//after we are done...create a zipfile out of the results
progressPercentage[0]="100_successfully done";
successBool[0]=true;
}
}catch(RserveException e) {
String step = progressPercentage[0].split("_")[1];
String tempString="101_Error occured at step:"+step+"<br/>Please consult R logfile under:<br/>"+rOutputFile+"<br/> if debugging is on also run the script "+rOutputScriptFile ;
//close the logging and the logfile before printing it or you will lose information!
String msg = e.getMessage();
String requestErrorDesc = e.getRequestErrorDescription();
int returnCode = e.getRequestReturnCode();
//uncomment try catch block for debugging
try {
getRengine().voidEval("sink()");
} catch(RserveException re) {
tempString+=" <br/>AND Error occured closing the R_OUTPUTSTREAM (this will be 99% caused by a Rserve dynlib crash):maybe your logfile isnt complete!...which will be a bad thing:<br/>One reason is not correctly formatting your annotation files under mac, e.g. saving it as a dos text file will bring Rserve to make segfault<br/>another reason is the use of Rserve <0.6";
}
progressPercentage[0]=tempString+"<br/><br/> <FONT COLOR=\"red\">received error Messages:"+getErrorMsgFromRLogfile()+"</FONT>"+"<br/>";
progressPercentage[0]+="msg:"+msg+"<br/>errorDesc:"+requestErrorDesc+"<br/>returnCode:"+returnCode+"<br/>";
FileCreator.stringToFile(new File(rOutputScriptFile),debugString);
//add script to the results zip file
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General Rserve problem:\n"+" at step: "+step+"\n"+msg+" "+requestErrorDesc+" returncode:"+returnCode+"\nPlease get in contact with program maintainers",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
} catch (Exception e) {
progressPercentage[0]="101_General error occured: "+e.getMessage();
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
//try to close the outputstream
try {
//at the end of our run
//restore old values for the next one accessing the server :
//back to old dir
getRengine().voidEval("setwd(orgDir)");
}catch(RserveException e) {
progressPercentage[0]="101_Error occured setting original dir";
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
//uncomment try catch block for debugging
try {
//close the logging and the logfile
getRengine().voidEval("sink()");
}catch(RserveException e) {
progressPercentage[0]="101_Error occured closing the R_OUTPUTSTREAM:maybe your logfile isnt complete!...which will be a bad thing:\nOne reason is running Rserve binary on Mac Os X server.Check /var/log/system.log and search for a Rserve crash report";
sendNotificationToMaintainer(progressPercentage[0]+"\n"+e.getMessage(),jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
e.printStackTrace();
getRengine().close();
semaphore.v(threadID);
return;
}
//if were here we have won!
FileCreator.stringToFile(new File(rOutputScriptFile),debugString);
//zip the results
if(!createResultsZipFile()) {
progressPercentage[0] = "101_Error occured trying to zip the resultfiles!";
sendNotificationToMaintainer(progressPercentage[0], jobID);
sendNotificationToUser("General server problems. Please get in contact with program maintainers", jobID);
getRengine().close();
semaphore.v(threadID);
//TODO:put all the exceptions and stuff in a seperate return function where you stop the semaphore and close everything
return;
}
//finally close this R Server connection
getRengine().close();
semaphore.v(threadID);
//send results to email
if(this.emailNotification) {
String runName=this.extractRunName(stringParams.get("runNameDir"));
//create a recycable downloadlink as well...therefore we have to keep track about how often a file is allowed to be downloaded
//which we will write into a properties file
String dlPropertiesFile = Configuration.UPLOAD_PATH+stringParams.get("jobName")+"/.dlProperties";
String downloadLink = stringParams.get("emailDownloadLink");
//init a properties file
Properties propObj = new Properties();
//set the relation between runname and result zip file
propObj.setProperty(runName+"_RESULT_ZIP",resultZipFile);
//put in the properties file that we downloaded this runid zero times
propObj.setProperty(runName,"0");
//generate a password for downloading
String pw = PasswordGenerator.get(20);
propObj.setProperty(runName+"_password",pw);
try {
propObj.store(new FileOutputStream(new File(dlPropertiesFile)),"properties file for email Download information");
}catch(Exception e) {
e.printStackTrace();
}
//FileCreator.writeDownloadPropertiesFile(new File(dlPropertiesFile),runName,0);
String emailMsg="";//"Your job ID was: "+runName+'\n';
String file=null;
int percentage = Integer.parseInt(progressPercentage[0].split("_")[0]);
String msg = progressPercentage[0].split("_")[1];
if(percentage==100) {
emailMsg+="Dear cellHTS2 user,\n" +
"\n" +
"Please download the calculated results from your query from our server (you are allowed to do this "+stringParams.get("allowed-dl-numbers")+" times ) at:\n\n"
+downloadLink+"\n"+" with the password: "+pw+"\n\n"+
// "Please find attached the calculated results from your query. " +
"Save the file and unpack it using an unzip program.\n" +
"The \"index.html\" file can be opened by any web browser for view the analysis results. We have also included a session " +
"that can be used to modify analysis settings.\n" +
"\n" +
"Do not hesitate to contact us if you have any question or suggestions for improvement.\n" +
"\n" +
"Sincerely,\n" +
"\n" +
"web cellHTS Team\n" +
"Email: "+ this.maintainEmailAddress+"\n" +
"\n" +
"Please use the following citation when using cellHTS:\n" +
"Boutros, M., L. Bras, and W. Huber. (2006). Analysis of cell-based RNAi screens. Genome Biology 7:R66.\n"+
"Abstract: http://genomebiology.com/2006/7/7/R66\n"+
"Full Text: http://genomebiology.com/content/pdf/gb-2006-7-7-r66.pdf\n"+
"PubMed: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&cmd=Retrieve&dopt=AbstractPlus&list_uids=16869968";
file=resultZipFile;
}
else {
emailMsg+="Sorry, but your run was not successful! Error percentage: "+percentage+"\nSystem output:\n"+msg+"\nPlease consult the manual or ask the developers of this tool for help!";
file =null;
}
//create array of attachements
String sessionFile = stringParams.get("sessionFile");
if(sessionFile==null) {
return;
}
String []files = {file,sessionFile};
postMailTools.postMail( emailAddress,
"cellHTS2 report (\""+runName+"\"):",
emailMsg,
this.maintainEmailAddress,
null //file if we want to send the result as file
);
}
}
/**
*
* this method sends a message to the maintainer
*
* @param msg the message to send
* @param runName the runname ID to send
*/
public void sendNotificationToMaintainer(String msg,String runName) {
if(this.emailNotification) {
if(this.sendErrorEmail) {
postMailTools.postMail( this.maintainEmailAddress,
"Error report for job ID: "+runName,
msg,
//"cellHTS2-results@"+hostname,
this.maintainEmailAddress,
null //no file attached
);
}
}
}
/**
*
* sends a notification to the user e.g. in case of error
*
* @param msg message to send
* @param runName the runname to send
*/
public void sendNotificationToUser(String msg,String runName) {
if(this.emailNotification) {
String errorMsg = "There were some problems executing your analysis job.\nPlease check your input or send an email to the maintainers (mentioning your job ID): "+this.maintainEmailAddress+"\n";
errorMsg+="\n\n\n------------\nError message: \n";
msg =errorMsg+msg;
postMailTools.postMail( emailAddress,
"Error report for job ID: "+runName,
msg,
this.maintainEmailAddress,
//"cellHTS2-results@"+hostname,
null //no file attached
);
}
}
public HashMap<String, String> getStringParams() {
return stringParams;
}
public void setStringParams(HashMap<String, String> stringParams) {
this.stringParams = stringParams;
}//inner class
public synchronized RConnection getRengine() {
return rConnection;
}
public synchronized void setRengine(RConnection e) {
rConnection = e;
}
/**
*
* parses an R logfile
*
* @return the parsed error message
*/
//TODO: this sub works only as long as were running this webapp from the same server as R and RServe is installed on
//TODO: otherwise this has to be changed to copy the log file from the server first
public String getErrorMsgFromRLogfile() {
String fileContent = FileParser.readFileAsStringWithNewline(new File(rOutputFile));
//begin returning error message at first error occurence
String returnErrorMsg="";
String[]lines = fileContent.split("\n");
Pattern p = Pattern.compile("Fehler|Error");
boolean foundErr=false;
for(String line : lines) {
Matcher m = p.matcher(line);
if(m.find()) {
foundErr=true;
}
if(foundErr) {
returnErrorMsg+=line+"\n";
}
}
return returnErrorMsg;
}
/**
*
* creates a zip file out of a results folder
*
* @return true if zipping succeeded, false otherwise
*/
public boolean createResultsZipFile() {
boolean returnValue = true;
//zip the results if there are any at all!
//create an temporary directory for this session
String zipDir=stringParams.get("runNameDir");
try {
ZipOutputStream zos = new
ZipOutputStream(new FileOutputStream(resultZipFile));
//we have to give the root dir ...this is a limitation of the zipDir function
String[]tmpDirs = zipDir.split("/");
String rootDir = tmpDirs[tmpDirs.length-1];
if (ShellEnvironment.zipDir(zipDir, zos, rootDir)) {
zos.close();
}
}catch(Exception e) {
e.printStackTrace();
returnValue=false;
}
return returnValue;
}
public String extractRunName(String dir) {
return (new File(dir)).getName();
}
/**
* kill the thread id and thread from the semaphore (only if it is still available..if we are at 100% this isnt true anymore)
*/
public void killMe() {
semaphore.removeRunningJob(threadID);
this.interrupt();
}
}
| true | true | public void run() {
String queueFullMsg;
queueFullMsg="99_queue is full, waiting for a free slot...hold on! (dont close the window)!";
threadID = getId();
//check if we still have place before running
semaphore.p(progressPercentage,queueFullMsg,threadID);
String jobID = stringParams.get("jobName");
//make a new connection to the R server Rserve
try {
RConnection c = new RConnection();
setRengine(c);
}catch(Exception e) {
String exceptionText = "failed making connection to Rserver maybe you forgot to start it \"R CMD Rserve\" ";//)+e.printStackTrace());
exceptionText+="Note: this currently only works starting the RServer on the same server as this java is started from";
progressPercentage[0]="101_"+exceptionText;
e.printStackTrace();
sendNotificationToMaintainer(e.getMessage(),jobID);
sendNotificationToUser("General server problems. Please get in contact with program maintainers",jobID);
return;
//throw new TapestryException(exceptionText, null);
}
String debugString="";
String cmdString;
String outputDir = stringParams.get("runNameDir");
try {
//TODO: this code is ugly and not elegant. Better: write the R Script into a file with VARIABLE SPACERS, load it here and replace all the spacers with the settings here
//store original location where we started r
cmdString= "orgDir=getwd()";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//first we have to change to the Indir in order to make the R cellHTS script working
cmdString= "setwd(\""+Configuration.UPLOAD_PATH+stringParams.get("jobName")+"\")";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//assign java variables to our R interface
cmdString="Indir=\""+Configuration.UPLOAD_PATH+stringParams.get("jobName")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Indir", Configuration.UPLOAD_PATH+stringParams.get("jobName"));
//create a outputfile for the results under the "root" out dir ..thats the only location where it is sure
//that we have rite permissions!
stringParams.put("outputDir",outputDir);
String evalOutput = "dir.create(\""+outputDir+"\", recursive = TRUE)";
getRengine().voidEval(evalOutput);
rOutputFile=outputDir+"/R_OUTPUT.TXT";
rOutputScriptFile=outputDir+"/R_OUTPUT.SCRIPT";
//getRengine().voidEval("options(warn=1)");
String openFile = "zz <- file(\""+rOutputFile+"\", open=\"w\")";
cmdString=openFile ;
debugString+=cmdString+"\n";
getRengine().voidEval(openFile);
//comment the next three lines for debugging
//get messages not the output!
String sinkMsg= "sink(file=zz,type=\"message\" )";
cmdString=sinkMsg ;
debugString+=cmdString+"\n";
getRengine().voidEval(sinkMsg);
//how to call the htmls result page
cmdString="Name=\""+stringParams.get("htmlResultName")+"\"";
debugString+=cmdString+"\n";
getRengine().assign("Name", stringParams.get("htmlResultName"));
cmdString="Outdir_report=\""+outputDir+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Outdir_report", outputDir);
//R has boolean support which is TRUE and FALSE and NOT! Strings "TRUE" or "FALSE"
if(stringParams.get("logTransform").equals("NO")) {
cmdString="LogTransform=FALSE" ;
debugString+=cmdString+"\n";
getRengine().voidEval("LogTransform=FALSE");
}
else {
cmdString="LogTransform=TRUE" ;
debugString+=cmdString+"\n";
getRengine().voidEval("LogTransform=TRUE");
}
cmdString= "PlateList=\""+stringParams.get("plateList")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("PlateList", stringParams.get("plateList"));
cmdString="Plateconf=\""+stringParams.get("plateConf")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Plateconf", stringParams.get("plateConf"));
cmdString="Description=\""+stringParams.get("descriptionFile")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Description", stringParams.get("descriptionFile")); //if we did not submit one we will generate one automaically
cmdString="NormalizationMethod=\""+stringParams.get("normalMethod")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("NormalizationMethod", stringParams.get("normalMethod"));
cmdString="NormalizationScaling=\""+stringParams.get("normalScaling")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("NormalizationScaling", stringParams.get("normalScaling"));
cmdString= "VarianceAdjust=\""+stringParams.get("varianceAdjust")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("VarianceAdjust", stringParams.get("varianceAdjust"));
cmdString="SummaryMethod=\""+stringParams.get("summaryMethod")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("SummaryMethod", stringParams.get("summaryMethod"));
cmdString= "Screenlog=\""+stringParams.get("screenLogFile")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Screenlog",stringParams.get("screenLogFile"));
//this should not be selected from the menue ...TODO: maybe we should add it later
cmdString="Score=\""+Configuration.scoreReplicates+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Score",Configuration.scoreReplicates);
if (stringParams.get("annotFile") != null) {
cmdString="Annotation=\""+stringParams.get("annotFile") +"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Annotation", stringParams.get("annotFile"));
}
//TODO:make case here single channel or dual channel script
try {
if (stringParams.get("channelTypes").equals("single")) {
//TODO: this is somehow ugly code and could be more beautiful..it was written under time pressure :-(
//TODO: check if the REXP isnull checking works at all
progressPercentage[0]="15_loading cellHTS2 lib";
cmdString="library(cellHTS2)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="20_reading plate list";
cmdString="x=readPlateList(PlateList, name = Name, path = Indir)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="25_configuring layout";
cmdString="x=configure(x, descripFile=Description, confFile=Plateconf, logFile=Screenlog)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="45_normalizing plates";
cmdString="xn=normalizePlates(x, scale =NormalizationScaling , log =LogTransform,method=NormalizationMethod, varianceAdjust=VarianceAdjust)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="47_comparing to cellHTS";
cmdString="comp=compare2cellHTS(x, xn)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="50_scoring replicates";
cmdString="xsc=scoreReplicates(xn, sign = \"-\", method = Score)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="60_summerizing replicates";
cmdString="xsc=summarizeReplicates(xsc, summary = SummaryMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="65_scoring data";
cmdString="scores=Data(xsc)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="80_quantiling";
cmdString="ylim=quantile(scores, c(0.001, 0.999), na.rm = TRUE)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="81_writing the report....";
if (stringParams.get("annotFile") != null) {
progressPercentage[0]="82_annotating data";
cmdString="xsc=annotate(xsc, geneIDFile = Annotation)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
progressPercentage[0]="85_writing the output";
//this is for cellHTS2 < 2.7.9
// getRengine().voidEval("out = writeReport(cellHTSlist = list(raw = x, normalized = xn, scored = xsc), outdir = Outdir_report, force = TRUE, plotPlateArgs = list(xrange = c(0.5,3)), imageScreenArgs = list(zrange = c(-4, 8), ar = 1),,progressReport=FALSE)");
//this is for the new cellHTS2 >= 2.7.9
cmdString="out=writeReport(raw = x, normalized = xn, scored = xsc, outdir = Outdir_report, force = TRUE, settings = list(xrange = c(0.5,3),zrange = c(-4, 8), ar = 1))";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="100_successfully done";
successBool[0]=true;
} else {
//this is the path for dual channel scripts
progressPercentage[0]="15_loading cellHTS2 lib";
cmdString="library(\"cellHTS2\")";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="20_reading plate list";
cmdString="x = readPlateList(PlateList,name=Name,path=Indir)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="25_configuring layout";
cmdString="x = configure(x , descripFile=Description, confFile=Plateconf, logFile=Screenlog)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="45_normalizing plates";
cmdString="xp = normalizePlates(x, log=LogTransform, scale=NormalizationScaling, method=NormalizationMethod, varianceAdjust=VarianceAdjust)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="60_summerizing channels";
if(stringParams.get("viabilityChannel").equals("NO")) {
cmdString="xs = summarizeChannels(xp)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
else {
if(stringParams.get("viabilityFunction")!=null) {
cmdString ="ViabilityMethod = "+stringParams.get("viabilityFunction");
}
else {
//this is our standard viability function
cmdString="ViabilityMethod = function(r1, r2) {ifelse(r2>(-1), -r1, NA)}";
}
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
cmdString="xs = summarizeChannels(xp, fun = ViabilityMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
cmdString="xn = xs";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
cmdString="xn@state[\"normalized\"] = TRUE";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="65_scoring replicates";
cmdString="xsc = scoreReplicates(xn, sign = \"-\", method = Score)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="70_summerizing replicates";
cmdString="xsc = summarizeReplicates(xsc, summary = SummaryMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="75_writing the report....";
if (stringParams.get("annotFile") != null) {
progressPercentage[0]="78_annotating data";
cmdString="xsc = annotate(xsc, geneIDFile = Annotation)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
progressPercentage[0]="76_writing the output";
//this is for cellHTS2 < 2.7.9
//getRengine().voidEval("out = writeReport(cellHTSlist = list(raw = x, normalized = xn, scored = xsc),imageScreenArgs = list(zrange = c(-4, 4)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE ,progressReport=FALSE)");
//this is for the new cellHTS2 >= 2.7.9
cmdString="out = writeReport(raw = x, normalized = xn, scored = xsc,settings = list(zrange = c(-4, 4)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE )";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//after we are done...create a zipfile out of the results
progressPercentage[0]="100_successfully done";
successBool[0]=true;
}
}catch(RserveException e) {
String step = progressPercentage[0].split("_")[1];
String tempString="101_Error occured at step:"+step+"<br/>Please consult R logfile under:<br/>"+rOutputFile+"<br/> if debugging is on also run the script "+rOutputScriptFile ;
//close the logging and the logfile before printing it or you will lose information!
String msg = e.getMessage();
String requestErrorDesc = e.getRequestErrorDescription();
int returnCode = e.getRequestReturnCode();
//uncomment try catch block for debugging
try {
getRengine().voidEval("sink()");
} catch(RserveException re) {
tempString+=" <br/>AND Error occured closing the R_OUTPUTSTREAM (this will be 99% caused by a Rserve dynlib crash):maybe your logfile isnt complete!...which will be a bad thing:<br/>One reason is not correctly formatting your annotation files under mac, e.g. saving it as a dos text file will bring Rserve to make segfault<br/>another reason is the use of Rserve <0.6";
}
progressPercentage[0]=tempString+"<br/><br/> <FONT COLOR=\"red\">received error Messages:"+getErrorMsgFromRLogfile()+"</FONT>"+"<br/>";
progressPercentage[0]+="msg:"+msg+"<br/>errorDesc:"+requestErrorDesc+"<br/>returnCode:"+returnCode+"<br/>";
FileCreator.stringToFile(new File(rOutputScriptFile),debugString);
//add script to the results zip file
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General Rserve problem:\n"+" at step: "+step+"\n"+msg+" "+requestErrorDesc+" returncode:"+returnCode+"\nPlease get in contact with program maintainers",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
} catch (Exception e) {
progressPercentage[0]="101_General error occured: "+e.getMessage();
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
//try to close the outputstream
try {
//at the end of our run
//restore old values for the next one accessing the server :
//back to old dir
getRengine().voidEval("setwd(orgDir)");
}catch(RserveException e) {
progressPercentage[0]="101_Error occured setting original dir";
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
//uncomment try catch block for debugging
try {
//close the logging and the logfile
getRengine().voidEval("sink()");
}catch(RserveException e) {
progressPercentage[0]="101_Error occured closing the R_OUTPUTSTREAM:maybe your logfile isnt complete!...which will be a bad thing:\nOne reason is running Rserve binary on Mac Os X server.Check /var/log/system.log and search for a Rserve crash report";
sendNotificationToMaintainer(progressPercentage[0]+"\n"+e.getMessage(),jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
e.printStackTrace();
getRengine().close();
semaphore.v(threadID);
return;
}
//if were here we have won!
FileCreator.stringToFile(new File(rOutputScriptFile),debugString);
//zip the results
if(!createResultsZipFile()) {
progressPercentage[0] = "101_Error occured trying to zip the resultfiles!";
sendNotificationToMaintainer(progressPercentage[0], jobID);
sendNotificationToUser("General server problems. Please get in contact with program maintainers", jobID);
getRengine().close();
semaphore.v(threadID);
//TODO:put all the exceptions and stuff in a seperate return function where you stop the semaphore and close everything
return;
}
//finally close this R Server connection
getRengine().close();
semaphore.v(threadID);
//send results to email
if(this.emailNotification) {
String runName=this.extractRunName(stringParams.get("runNameDir"));
//create a recycable downloadlink as well...therefore we have to keep track about how often a file is allowed to be downloaded
//which we will write into a properties file
String dlPropertiesFile = Configuration.UPLOAD_PATH+stringParams.get("jobName")+"/.dlProperties";
String downloadLink = stringParams.get("emailDownloadLink");
//init a properties file
Properties propObj = new Properties();
//set the relation between runname and result zip file
propObj.setProperty(runName+"_RESULT_ZIP",resultZipFile);
//put in the properties file that we downloaded this runid zero times
propObj.setProperty(runName,"0");
//generate a password for downloading
String pw = PasswordGenerator.get(20);
propObj.setProperty(runName+"_password",pw);
try {
propObj.store(new FileOutputStream(new File(dlPropertiesFile)),"properties file for email Download information");
}catch(Exception e) {
e.printStackTrace();
}
//FileCreator.writeDownloadPropertiesFile(new File(dlPropertiesFile),runName,0);
String emailMsg="";//"Your job ID was: "+runName+'\n';
String file=null;
int percentage = Integer.parseInt(progressPercentage[0].split("_")[0]);
String msg = progressPercentage[0].split("_")[1];
if(percentage==100) {
emailMsg+="Dear cellHTS2 user,\n" +
"\n" +
"Please download the calculated results from your query from our server (you are allowed to do this "+stringParams.get("allowed-dl-numbers")+" times ) at:\n\n"
+downloadLink+"\n"+" with the password: "+pw+"\n\n"+
// "Please find attached the calculated results from your query. " +
"Save the file and unpack it using an unzip program.\n" +
"The \"index.html\" file can be opened by any web browser for view the analysis results. We have also included a session " +
"that can be used to modify analysis settings.\n" +
"\n" +
"Do not hesitate to contact us if you have any question or suggestions for improvement.\n" +
"\n" +
"Sincerely,\n" +
"\n" +
"web cellHTS Team\n" +
"Email: "+ this.maintainEmailAddress+"\n" +
"\n" +
"Please use the following citation when using cellHTS:\n" +
"Boutros, M., L. Bras, and W. Huber. (2006). Analysis of cell-based RNAi screens. Genome Biology 7:R66.\n"+
"Abstract: http://genomebiology.com/2006/7/7/R66\n"+
"Full Text: http://genomebiology.com/content/pdf/gb-2006-7-7-r66.pdf\n"+
"PubMed: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&cmd=Retrieve&dopt=AbstractPlus&list_uids=16869968";
file=resultZipFile;
}
else {
emailMsg+="Sorry, but your run was not successful! Error percentage: "+percentage+"\nSystem output:\n"+msg+"\nPlease consult the manual or ask the developers of this tool for help!";
file =null;
}
//create array of attachements
String sessionFile = stringParams.get("sessionFile");
if(sessionFile==null) {
return;
}
String []files = {file,sessionFile};
postMailTools.postMail( emailAddress,
"cellHTS2 report (\""+runName+"\"):",
emailMsg,
this.maintainEmailAddress,
null //file if we want to send the result as file
);
}
}
| public void run() {
String queueFullMsg;
queueFullMsg="99_queue is full, waiting for a free slot...hold on! (dont close the window)!";
threadID = getId();
//check if we still have place before running
semaphore.p(progressPercentage,queueFullMsg,threadID);
String jobID = stringParams.get("jobName");
//make a new connection to the R server Rserve
try {
RConnection c = new RConnection();
setRengine(c);
}catch(Exception e) {
String exceptionText = "failed making connection to Rserver maybe you forgot to start it \"R CMD Rserve\" ";//)+e.printStackTrace());
exceptionText+="Note: this currently only works starting the RServer on the same server as this java is started from";
progressPercentage[0]="101_"+exceptionText;
e.printStackTrace();
sendNotificationToMaintainer(e.getMessage(),jobID);
sendNotificationToUser("General server problems. Please get in contact with program maintainers",jobID);
return;
//throw new TapestryException(exceptionText, null);
}
String debugString="";
String cmdString;
String outputDir = stringParams.get("runNameDir");
try {
//TODO: this code is ugly and not elegant. Better: write the R Script into a file with VARIABLE SPACERS, load it here and replace all the spacers with the settings here
//store original location where we started r
cmdString= "orgDir=getwd()";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//first we have to change to the Indir in order to make the R cellHTS script working
cmdString= "setwd(\""+Configuration.UPLOAD_PATH+stringParams.get("jobName")+"\")";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//assign java variables to our R interface
cmdString="Indir=\""+Configuration.UPLOAD_PATH+stringParams.get("jobName")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Indir", Configuration.UPLOAD_PATH+stringParams.get("jobName"));
//create a outputfile for the results under the "root" out dir ..thats the only location where it is sure
//that we have rite permissions!
stringParams.put("outputDir",outputDir);
String evalOutput = "dir.create(\""+outputDir+"\", recursive = TRUE)";
getRengine().voidEval(evalOutput);
rOutputFile=outputDir+"/R_OUTPUT.TXT";
rOutputScriptFile=outputDir+"/R_OUTPUT.SCRIPT";
//getRengine().voidEval("options(warn=1)");
String openFile = "zz <- file(\""+rOutputFile+"\", open=\"w\")";
cmdString=openFile ;
debugString+=cmdString+"\n";
getRengine().voidEval(openFile);
//comment the next three lines for debugging
//get messages not the output!
String sinkMsg= "sink(file=zz,type=\"message\" )";
cmdString=sinkMsg ;
debugString+=cmdString+"\n";
getRengine().voidEval(sinkMsg);
//how to call the htmls result page
cmdString="Name=\""+stringParams.get("htmlResultName")+"\"";
debugString+=cmdString+"\n";
getRengine().assign("Name", stringParams.get("htmlResultName"));
cmdString="Outdir_report=\""+outputDir+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Outdir_report", outputDir);
//R has boolean support which is TRUE and FALSE and NOT! Strings "TRUE" or "FALSE"
if(stringParams.get("logTransform").equals("NO")) {
cmdString="LogTransform=FALSE" ;
debugString+=cmdString+"\n";
getRengine().voidEval("LogTransform=FALSE");
}
else {
cmdString="LogTransform=TRUE" ;
debugString+=cmdString+"\n";
getRengine().voidEval("LogTransform=TRUE");
}
cmdString= "PlateList=\""+stringParams.get("plateList")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("PlateList", stringParams.get("plateList"));
cmdString="Plateconf=\""+stringParams.get("plateConf")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Plateconf", stringParams.get("plateConf"));
cmdString="Description=\""+stringParams.get("descriptionFile")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Description", stringParams.get("descriptionFile")); //if we did not submit one we will generate one automaically
cmdString="NormalizationMethod=\""+stringParams.get("normalMethod")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("NormalizationMethod", stringParams.get("normalMethod"));
cmdString="NormalizationScaling=\""+stringParams.get("normalScaling")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("NormalizationScaling", stringParams.get("normalScaling"));
cmdString= "VarianceAdjust=\""+stringParams.get("varianceAdjust")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("VarianceAdjust", stringParams.get("varianceAdjust"));
cmdString="SummaryMethod=\""+stringParams.get("summaryMethod")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("SummaryMethod", stringParams.get("summaryMethod"));
cmdString= "Screenlog=\""+stringParams.get("screenLogFile")+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Screenlog",stringParams.get("screenLogFile"));
//this should not be selected from the menue ...TODO: maybe we should add it later
cmdString="Score=\""+Configuration.scoreReplicates+"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Score",Configuration.scoreReplicates);
if (stringParams.get("annotFile") != null) {
cmdString="Annotation=\""+stringParams.get("annotFile") +"\"" ;
debugString+=cmdString+"\n";
getRengine().assign("Annotation", stringParams.get("annotFile"));
}
//TODO:make case here single channel or dual channel script
try {
if (stringParams.get("channelTypes").equals("single")) {
//TODO: this is somehow ugly code and could be more beautiful..it was written under time pressure :-(
//TODO: check if the REXP isnull checking works at all
progressPercentage[0]="15_loading cellHTS2 lib";
cmdString="library(cellHTS2)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="20_reading plate list";
cmdString="x=readPlateList(PlateList, name = Name, path = Indir)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="25_configuring layout";
cmdString="x=configure(x, descripFile=Description, confFile=Plateconf, logFile=Screenlog)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="45_normalizing plates";
cmdString="xn=normalizePlates(x, scale =NormalizationScaling , log =LogTransform,method=NormalizationMethod, varianceAdjust=VarianceAdjust)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="47_comparing to cellHTS";
cmdString="comp=compare2cellHTS(x, xn)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="50_scoring replicates";
cmdString="xsc=scoreReplicates(xn, sign = \"-\", method = Score)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="60_summerizing replicates";
cmdString="xsc=summarizeReplicates(xsc, summary = SummaryMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="65_scoring data";
cmdString="scores=Data(xsc)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="80_quantiling";
cmdString="ylim=quantile(scores, c(0.001, 0.999), na.rm = TRUE)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="81_writing the report....";
if (stringParams.get("annotFile") != null) {
progressPercentage[0]="82_annotating data";
cmdString="xsc=annotate(xsc, geneIDFile = Annotation)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
progressPercentage[0]="85_writing the output";
//this is for cellHTS2 < 2.7.9
// getRengine().voidEval("out = writeReport(cellHTSlist = list(raw = x, normalized = xn, scored = xsc), outdir = Outdir_report, force = TRUE, plotPlateArgs = list(xrange = c(0.5,3)), imageScreenArgs = list(zrange = c(-4, 8), ar = 1),,progressReport=FALSE)");
//this is for the new cellHTS2 >= 2.7.9
cmdString="out=writeReport(raw = x, normalized = xn, scored = xsc, outdir = Outdir_report, force = TRUE, settings = list(xrange = c(0.5,3),zrange = c(-4, 8), ar = 1))";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="100_successfully done";
successBool[0]=true;
} else {
//this is the path for dual channel scripts
progressPercentage[0]="15_loading cellHTS2 lib";
cmdString="library(\"cellHTS2\")";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="20_reading plate list";
cmdString="x = readPlateList(PlateList,name=Name,path=Indir)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="25_configuring layout";
cmdString="x = configure(x , descripFile=Description, confFile=Plateconf, logFile=Screenlog)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="45_normalizing plates";
cmdString="xp = normalizePlates(x, log=LogTransform, scale=NormalizationScaling, method=NormalizationMethod, varianceAdjust=VarianceAdjust)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="60_summerizing channels";
if(stringParams.get("viabilityChannel").equals("NO")) {
cmdString="xs = summarizeChannels(xp)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
else {
if(stringParams.get("viabilityFunction")!=null) {
cmdString ="ViabilityMethod = "+stringParams.get("viabilityFunction");
}
else {
//this is our standard viability function
cmdString="ViabilityMethod = function(r1, r2) {ifelse(r2>(-1), -r1, NA)}";
}
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
cmdString="xs = summarizeChannels(xp, fun = ViabilityMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
cmdString="xn = xs";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
cmdString="xn@state[\"normalized\"] = TRUE";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="65_scoring replicates";
cmdString="xsc = scoreReplicates(xn, sign = \"-\", method = Score)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="70_summerizing replicates";
cmdString="xsc = summarizeReplicates(xsc, summary = SummaryMethod)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
progressPercentage[0]="75_writing the report....";
if (stringParams.get("annotFile") != null) {
progressPercentage[0]="78_annotating data";
cmdString="xsc = annotate(xsc, geneIDFile = Annotation)";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
}
progressPercentage[0]="76_writing the output";
//this is for cellHTS2 < 2.7.9
//getRengine().voidEval("out = writeReport(cellHTSlist = list(raw = x, normalized = xn, scored = xsc),imageScreenArgs = list(zrange = c(-4, 4)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE ,progressReport=FALSE)");
//this is for the new cellHTS2 >= 2.7.9
cmdString="out = writeReport(raw = x, normalized = xn, scored = xsc,settings = list(zrange = c(-4, 4),xrange = c(0.5,3)), plotPlateArgs=list(), outdir=Outdir_report, force=TRUE )";
debugString+=cmdString+"\n";
getRengine().voidEval(cmdString);
//after we are done...create a zipfile out of the results
progressPercentage[0]="100_successfully done";
successBool[0]=true;
}
}catch(RserveException e) {
String step = progressPercentage[0].split("_")[1];
String tempString="101_Error occured at step:"+step+"<br/>Please consult R logfile under:<br/>"+rOutputFile+"<br/> if debugging is on also run the script "+rOutputScriptFile ;
//close the logging and the logfile before printing it or you will lose information!
String msg = e.getMessage();
String requestErrorDesc = e.getRequestErrorDescription();
int returnCode = e.getRequestReturnCode();
//uncomment try catch block for debugging
try {
getRengine().voidEval("sink()");
} catch(RserveException re) {
tempString+=" <br/>AND Error occured closing the R_OUTPUTSTREAM (this will be 99% caused by a Rserve dynlib crash):maybe your logfile isnt complete!...which will be a bad thing:<br/>One reason is not correctly formatting your annotation files under mac, e.g. saving it as a dos text file will bring Rserve to make segfault<br/>another reason is the use of Rserve <0.6";
}
progressPercentage[0]=tempString+"<br/><br/> <FONT COLOR=\"red\">received error Messages:"+getErrorMsgFromRLogfile()+"</FONT>"+"<br/>";
progressPercentage[0]+="msg:"+msg+"<br/>errorDesc:"+requestErrorDesc+"<br/>returnCode:"+returnCode+"<br/>";
FileCreator.stringToFile(new File(rOutputScriptFile),debugString);
//add script to the results zip file
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General Rserve problem:\n"+" at step: "+step+"\n"+msg+" "+requestErrorDesc+" returncode:"+returnCode+"\nPlease get in contact with program maintainers",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
} catch (Exception e) {
progressPercentage[0]="101_General error occured: "+e.getMessage();
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
//try to close the outputstream
try {
//at the end of our run
//restore old values for the next one accessing the server :
//back to old dir
getRengine().voidEval("setwd(orgDir)");
}catch(RserveException e) {
progressPercentage[0]="101_Error occured setting original dir";
sendNotificationToMaintainer(progressPercentage[0],jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
getRengine().close();
semaphore.v(threadID);
return;
}
//uncomment try catch block for debugging
try {
//close the logging and the logfile
getRengine().voidEval("sink()");
}catch(RserveException e) {
progressPercentage[0]="101_Error occured closing the R_OUTPUTSTREAM:maybe your logfile isnt complete!...which will be a bad thing:\nOne reason is running Rserve binary on Mac Os X server.Check /var/log/system.log and search for a Rserve crash report";
sendNotificationToMaintainer(progressPercentage[0]+"\n"+e.getMessage(),jobID);
sendNotificationToUser("General exception occured. Please get in contact with a program maintainer soon",jobID);
e.printStackTrace();
getRengine().close();
semaphore.v(threadID);
return;
}
//if were here we have won!
FileCreator.stringToFile(new File(rOutputScriptFile),debugString);
//zip the results
if(!createResultsZipFile()) {
progressPercentage[0] = "101_Error occured trying to zip the resultfiles!";
sendNotificationToMaintainer(progressPercentage[0], jobID);
sendNotificationToUser("General server problems. Please get in contact with program maintainers", jobID);
getRengine().close();
semaphore.v(threadID);
//TODO:put all the exceptions and stuff in a seperate return function where you stop the semaphore and close everything
return;
}
//finally close this R Server connection
getRengine().close();
semaphore.v(threadID);
//send results to email
if(this.emailNotification) {
String runName=this.extractRunName(stringParams.get("runNameDir"));
//create a recycable downloadlink as well...therefore we have to keep track about how often a file is allowed to be downloaded
//which we will write into a properties file
String dlPropertiesFile = Configuration.UPLOAD_PATH+stringParams.get("jobName")+"/.dlProperties";
String downloadLink = stringParams.get("emailDownloadLink");
//init a properties file
Properties propObj = new Properties();
//set the relation between runname and result zip file
propObj.setProperty(runName+"_RESULT_ZIP",resultZipFile);
//put in the properties file that we downloaded this runid zero times
propObj.setProperty(runName,"0");
//generate a password for downloading
String pw = PasswordGenerator.get(20);
propObj.setProperty(runName+"_password",pw);
try {
propObj.store(new FileOutputStream(new File(dlPropertiesFile)),"properties file for email Download information");
}catch(Exception e) {
e.printStackTrace();
}
//FileCreator.writeDownloadPropertiesFile(new File(dlPropertiesFile),runName,0);
String emailMsg="";//"Your job ID was: "+runName+'\n';
String file=null;
int percentage = Integer.parseInt(progressPercentage[0].split("_")[0]);
String msg = progressPercentage[0].split("_")[1];
if(percentage==100) {
emailMsg+="Dear cellHTS2 user,\n" +
"\n" +
"Please download the calculated results from your query from our server (you are allowed to do this "+stringParams.get("allowed-dl-numbers")+" times ) at:\n\n"
+downloadLink+"\n"+" with the password: "+pw+"\n\n"+
// "Please find attached the calculated results from your query. " +
"Save the file and unpack it using an unzip program.\n" +
"The \"index.html\" file can be opened by any web browser for view the analysis results. We have also included a session " +
"that can be used to modify analysis settings.\n" +
"\n" +
"Do not hesitate to contact us if you have any question or suggestions for improvement.\n" +
"\n" +
"Sincerely,\n" +
"\n" +
"web cellHTS Team\n" +
"Email: "+ this.maintainEmailAddress+"\n" +
"\n" +
"Please use the following citation when using cellHTS:\n" +
"Boutros, M., L. Bras, and W. Huber. (2006). Analysis of cell-based RNAi screens. Genome Biology 7:R66.\n"+
"Abstract: http://genomebiology.com/2006/7/7/R66\n"+
"Full Text: http://genomebiology.com/content/pdf/gb-2006-7-7-r66.pdf\n"+
"PubMed: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&cmd=Retrieve&dopt=AbstractPlus&list_uids=16869968";
file=resultZipFile;
}
else {
emailMsg+="Sorry, but your run was not successful! Error percentage: "+percentage+"\nSystem output:\n"+msg+"\nPlease consult the manual or ask the developers of this tool for help!";
file =null;
}
//create array of attachements
String sessionFile = stringParams.get("sessionFile");
if(sessionFile==null) {
return;
}
String []files = {file,sessionFile};
postMailTools.postMail( emailAddress,
"cellHTS2 report (\""+runName+"\"):",
emailMsg,
this.maintainEmailAddress,
null //file if we want to send the result as file
);
}
}
|
diff --git a/src/com/project4/FilterPlayGround/AbstractFilterBox.java b/src/com/project4/FilterPlayGround/AbstractFilterBox.java
index c9d0d47..819b0d4 100644
--- a/src/com/project4/FilterPlayGround/AbstractFilterBox.java
+++ b/src/com/project4/FilterPlayGround/AbstractFilterBox.java
@@ -1,154 +1,154 @@
package com.project4.FilterPlayGround;
import java.util.ArrayList;
import com.anotherbrick.inthewall.Config.MyColorEnum;
import com.anotherbrick.inthewall.TouchEnabled;
import com.anotherbrick.inthewall.VizButton;
import com.anotherbrick.inthewall.VizPanel;
import com.project4.FilterPlayGround.serializables.AbstractSerializableBox;
public abstract class AbstractFilterBox extends VizPanel implements TouchEnabled {
protected BoxConnectorIngoing inputConnector;
protected BoxConnectorOutgoing outputConnector;
private Integer id = 0;
protected MyColorEnum COLOR = MyColorEnum.DARK_WHITE;
public AbstractBoxConnector getInputConnector() {
return inputConnector;
}
public AbstractBoxConnector getOutputConnector() {
return outputConnector;
}
public float CONNECTOR_SIZE = 20;
public float REMOVE_BUTTON_DEFAULT_X = 60;
public float REMOVE_BUTTON_DEFAULT_Y = 25;
public float REMOVE_BUTTON_DEFAULT_HEIGHT = 12;
public float REMOVE_BUTTON_DEFAULT_WIDTH = 26;
public AbstractFilterBox(float x0, float y0, float width, float height, VizPanel parent) {
super(x0, y0, width, height, parent);
inputConnector =
new BoxConnectorIngoing(0, getHeight() / 2, CONNECTOR_SIZE, CONNECTOR_SIZE, this);
}
public abstract boolean needKeyboard();
public float getRemoveX() {
return REMOVE_BUTTON_DEFAULT_X;
}
public float getRemoveY() {
return REMOVE_BUTTON_DEFAULT_Y;
}
protected VizButton removeButton;
private ArrayList<AbstractFilterBox> ingoingConnections = new ArrayList<AbstractFilterBox>();
public void addIngoingConnection(AbstractFilterBox afb) {
ingoingConnections.add(afb);
}
public void removeIngoingConnection(AbstractFilterBox afb) {
ingoingConnections.remove(afb);
}
public abstract String getFilter();
float spanX;
float spanY;
public boolean draw() {
pushStyle();
background(COLOR);
inputConnector.draw();
if (!isTerminal()) {
outputConnector.draw();
}
removeButton.draw();
popStyle();
if (dragging) {
- modifyPositionWithAbsoluteValue(m.touchX, m.touchY);
+ modifyPositionWithAbsoluteValue(m.touchX - spanX, m.touchY - spanY);
}
return false;
}
@Override
public void setup() {
removeButton =
new VizButton(getRemoveX(), getRemoveY(), REMOVE_BUTTON_DEFAULT_WIDTH,
REMOVE_BUTTON_DEFAULT_HEIGHT, this);
removeButton.setText("Canc");
removeButton.setStyle(MyColorEnum.LIGHT_GRAY, MyColorEnum.WHITE, MyColorEnum.DARK_GRAY, 255f,
255f, 10);
removeButton.setStylePressed(MyColorEnum.MEDIUM_GRAY, MyColorEnum.WHITE, MyColorEnum.DARK_GRAY,
255f, 10);
addTouchSubscriber(removeButton);
}
@Override
public void modifyPosition(float newX0, float newY0) {
super.modifyPosition(newX0, newY0);
inputConnector.modifyPosition(0, getHeight() / 2);
if (!isTerminal()) outputConnector.modifyPosition(getWidth(), getHeight() / 2);
removeButton.modifyPosition(getRemoveX(), getRemoveY());
}
@Override
public void modifyPositionWithAbsoluteValue(float newX0, float newY0) {
super.modifyPositionWithAbsoluteValue(newX0, newY0);
inputConnector.modifyPosition(0, getHeight() / 2);
if (!isTerminal()) outputConnector.modifyPosition(getWidth(), getHeight() / 2);
removeButton.modifyPosition(getRemoveX(), getRemoveY());
}
public ArrayList<AbstractFilterBox> getIngoingConnections() {
return ingoingConnections;
}
private boolean focus = false;
public void setFocus(boolean focus) {
this.focus = focus;
}
public boolean hasFocus() {
return focus;
}
private boolean dragging = false;
public boolean touch(float x, float y, boolean down, TouchTypeEnum touchType) {
if (down) {
dragging = true;
// setModal(true);
spanX = m.touchX - getX0Absolute();
spanY = m.touchY - getY0Absolute();
} else {
dragging = false;
// setModal(false);
}
return false;
}
public abstract boolean isTerminal();
public abstract AbstractSerializableBox serialize();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
removeButton.name = id + "|" + "remove";
}
}
| true | true | public boolean draw() {
pushStyle();
background(COLOR);
inputConnector.draw();
if (!isTerminal()) {
outputConnector.draw();
}
removeButton.draw();
popStyle();
if (dragging) {
modifyPositionWithAbsoluteValue(m.touchX, m.touchY);
}
return false;
}
| public boolean draw() {
pushStyle();
background(COLOR);
inputConnector.draw();
if (!isTerminal()) {
outputConnector.draw();
}
removeButton.draw();
popStyle();
if (dragging) {
modifyPositionWithAbsoluteValue(m.touchX - spanX, m.touchY - spanY);
}
return false;
}
|
diff --git a/web/spring/src/test/java/org/appfuse/webapp/action/BaseControllerTestCase.java b/web/spring/src/test/java/org/appfuse/webapp/action/BaseControllerTestCase.java
index a31c6d66..92da9c17 100644
--- a/web/spring/src/test/java/org/appfuse/webapp/action/BaseControllerTestCase.java
+++ b/web/spring/src/test/java/org/appfuse/webapp/action/BaseControllerTestCase.java
@@ -1,116 +1,121 @@
package org.appfuse.webapp.action;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.BaseObject;
import org.appfuse.model.User;
import org.appfuse.service.UserManager;
import org.appfuse.util.DateUtil;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
public abstract class BaseControllerTestCase extends TestCase {
protected transient final Log log = LogFactory.getLog(getClass());
protected static XmlWebApplicationContext ctx;
protected User user;
// This static block ensures that Spring's BeanFactory is only loaded
// once for all tests
static {
String[] paths = {
"classpath*:/applicationContext-dao.xml",
"classpath*:/applicationContext-service.xml",
"/WEB-INF/applicationContext-resources.xml",
"/WEB-INF/applicationContext-validation.xml",
"/WEB-INF/action-servlet.xml"
};
ctx = new XmlWebApplicationContext();
ctx.setConfigLocations(paths);
ctx.setServletContext(new MockServletContext(""));
ctx.refresh();
}
protected void setUp() throws Exception {
// populate the userForm and place into session
UserManager userMgr = (UserManager) ctx.getBean("userManager");
user = (User) userMgr.getUserByUsername("tomcat");
// change the port on the mailSender so it doesn't conflict with an
// existing SMTP server on localhost
JavaMailSenderImpl mailSender = (JavaMailSenderImpl) ctx.getBean("mailSender");
mailSender.setPort(2525);
mailSender.setHost("localhost");
}
/**
* Convenience methods to make tests simpler
*/
public MockHttpServletRequest newPost(String url) {
return new MockHttpServletRequest("POST", url);
}
public MockHttpServletRequest newGet(String url) {
return new MockHttpServletRequest("GET", url);
}
public void objectToRequestParameters(Object o, MockHttpServletRequest request) throws Exception {
objectToRequestParameters(o, request, null);
}
public void objectToRequestParameters(Object o, MockHttpServletRequest request, String prefix) throws Exception {
Class clazz = o.getClass();
Field[] fields = getDeclaredFields(clazz);
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length; i++) {
Object field = (fields[i].get(o));
if (field != null) {
if (field instanceof BaseObject) {
- objectToRequestParameters(field, request, fields[i].getName());
+ // Fix for http://issues.appfuse.org/browse/APF-429
+ if (prefix != null) {
+ objectToRequestParameters(field, request, prefix + "." + fields[i].getName());
+ } else {
+ objectToRequestParameters(field, request, fields[i].getName());
+ }
} else if (!(field instanceof List) && !(field instanceof Set)) {
String paramName = fields[i].getName();
if (prefix != null) {
paramName = prefix + "." + paramName;
}
String paramValue = String.valueOf(fields[i].get(o));
// handle Dates
if (field instanceof java.util.Date) {
paramValue = DateUtil.convertDateToString((Date)fields[i].get(o));
if ("null".equals(paramValue)) paramValue = "";
}
request.addParameter(paramName, paramValue);
}
}
}
}
private Field[] getDeclaredFields(Class clazz) {
Field[] f = new Field[0];
Class superClazz = clazz.getSuperclass();
Collection rval = new ArrayList();
if (superClazz != null) {
rval.addAll(Arrays.asList(getDeclaredFields(superClazz)));
}
rval.addAll(Arrays.asList(clazz.getDeclaredFields()));
return (Field[]) rval.toArray(f);
}
}
| true | true | public void objectToRequestParameters(Object o, MockHttpServletRequest request, String prefix) throws Exception {
Class clazz = o.getClass();
Field[] fields = getDeclaredFields(clazz);
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length; i++) {
Object field = (fields[i].get(o));
if (field != null) {
if (field instanceof BaseObject) {
objectToRequestParameters(field, request, fields[i].getName());
} else if (!(field instanceof List) && !(field instanceof Set)) {
String paramName = fields[i].getName();
if (prefix != null) {
paramName = prefix + "." + paramName;
}
String paramValue = String.valueOf(fields[i].get(o));
// handle Dates
if (field instanceof java.util.Date) {
paramValue = DateUtil.convertDateToString((Date)fields[i].get(o));
if ("null".equals(paramValue)) paramValue = "";
}
request.addParameter(paramName, paramValue);
}
}
}
}
| public void objectToRequestParameters(Object o, MockHttpServletRequest request, String prefix) throws Exception {
Class clazz = o.getClass();
Field[] fields = getDeclaredFields(clazz);
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length; i++) {
Object field = (fields[i].get(o));
if (field != null) {
if (field instanceof BaseObject) {
// Fix for http://issues.appfuse.org/browse/APF-429
if (prefix != null) {
objectToRequestParameters(field, request, prefix + "." + fields[i].getName());
} else {
objectToRequestParameters(field, request, fields[i].getName());
}
} else if (!(field instanceof List) && !(field instanceof Set)) {
String paramName = fields[i].getName();
if (prefix != null) {
paramName = prefix + "." + paramName;
}
String paramValue = String.valueOf(fields[i].get(o));
// handle Dates
if (field instanceof java.util.Date) {
paramValue = DateUtil.convertDateToString((Date)fields[i].get(o));
if ("null".equals(paramValue)) paramValue = "";
}
request.addParameter(paramName, paramValue);
}
}
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java
index 9e761de0..a2fa3057 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java
@@ -1,261 +1,264 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2005 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Abstract class for chekcs which need to collect information about
* declared members/parameters/variables.
*
* @author o_sukhodolsky
*/
public abstract class DeclarationCollector extends Check
{
/** Stack of variable declaration frames. */
private FrameStack mFrames;
/** {@inheritDoc} */
public void beginTree(DetailAST aRootAST)
{
mFrames = new FrameStack();
}
/** {@inheritDoc} */
public void visitToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.PARAMETER_DEF :
case TokenTypes.VARIABLE_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
break;
}
- case TokenTypes.CLASS_DEF : {
+ case TokenTypes.CLASS_DEF :
+ case TokenTypes.INTERFACE_DEF :
+ case TokenTypes.ENUM_DEF :
+ case TokenTypes.ANNOTATION_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
this.mFrames.enter(new ClassFrame());
break;
}
case TokenTypes.SLIST :
this.mFrames.enter(new BlockFrame());
break;
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.enter(new MethodFrame());
break;
default:
// do nothing
}
}
/** {@inheritDoc} */
public void leaveToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.CLASS_DEF :
case TokenTypes.INTERFACE_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ANNOTATION_DEF :
case TokenTypes.SLIST :
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.leave();
break;
default :
// do nothing
}
}
/**
* Check if given name is a name for declafred variable/parameter/member in
* current environment.
* @param aName a name to check
* @return true is the given name is declare one.
*/
protected final boolean isDeclared(String aName)
{
return (null != mFrames.findFrame(aName));
}
/**
* Check if given name is a name for class field in current environment.
* @param aName a name to check
* @return true is the given name is name of method or member.
*/
protected final boolean isClassField(String aName)
{
return (mFrames.findFrame(aName) instanceof ClassFrame);
}
}
/**
* A declaration frame.
* @author Stephen Bloch
* June 19, 2003
*/
abstract class LexicalFrame
{
/** Set of name of variables declared in this frame. */
private HashSet mVarNames;
/** constructor -- invocable only via super() from subclasses */
protected LexicalFrame()
{
mVarNames = new HashSet();
}
/** add a name to the frame.
* @param aNameToAdd the name we're adding
*/
void addName(String aNameToAdd)
{
this.mVarNames.add(aNameToAdd);
}
/** check whether the frame contains a given name.
* @param aNameToFind the name we're looking for
* @return whether it was found
*/
boolean contains(String aNameToFind)
{
return this.mVarNames.contains(aNameToFind);
}
}
/**
* The global frame; should hold only class names.
* @author Stephen Bloch
*/
class GlobalFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
GlobalFrame()
{
super();
}
}
/**
* A frame initiated at method definition; holds parameter names.
* @author Stephen Bloch
*/
class MethodFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
MethodFrame()
{
super();
}
}
/**
* A frame initiated at class definition; holds instance variable
* names. For the present, I'm not worried about other class names,
* method names, etc.
* @author Stephen Bloch
*/
class ClassFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
ClassFrame()
{
super();
}
}
/**
* A frame initiated on entering a statement list; holds local variable
* names. For the present, I'm not worried about other class names,
* method names, etc.
* @author Stephen Bloch
*/
class BlockFrame extends LexicalFrame
{
/** Create new instance of hte frame. */
BlockFrame()
{
super();
}
}
/**
* A stack of LexicalFrames. Standard issue....
* @author Stephen Bloch
*/
class FrameStack
{
/** List of lexical frames. */
private LinkedList mFrameList;
/** Creates an empty FrameStack. */
FrameStack()
{
mFrameList = new LinkedList();
this.enter(new GlobalFrame());
}
/**
* Enter a scope, i.e. push a frame on the stack.
* @param aNewFrame the already-created frame to push
*/
void enter(LexicalFrame aNewFrame)
{
mFrameList.addFirst(aNewFrame);
}
/** Leave a scope, i.e. pop a frame from the stack. */
void leave()
{
mFrameList.removeFirst();
}
/**
* Get current scope, i.e. top frame on the stack.
* @return the current frame
*/
LexicalFrame current()
{
return (LexicalFrame) mFrameList.getFirst();
}
/**
* Search this and containing frames for a given name.
* @param aNameToFind the name we're looking for
* @return the frame in which it was found, or null if not found
*/
LexicalFrame findFrame(String aNameToFind)
{
final Iterator it = mFrameList.iterator();
while (it.hasNext()) {
final LexicalFrame thisFrame = (LexicalFrame) it.next();
if (thisFrame.contains(aNameToFind)) {
return thisFrame;
}
}
return null;
}
}
| true | true | public void visitToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.PARAMETER_DEF :
case TokenTypes.VARIABLE_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
break;
}
case TokenTypes.CLASS_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
this.mFrames.enter(new ClassFrame());
break;
}
case TokenTypes.SLIST :
this.mFrames.enter(new BlockFrame());
break;
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.enter(new MethodFrame());
break;
default:
// do nothing
}
}
| public void visitToken(DetailAST aAST)
{
switch (aAST.getType()) {
case TokenTypes.PARAMETER_DEF :
case TokenTypes.VARIABLE_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
break;
}
case TokenTypes.CLASS_DEF :
case TokenTypes.INTERFACE_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ANNOTATION_DEF : {
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
this.mFrames.current().addName(nameAST.getText());
this.mFrames.enter(new ClassFrame());
break;
}
case TokenTypes.SLIST :
this.mFrames.enter(new BlockFrame());
break;
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
this.mFrames.enter(new MethodFrame());
break;
default:
// do nothing
}
}
|
diff --git a/src/com/cse454/nel/DocumentProcessor.java b/src/com/cse454/nel/DocumentProcessor.java
index ca33079..1dcaa50 100644
--- a/src/com/cse454/nel/DocumentProcessor.java
+++ b/src/com/cse454/nel/DocumentProcessor.java
@@ -1,39 +1,39 @@
package com.cse454.nel;
import java.sql.SQLException;
import java.util.List;
import com.cse454.nel.disambiguate.AbstractDisambiguator;
import com.cse454.nel.disambiguate.SimpleDisambiguator;
import com.cse454.nel.extract.AbstractEntityExtractor;
import com.cse454.nel.extract.EntityExtractor;
import com.cse454.nel.search.AbstractSearcher;
import com.cse454.nel.search.BasicSearcher;
public class DocumentProcessor {
private final int docID;
public DocumentProcessor(int docID) throws SQLException {
this.docID = docID;
}
public void run() throws SQLException {
- WikiConnect wiki = new WikiConnect();
- List<Sentence> sentences = wiki.getFile(this.docID);
+ SentenceConnect docs = new SentenceConnect();
+ List<Sentence> sentences = docs.getDocument(this.docID);
AbstractEntityExtractor extractor = new EntityExtractor();
List<EntityMention> mentions = extractor.extract(sentences);
AbstractSearcher searcher = new BasicSearcher();
for (EntityMention mention : mentions) {
searcher.GetCandidateEntities(mention);
}
AbstractDisambiguator disambiguator = new SimpleDisambiguator();
disambiguator.disambiguate(mentions);
// TODO: output entities to file
}
}
| true | true | public void run() throws SQLException {
WikiConnect wiki = new WikiConnect();
List<Sentence> sentences = wiki.getFile(this.docID);
AbstractEntityExtractor extractor = new EntityExtractor();
List<EntityMention> mentions = extractor.extract(sentences);
AbstractSearcher searcher = new BasicSearcher();
for (EntityMention mention : mentions) {
searcher.GetCandidateEntities(mention);
}
AbstractDisambiguator disambiguator = new SimpleDisambiguator();
disambiguator.disambiguate(mentions);
// TODO: output entities to file
}
| public void run() throws SQLException {
SentenceConnect docs = new SentenceConnect();
List<Sentence> sentences = docs.getDocument(this.docID);
AbstractEntityExtractor extractor = new EntityExtractor();
List<EntityMention> mentions = extractor.extract(sentences);
AbstractSearcher searcher = new BasicSearcher();
for (EntityMention mention : mentions) {
searcher.GetCandidateEntities(mention);
}
AbstractDisambiguator disambiguator = new SimpleDisambiguator();
disambiguator.disambiguate(mentions);
// TODO: output entities to file
}
|
diff --git a/src/resources/directory/src/java/org/wyona/yanel/impl/resources/DirectoryResource.java b/src/resources/directory/src/java/org/wyona/yanel/impl/resources/DirectoryResource.java
index 20d76ddff..4ce49bc70 100644
--- a/src/resources/directory/src/java/org/wyona/yanel/impl/resources/DirectoryResource.java
+++ b/src/resources/directory/src/java/org/wyona/yanel/impl/resources/DirectoryResource.java
@@ -1,247 +1,247 @@
/*
* Copyright 2006 Wyona
*
* 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.wyona.org/licenses/APACHE-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.wyona.yanel.impl.resources;
import org.wyona.yanel.core.Path;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import javax.servlet.http.HttpServletRequest;
import org.wyona.yarep.core.NoSuchNodeException;
import org.wyona.yarep.core.RepositoryException;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryFactory;
import org.wyona.yarep.util.RepoPath;
import org.wyona.yanel.core.util.PathUtil;
import org.apache.log4j.Category;
import java.io.ByteArrayInputStream;
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import java.util.Iterator;
import java.util.LinkedHashSet;
/**
*
*/
public class DirectoryResource extends Resource implements ViewableV2 {
private static Category log = Category.getInstance(DirectoryResource.class);
/**
*
*/
public DirectoryResource() {
}
/**
*
*/
public ViewDescriptor[] getViewDescriptors() {
return null;
}
/**
*
*/
public View getView(String viewId) {
View defaultView = new View();
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
// sb.append("<?xml-stylesheet type=\"text/xsl\"
// href=\"yanel/resources/directory/xslt/dir2xhtml.xsl\"?>");
Repository contentRepo = null;
try {
contentRepo = getRealm().getRepository();
org.wyona.yarep.core.Path p = new org.wyona.yarep.core.Path(getPath());
// TODO: This doesn't seem to work ... (check on Yarep ...)
if (contentRepo.isResource(p)) {
log.warn("Path is a resource instead of a collection: " + p);
// p = p.getParent();
}
// TODO: Implement org.wyona.yarep.core.Path.getParent()
if (!contentRepo.isCollection(p)) {
log.warn("Path is not a collection: " + p);
p = new org.wyona.yarep.core.Path(new org.wyona.commons.io.Path(p.toString()).getParent().toString());
log.warn("Use parent of path: " + p);
}
// TODO: Add realm prefix, e.g. realm-prefix="ulysses-demo"
// NOTE: The schema is according to
// http://cocoon.apache.org/2.1/userdocs/directory-generator.html
sb.append("<dir:directory yanel:path=\""
+ getPath()
+ "\" dir:name=\""
+ p.getName()
+ "\" dir:path=\""
+ p
+ "\" xmlns:dir=\"http://apache.org/cocoon/directory/2.0\" xmlns:yanel=\"http://www.wyona.org/yanel/resource/directory/1.0\">");
// TODO: Do not show the children with suffix .yanel-rti resp. make
// this configurable!
// NOTE: Do not hardcode the .yanel-rti, but rather use
// Path.getRTIPath ...
org.wyona.yarep.core.Path[] children = contentRepo.getChildren(p);
for (int i = 0; i < children.length; i++) {
if (contentRepo.isResource(children[i])) {
sb.append("<dir:file path=\"" + children[i] + "\" name=\"" + children[i].getName() + "\"/>");
} else if (contentRepo.isCollection(children[i])) {
sb.append("<dir:directory path=\"" + children[i] + "\" name=\"" + children[i].getName() + "\"/>");
} else {
sb.append("<yanel:exception yanel:path=\"" + children[i] + "\"/>");
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
sb.append("</dir:directory>");
if (viewId != null && viewId.equals("source")) {
defaultView.setMimeType("application/xml");
defaultView.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
return defaultView;
}
try {
String assetPath = "";
- if (getPath().endsWith("/")) {
+ if (getPath().endsWith("/") && !isRoot(getPath())) {
assetPath = "../";
}
TransformerFactory tfactory = TransformerFactory.newInstance();
String[] xsltTransformers = getXSLTprop();
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
Transformer transformerIntern = tfactory.newTransformer(getXSLTStreamSource( contentRepo));
StreamSource orig = new StreamSource(new java.io.StringBufferInputStream(sb.toString()));
transformerIntern.setParameter("yanel.path.name", PathUtil.getName(getPath()));
transformerIntern.setParameter("yanel.path", getPath().toString());
transformerIntern.setParameter("yanel.back2context", backToRoot(getPath(), assetPath));
transformerIntern.setParameter("yarep.back2realm", backToRoot(getPath(), assetPath));
transformerIntern.transform(orig, new StreamResult(baos));
if (xsltTransformers != null) {
//StreamSource orig = new StreamSource(new java.io.StringBufferInputStream(sb.toString()));
for (int i = 0; i < xsltTransformers.length; i++) {
orig = new StreamSource(new ByteArrayInputStream(baos.toByteArray()));
baos = new java.io.ByteArrayOutputStream();
Transformer transformer = tfactory.newTransformer(new StreamSource(contentRepo.getInputStream(new org.wyona.yarep.core.Path(new Path(xsltTransformers[i]).toString()))));
transformer.setParameter("yanel.path.name", PathUtil.getName(getPath()));
transformer.setParameter("yanel.path", getPath().toString());
transformer.setParameter("yanel.back2context", backToRoot(getPath(), assetPath));
transformer.setParameter("yarep.back2realm", backToRoot(getPath(), assetPath));
transformer.transform(orig, new StreamResult(baos));
}
}
// TODO: Is this the best way to generate an InputStream from an OutputStream?
defaultView.setMimeType(getMimeType());
defaultView.setInputStream(new java.io.ByteArrayInputStream(baos.toByteArray()));
} catch (Exception e) {
log.error(e);
}
return defaultView;
}
/**
*
*/
public boolean exists() throws Exception {
log.warn("Not implemented yet!");
return true;
}
/**
*
*/
public long getSize() throws Exception {
// TODO: not implemented yet
log.warn("TODO: Method is not implemented yet");
return -1;
}
/**
*
*/
private StreamSource getXSLTStreamSource(Repository repo) throws RepositoryException {
File xsltFile = org.wyona.commons.io.FileUtil.file(rtd.getConfigFile().getParentFile().getAbsolutePath(),
"xslt" + File.separator + "dir2xhtml.xsl");
log.error("DEBUG: XSLT file: " + xsltFile);
return new StreamSource(xsltFile);
}
/**
* Get XSLT
*/
private String[] getXSLTprop() {
String xslt =getRTI().getProperty("xslt");
if (xslt != null) return xslt.split(",");
return null;
}
/**
* Get mime type
*/
private String getMimeType() {
String mimeType = getRTI().getProperty("mime-type");
if (mimeType != null) return mimeType;
// NOTE: Assuming fallback re dir2xhtml.xsl ...
return "application/xhtml+xml";
}
/**
*
*/
private String backToRoot(String path, String backToRoot) {
String parent = PathUtil.getParent(path);
if (parent != null && !isRoot(parent)) {
return backToRoot(parent, backToRoot + "../");
}
return backToRoot;
}
/**
*
*/
private boolean isRoot(String path) {
if (path.equals(File.separator)) return true;
return false;
}
}
| true | true | public View getView(String viewId) {
View defaultView = new View();
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
// sb.append("<?xml-stylesheet type=\"text/xsl\"
// href=\"yanel/resources/directory/xslt/dir2xhtml.xsl\"?>");
Repository contentRepo = null;
try {
contentRepo = getRealm().getRepository();
org.wyona.yarep.core.Path p = new org.wyona.yarep.core.Path(getPath());
// TODO: This doesn't seem to work ... (check on Yarep ...)
if (contentRepo.isResource(p)) {
log.warn("Path is a resource instead of a collection: " + p);
// p = p.getParent();
}
// TODO: Implement org.wyona.yarep.core.Path.getParent()
if (!contentRepo.isCollection(p)) {
log.warn("Path is not a collection: " + p);
p = new org.wyona.yarep.core.Path(new org.wyona.commons.io.Path(p.toString()).getParent().toString());
log.warn("Use parent of path: " + p);
}
// TODO: Add realm prefix, e.g. realm-prefix="ulysses-demo"
// NOTE: The schema is according to
// http://cocoon.apache.org/2.1/userdocs/directory-generator.html
sb.append("<dir:directory yanel:path=\""
+ getPath()
+ "\" dir:name=\""
+ p.getName()
+ "\" dir:path=\""
+ p
+ "\" xmlns:dir=\"http://apache.org/cocoon/directory/2.0\" xmlns:yanel=\"http://www.wyona.org/yanel/resource/directory/1.0\">");
// TODO: Do not show the children with suffix .yanel-rti resp. make
// this configurable!
// NOTE: Do not hardcode the .yanel-rti, but rather use
// Path.getRTIPath ...
org.wyona.yarep.core.Path[] children = contentRepo.getChildren(p);
for (int i = 0; i < children.length; i++) {
if (contentRepo.isResource(children[i])) {
sb.append("<dir:file path=\"" + children[i] + "\" name=\"" + children[i].getName() + "\"/>");
} else if (contentRepo.isCollection(children[i])) {
sb.append("<dir:directory path=\"" + children[i] + "\" name=\"" + children[i].getName() + "\"/>");
} else {
sb.append("<yanel:exception yanel:path=\"" + children[i] + "\"/>");
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
sb.append("</dir:directory>");
if (viewId != null && viewId.equals("source")) {
defaultView.setMimeType("application/xml");
defaultView.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
return defaultView;
}
try {
String assetPath = "";
if (getPath().endsWith("/")) {
assetPath = "../";
}
TransformerFactory tfactory = TransformerFactory.newInstance();
String[] xsltTransformers = getXSLTprop();
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
Transformer transformerIntern = tfactory.newTransformer(getXSLTStreamSource( contentRepo));
StreamSource orig = new StreamSource(new java.io.StringBufferInputStream(sb.toString()));
transformerIntern.setParameter("yanel.path.name", PathUtil.getName(getPath()));
transformerIntern.setParameter("yanel.path", getPath().toString());
transformerIntern.setParameter("yanel.back2context", backToRoot(getPath(), assetPath));
transformerIntern.setParameter("yarep.back2realm", backToRoot(getPath(), assetPath));
transformerIntern.transform(orig, new StreamResult(baos));
if (xsltTransformers != null) {
//StreamSource orig = new StreamSource(new java.io.StringBufferInputStream(sb.toString()));
for (int i = 0; i < xsltTransformers.length; i++) {
orig = new StreamSource(new ByteArrayInputStream(baos.toByteArray()));
baos = new java.io.ByteArrayOutputStream();
Transformer transformer = tfactory.newTransformer(new StreamSource(contentRepo.getInputStream(new org.wyona.yarep.core.Path(new Path(xsltTransformers[i]).toString()))));
transformer.setParameter("yanel.path.name", PathUtil.getName(getPath()));
transformer.setParameter("yanel.path", getPath().toString());
transformer.setParameter("yanel.back2context", backToRoot(getPath(), assetPath));
transformer.setParameter("yarep.back2realm", backToRoot(getPath(), assetPath));
transformer.transform(orig, new StreamResult(baos));
}
}
// TODO: Is this the best way to generate an InputStream from an OutputStream?
defaultView.setMimeType(getMimeType());
defaultView.setInputStream(new java.io.ByteArrayInputStream(baos.toByteArray()));
} catch (Exception e) {
log.error(e);
}
return defaultView;
}
| public View getView(String viewId) {
View defaultView = new View();
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
// sb.append("<?xml-stylesheet type=\"text/xsl\"
// href=\"yanel/resources/directory/xslt/dir2xhtml.xsl\"?>");
Repository contentRepo = null;
try {
contentRepo = getRealm().getRepository();
org.wyona.yarep.core.Path p = new org.wyona.yarep.core.Path(getPath());
// TODO: This doesn't seem to work ... (check on Yarep ...)
if (contentRepo.isResource(p)) {
log.warn("Path is a resource instead of a collection: " + p);
// p = p.getParent();
}
// TODO: Implement org.wyona.yarep.core.Path.getParent()
if (!contentRepo.isCollection(p)) {
log.warn("Path is not a collection: " + p);
p = new org.wyona.yarep.core.Path(new org.wyona.commons.io.Path(p.toString()).getParent().toString());
log.warn("Use parent of path: " + p);
}
// TODO: Add realm prefix, e.g. realm-prefix="ulysses-demo"
// NOTE: The schema is according to
// http://cocoon.apache.org/2.1/userdocs/directory-generator.html
sb.append("<dir:directory yanel:path=\""
+ getPath()
+ "\" dir:name=\""
+ p.getName()
+ "\" dir:path=\""
+ p
+ "\" xmlns:dir=\"http://apache.org/cocoon/directory/2.0\" xmlns:yanel=\"http://www.wyona.org/yanel/resource/directory/1.0\">");
// TODO: Do not show the children with suffix .yanel-rti resp. make
// this configurable!
// NOTE: Do not hardcode the .yanel-rti, but rather use
// Path.getRTIPath ...
org.wyona.yarep.core.Path[] children = contentRepo.getChildren(p);
for (int i = 0; i < children.length; i++) {
if (contentRepo.isResource(children[i])) {
sb.append("<dir:file path=\"" + children[i] + "\" name=\"" + children[i].getName() + "\"/>");
} else if (contentRepo.isCollection(children[i])) {
sb.append("<dir:directory path=\"" + children[i] + "\" name=\"" + children[i].getName() + "\"/>");
} else {
sb.append("<yanel:exception yanel:path=\"" + children[i] + "\"/>");
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
sb.append("</dir:directory>");
if (viewId != null && viewId.equals("source")) {
defaultView.setMimeType("application/xml");
defaultView.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
return defaultView;
}
try {
String assetPath = "";
if (getPath().endsWith("/") && !isRoot(getPath())) {
assetPath = "../";
}
TransformerFactory tfactory = TransformerFactory.newInstance();
String[] xsltTransformers = getXSLTprop();
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
Transformer transformerIntern = tfactory.newTransformer(getXSLTStreamSource( contentRepo));
StreamSource orig = new StreamSource(new java.io.StringBufferInputStream(sb.toString()));
transformerIntern.setParameter("yanel.path.name", PathUtil.getName(getPath()));
transformerIntern.setParameter("yanel.path", getPath().toString());
transformerIntern.setParameter("yanel.back2context", backToRoot(getPath(), assetPath));
transformerIntern.setParameter("yarep.back2realm", backToRoot(getPath(), assetPath));
transformerIntern.transform(orig, new StreamResult(baos));
if (xsltTransformers != null) {
//StreamSource orig = new StreamSource(new java.io.StringBufferInputStream(sb.toString()));
for (int i = 0; i < xsltTransformers.length; i++) {
orig = new StreamSource(new ByteArrayInputStream(baos.toByteArray()));
baos = new java.io.ByteArrayOutputStream();
Transformer transformer = tfactory.newTransformer(new StreamSource(contentRepo.getInputStream(new org.wyona.yarep.core.Path(new Path(xsltTransformers[i]).toString()))));
transformer.setParameter("yanel.path.name", PathUtil.getName(getPath()));
transformer.setParameter("yanel.path", getPath().toString());
transformer.setParameter("yanel.back2context", backToRoot(getPath(), assetPath));
transformer.setParameter("yarep.back2realm", backToRoot(getPath(), assetPath));
transformer.transform(orig, new StreamResult(baos));
}
}
// TODO: Is this the best way to generate an InputStream from an OutputStream?
defaultView.setMimeType(getMimeType());
defaultView.setInputStream(new java.io.ByteArrayInputStream(baos.toByteArray()));
} catch (Exception e) {
log.error(e);
}
return defaultView;
}
|
diff --git a/jsecurity/ri/business/src/org/jsecurity/ri/authc/module/activedirectory/ActiveDirectoryAuthenticationModule.java b/jsecurity/ri/business/src/org/jsecurity/ri/authc/module/activedirectory/ActiveDirectoryAuthenticationModule.java
index de0418a2..668b6e15 100644
--- a/jsecurity/ri/business/src/org/jsecurity/ri/authc/module/activedirectory/ActiveDirectoryAuthenticationModule.java
+++ b/jsecurity/ri/business/src/org/jsecurity/ri/authc/module/activedirectory/ActiveDirectoryAuthenticationModule.java
@@ -1,363 +1,363 @@
/*
* Copyright (C) 2005 Les Hazlewood
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307
* USA
*
* Or, you may view it online at
* http://www.opensource.org/licenses/lgpl-license.php
*/
package org.jsecurity.ri.authc.module.activedirectory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.AuthenticationToken;
import org.jsecurity.authc.IncorrectCredentialException;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.authc.module.AuthenticationInfo;
import org.jsecurity.authc.module.AuthenticationModule;
import org.jsecurity.ri.authc.module.dao.SimpleAuthenticationInfo;
import org.jsecurity.ri.util.UsernamePrincipal;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.security.Principal;
import java.util.*;
/**
* <p>An {@link AuthenticationModule} that authenticates with an active directory LDAP
* server to determine the roles for a particular user. This module accepts authentication
* tokens of type {@link UsernamePasswordToken}. This implementation only returns roles for a
* particular user, and not permissions - but it can be subclassed to build a permission
* list as well.</p>
*
* <p>More advanced implementations would likely want to override the
* {@link #getLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)} and
* {@link #buildAuthenticationInfo(String, char[], LdapDirectoryInfo)} methods.</p>
*
* todo This class needs to be refactored to have an LdapAuthenticationModule superclass
*
* @see LdapDirectoryInfo
* @see #getLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)
* @see #buildAuthenticationInfo(String, char[], LdapDirectoryInfo)
*
* @author Tim Veil
* @author Jeremy Haile
*/
public class ActiveDirectoryAuthenticationModule implements AuthenticationModule {
/*--------------------------------------------
| C O N S T A N T S |
============================================*/
/*--------------------------------------------
| I N S T A N C E V A R I A B L E S |
============================================*/
/**
* Commons-logger.
*/
protected transient final Log log = LogFactory.getLog( getClass() );
/**
* The type of LDAP authentication to perform.
*/
private String authentication = "simple";
/**
* A suffix appended to the username when searching in the LDAP context.
* This is typically for domain names. (e.g. "@MyDomain.local")
*/
private String principalSuffix = null;
/**
* The search base for the search to perform in the LDAP server.
* (e.g. OU=OrganizationName,DC=MyDomain,DC=local )
*/
private String searchBase = null;
/**
* The context factory to use. This defaults to the SUN LDAP JNDI implementation
* but can be overridden to use custom LDAP factories.
*/
private String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
/**
* The LDAP url to connect to. (e.g. ldap://<activeDirectoryHostname>:<port>)
*/
private String url = null;
/**
* The LDAP referral property. Defaults to "follow"
*/
private String refferal = "follow";
/**
* Mapping from fully qualified group names (e.g. CN=Group,OU=Company,DC=MyDomain,DC=local)
* as returned by active directory to role names.
*/
private Map<String, String> groupRoleMap;
/*--------------------------------------------
| C O N S T R U C T O R S |
============================================*/
/*--------------------------------------------
| A C C E S S O R S / M O D I F I E R S |
============================================*/
public void setAuthentication(String authentication) {
this.authentication = authentication;
}
public void setPrincipalSuffix(String principalSuffix) {
this.principalSuffix = principalSuffix;
}
public void setSearchBase(String searchBase) {
this.searchBase = searchBase;
}
public void setContextFactory(String contextFactory) {
this.contextFactory = contextFactory;
}
public void setUrl(String url) {
this.url = url;
}
public void setRefferal(String refferal) {
this.refferal = refferal;
}
public void setGroupRoleMap(Map<String, String> groupRoleMap) {
this.groupRoleMap = groupRoleMap;
}
/*--------------------------------------------
| M E T H O D S |
============================================*/
public boolean supports(Class tokenClass) {
return UsernamePasswordToken.class.isAssignableFrom( tokenClass );
}
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
LdapDirectoryInfo ldapDirectoryInfo = performAuthentication(upToken.getUsername(), upToken.getPassword());
return buildAuthenticationInfo( upToken.getUsername(), upToken.getPassword(), ldapDirectoryInfo );
}
/**
* Builds an {@link AuthenticationInfo} object to return based on an {@link LdapDirectoryInfo} object
* returned from {@link #performAuthentication(String, char[])}
*
* @param username the username of the user being authenticated.
* @param password the password of the user being authenticated.
* @param ldapDirectoryInfo the LDAP directory information queried from the LDAP server.
* @return an instance of {@link AuthenticationInfo} that represents the principal, credentials, and
* roles that this user has.
*/
protected AuthenticationInfo buildAuthenticationInfo(String username, char[] password, LdapDirectoryInfo ldapDirectoryInfo) {
List<Principal> principals = new ArrayList<Principal>( ldapDirectoryInfo.getPrincipals().size() + 1 );
UsernamePrincipal principal = new UsernamePrincipal( username );
principals.add( principal );
principals.addAll( ldapDirectoryInfo.getPrincipals() );
return new SimpleAuthenticationInfo( principals, password, ldapDirectoryInfo.getRoleNames() );
}
/**
* Performs the actual authentication of the user by connecting to the LDAP server, querying it
* for user information, and returning an {@link LdapDirectoryInfo} instance containing the
* results.
*
* <p>Typically, users that need special behavior will not override this method, but will instead
* override {@link #getLdapDirectoryInfo(String, javax.naming.ldap.LdapContext)}</p>
*
* @param username the username of the user being authenticated.
* @param password the password of the user being authenticated.
*
* @return the results of the LDAP directory search.
*/
protected LdapDirectoryInfo performAuthentication(String username, char[] password) {
if( searchBase == null ) {
throw new IllegalStateException( "A search base must be specified." );
}
if( url == null ) {
throw new IllegalStateException( "An LDAP URL must be specified of the form ldap://<hostname>:<port>" );
}
if( principalSuffix != null ) {
username = username + principalSuffix;
}
Hashtable<String, String> env = new Hashtable<String, String>(6);
env.put(Context.SECURITY_AUTHENTICATION, authentication);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, new String( password ));
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, url);
env.put(Context.REFERRAL, refferal);
if (log.isDebugEnabled()) {
- log.debug( "Initializing LDAP context using environment properties [" + env + "]" );
+ log.debug( "Initializing LDAP context using URL [" + url + "] for user [" + username + "]." );
}
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
return getLdapDirectoryInfo(username, ctx);
} catch (javax.naming.AuthenticationException e) {
throw new IncorrectCredentialException( "User could not be authenticated with LDAP server.", e );
} catch (NamingException e) {
throw new AuthenticationException( "LDAP naming error while attempting to authenticate user.", e );
} finally {
// Always close the LDAP context
try {
if (ctx != null) {
ctx.close();
}
} catch (NamingException e) {
if( log.isErrorEnabled() ) {
log.error("Problem closing Context: ", e);
}
}
}
}
/**
* Builds an {@link LdapDirectoryInfo} object by querying the given LDAP context for the
* specified username. The default implementation queries for all groups that
* the user is a member of and returns them as roles for that user.
*
* <p>This method can be overridden by subclasses to query the LDAP server
*
* @param username the username whose information should be queried from the LDAP server.
* @param ctx the LDAP context that is connected to the LDAP server.
*
* @return an {@link LdapDirectoryInfo} instance containing information retrieved from LDAP
* that can be used to build an {@link AuthenticationInfo} instance to return.
*
* @throws NamingException if any LDAP errors occur during the search.
*/
protected LdapDirectoryInfo getLdapDirectoryInfo(String username, LdapContext ctx) throws NamingException {
LdapDirectoryInfo info = new LdapDirectoryInfo();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=*)(userPrincipalName=" + username + "))";
// Perform context search
NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
log.debug("Retrieving group names for user [" + sr.getName() + "]");
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while( ae.hasMore() ) {
Attribute attr = (Attribute) ae.next();
processAttribute(info, attr);
}
}
}
return info;
}
protected void processAttribute(LdapDirectoryInfo info, Attribute attr) throws NamingException {
if( attr.getID().equals( "memberOf" ) ) {
Collection<String> groupNames = getAllAttributeValues(attr);
Collection<String> roleNames = translateRoleNames(groupNames);
if( log.isDebugEnabled() ) {
log.debug( "Adding roles [" + groupNames + "] to LDAP directory info." );
}
info.addAllRoleNames( roleNames );
}
}
protected Collection<String> translateRoleNames(Collection<String> groupNames) {
Set<String> roleNames = new HashSet<String>( groupNames.size() );
for( String groupName : groupNames ) {
String roleName = groupRoleMap.get( groupName );
roleNames.add( roleName );
}
return roleNames;
}
/**
* Helper method used to retrieve all attribute values from a particular context attribute.
*/
protected Collection<String> getAllAttributeValues(Attribute attr) throws NamingException {
Set<String> values = new HashSet<String>();
for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
String value = (String) e.next();
values.add( value );
}
return values;
}
public static void main(String[] args) {
ActiveDirectoryAuthenticationModule m = new ActiveDirectoryAuthenticationModule();
m.setUrl( "ldap://10.0.0.2:389" );
m.setSearchBase( "OU=SolTech,DC=Solad,DC=local" );
m.setPrincipalSuffix( "@Solad.local" );
UsernamePasswordToken t = new UsernamePasswordToken( "jhaile", "differen" );
AuthenticationInfo ai = m.getAuthenticationInfo( t );
System.out.println( ai );
for( String roleName : ai.getRoles() ) {
System.out.println( roleName );
}
}
}
| true | true | protected LdapDirectoryInfo performAuthentication(String username, char[] password) {
if( searchBase == null ) {
throw new IllegalStateException( "A search base must be specified." );
}
if( url == null ) {
throw new IllegalStateException( "An LDAP URL must be specified of the form ldap://<hostname>:<port>" );
}
if( principalSuffix != null ) {
username = username + principalSuffix;
}
Hashtable<String, String> env = new Hashtable<String, String>(6);
env.put(Context.SECURITY_AUTHENTICATION, authentication);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, new String( password ));
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, url);
env.put(Context.REFERRAL, refferal);
if (log.isDebugEnabled()) {
log.debug( "Initializing LDAP context using environment properties [" + env + "]" );
}
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
return getLdapDirectoryInfo(username, ctx);
} catch (javax.naming.AuthenticationException e) {
throw new IncorrectCredentialException( "User could not be authenticated with LDAP server.", e );
} catch (NamingException e) {
throw new AuthenticationException( "LDAP naming error while attempting to authenticate user.", e );
} finally {
// Always close the LDAP context
try {
if (ctx != null) {
ctx.close();
}
} catch (NamingException e) {
if( log.isErrorEnabled() ) {
log.error("Problem closing Context: ", e);
}
}
}
}
| protected LdapDirectoryInfo performAuthentication(String username, char[] password) {
if( searchBase == null ) {
throw new IllegalStateException( "A search base must be specified." );
}
if( url == null ) {
throw new IllegalStateException( "An LDAP URL must be specified of the form ldap://<hostname>:<port>" );
}
if( principalSuffix != null ) {
username = username + principalSuffix;
}
Hashtable<String, String> env = new Hashtable<String, String>(6);
env.put(Context.SECURITY_AUTHENTICATION, authentication);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, new String( password ));
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, url);
env.put(Context.REFERRAL, refferal);
if (log.isDebugEnabled()) {
log.debug( "Initializing LDAP context using URL [" + url + "] for user [" + username + "]." );
}
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
return getLdapDirectoryInfo(username, ctx);
} catch (javax.naming.AuthenticationException e) {
throw new IncorrectCredentialException( "User could not be authenticated with LDAP server.", e );
} catch (NamingException e) {
throw new AuthenticationException( "LDAP naming error while attempting to authenticate user.", e );
} finally {
// Always close the LDAP context
try {
if (ctx != null) {
ctx.close();
}
} catch (NamingException e) {
if( log.isErrorEnabled() ) {
log.error("Problem closing Context: ", e);
}
}
}
}
|
diff --git a/src/com/LRFLEW/PvP/Commands.java b/src/com/LRFLEW/PvP/Commands.java
index 4e32caf..e973058 100644
--- a/src/com/LRFLEW/PvP/Commands.java
+++ b/src/com/LRFLEW/PvP/Commands.java
@@ -1,239 +1,239 @@
package com.LRFLEW.PvP;
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;
public class Commands implements CommandExecutor {
private final PvP plugin;
protected Commands (PvP instance) {
plugin = instance;
}
public boolean onCommand (CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (args.length >= 1 && args[0].equalsIgnoreCase("on")) {
if (sender instanceof Player && args.length == 1) {
Player player = (Player)sender;
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
player.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff + " seconds before you can turn PVP on");
} else {
if (!plugin.PvP.contains(player.getName())) {
plugin.PvP.add(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOnToOff*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is raring to fight", player);
} else {
if (plugin.cooldown.containsKey(player.getName())) plugin.cooldown.remove(player.getName());
}
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for you. Beware! " +
"Turn it off by typing " + ChatColor.WHITE + "/pvp off");
}
return true;
} else if (args.length >= 2){
Player player = Bukkit.getPlayer(args[1]);
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
sender.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff +
" seconds before you can turn PVP on for" + player.getDisplayName());
} else {
if (!plugin.PvP.contains(player.getName())) {
plugin.PvP.add(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOnToOff*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is raring to fight", player);
} else {
if (plugin.cooldown.containsKey(player.getName())) plugin.cooldown.remove(player.getName());
}
}
sender.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for " + player.getDisplayName());
return true;
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("off")) {
if (sender instanceof Player && args.length == 1) {
Player player = (Player)sender;
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
player.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff + " seconds before you can turn PVP off");
return true;
} else {
if (plugin.PvP.contains(player.getName())) {
plugin.PvP.remove(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOffToOn*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is done fighting", player);
}
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "Off" + Settings.preFx + " for you. " +
"Just look out for spiders :)");
return true;
}
} else if (args.length >= 2) {
Player player = Bukkit.getPlayer(args[1]);
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
sender.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff +
" seconds before you can turn PVP on for" + player.getDisplayName());
return true;
} else {
if (plugin.PvP.contains(player.getName())) {
plugin.PvP.remove(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOffToOn*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is done fighting", player);
}
sender.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for " + player.getDisplayName());
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("spar")) {
if (sender instanceof Player) {
Player sparrer = (Player)sender;
if (args.length > 1) {
Player sparri = plugin.getServer().getPlayer(args[1]);
if (sparri == null) {
sparrer.sendMessage("Player not Found");
return true;
}
plugin.sparRequest.put(sparri.getName(), sparrer.getName());
sparri.sendMessage(sparrer.getDisplayName() + Settings.preFx + " wants to spar you. ");
sparri.sendMessage(Settings.preFx + "Accept by typing " + ChatColor.WHITE + "/pvp yes" +
Settings.preFx + " or deny with " + ChatColor.WHITE + "/pvp no");
sparrer.sendMessage("Request sent to " + sparri.getDisplayName());
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("yes")) {
if (sender instanceof Player) {
Player sparri = (Player)sender;
if (plugin.sparRequest.containsKey(sparri.getName())) {
if (plugin.sparRequest.get(sparri.getName()) == null) {
plugin.sparRequest.remove(sparri.getName());
new Misc.MapMissmatchException(sparri.getName() + " -> null");
} else {
Player sparrer = Bukkit.getPlayerExact(plugin.sparRequest.get(sparri.getName()));
plugin.sparRequest.remove(sparri.getName());
plugin.spar.put(sparri.getName(), sparrer.getName());
plugin.spar.put(sparrer.getName(), sparri.getName());
sparri.sendMessage(Settings.preFx + "You are now sparring " + ChatColor.WHITE + sparrer.getDisplayName() +
Settings.preFx + ". Good luck");
sparrer.sendMessage(Settings.preFx + "You are now sparring " + ChatColor.WHITE + sparrer.getDisplayName() +
Settings.preFx + ". Good luck");
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + sparri.getDisplayName() + " and " + sparrer.getDisplayName() +
" are noew dueling eachother. Epic", sparrer, sparri);
return true;
}
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("no")) {
if (sender instanceof Player) {
Player sparri = (Player)sender;
if (plugin.sparRequest.containsKey(sparri.getName())) {
if (plugin.sparRequest.get(sparri.getName()) == null) {
plugin.sparRequest.remove(sparri.getName());
new Misc.MapMissmatchException(sparri.getName() + " -> null");
} else {
Player sparrer = Bukkit.getPlayerExact(plugin.sparRequest.get(sparri.getName()));
plugin.sparRequest.remove(sparri.getName());
sparri.sendMessage("You have denied the spar request from " + sparrer.getDisplayName());
sparrer.sendMessage(sparrer.getDisplayName() + " Denied you sparring request. Sorry");
return true;
}
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("killswitch") || args.length >= 1 && args[0].equalsIgnoreCase("ks")) {
if (sender instanceof Player)
if (!((Player)sender).isOp()) {
sender.sendMessage((Settings.preFx + "You don't have permissions to run this command"));
return true;
}
if (args[1].equalsIgnoreCase("dissable") || args[1].equalsIgnoreCase("dis")) {
plugin.killSwitch = 0;
Bukkit.broadcastMessage(Settings.preFx + "Users can now set their own PvP status");
} else {
if (args[1].equalsIgnoreCase("on")) {
plugin.killSwitch = 1;
Bukkit.broadcastMessage(Settings.preFx + "PvP is now forced on for everybody");
} if (args[1].equalsIgnoreCase("off")) {
plugin.killSwitch = -1;
Bukkit.broadcastMessage(Settings.preFx + "PvP is now forced off for everybody");
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("list")) {
if (plugin.PvP.isEmpty()) {
sender.sendMessage(Settings.preFx + "Nobody has PvP on");
return true;
}
int page;
if (args.length >= 2) try {
page = Integer.parseInt(args[1]) - 1;
if (page < 0) {
if (page == -1) sender.sendMessage(Settings.preFx + "no page 0");
else sender.sendMessage(Settings.preFx + "no negative pages");
page = 0;
}
- if (plugin.PvP.size() > page * 16) {
+ if (page * 16 > plugin.PvP.size()) {
sender.sendMessage(Settings.preFx + "there is no page " + page);
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(Settings.preFx + "\"" + args[1] + "\"" + " is not a number");
page = 0;
}
else page = 0;
boolean display = sender instanceof Player;
sender.sendMessage(Settings.preFx + "page " + page + " out of " + Math.ceil((double)plugin.PvP.size()/16));
String[] names = new String[16];
int i = 0, j = 0;
for (String p : plugin.PvP) {
if (i++ < page * 16) continue;
if (display) names[j++] = Bukkit.getPlayer(p).getDisplayName();
else names[j++] = p;
if (j >= 16) break;
}
for (i = 0; i < 4 && (i*4) < j; i++) {
String temp = "";
for (int k = 0; k < 4 && (i*4) + k < j; k++) {
temp += Settings.preFx + names[(i*4) + k];
}
sender.sendMessage(temp);
}
return true;
}
if (args.length >= 1 && args[0].equalsIgnoreCase("help")) {
if (sender instanceof Player) {
Player player = (Player)sender;
player.sendMessage(Settings.preFx + "Usage:");
player.sendMessage(ChatColor.WHITE + " /PvP on" + Settings.preFx + " - you can be attacked by players");
player.sendMessage(ChatColor.WHITE + " /PvP off" + Settings.preFx + " - players can't attack you");
return true;
} else {
System.out.println("Usage:");
System.out.println("\t/PvP on" + Settings.preFx + " - you can be attacked by players");
System.out.println("\t/PvP off" + Settings.preFx + " - players can't attack you");
}
}
if (sender instanceof Player) {
Player player = (Player)sender;
if ( plugin.PvP.contains(player.getName())) {
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for you. Beware!");
} else {
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "Off" + Settings.preFx + " for you. " +
"Just look out for spiders :)");
}
player.sendMessage(Settings.preFx + "Usage:");
player.sendMessage(ChatColor.WHITE + " /PvP on" + Settings.preFx + " - you can be attacked by players");
player.sendMessage(ChatColor.WHITE + " /PvP off" + Settings.preFx + " - players can't attack you");
Long l = plugin.cooldown.get(player.getName());
if (l != null && l <= System.currentTimeMillis()) plugin.cooldown.remove(player.getName());
return true;
} else {
System.out.println("Type \"pvp help\" for a list of commands");
}
return true;
}
}
| true | true | public boolean onCommand (CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (args.length >= 1 && args[0].equalsIgnoreCase("on")) {
if (sender instanceof Player && args.length == 1) {
Player player = (Player)sender;
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
player.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff + " seconds before you can turn PVP on");
} else {
if (!plugin.PvP.contains(player.getName())) {
plugin.PvP.add(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOnToOff*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is raring to fight", player);
} else {
if (plugin.cooldown.containsKey(player.getName())) plugin.cooldown.remove(player.getName());
}
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for you. Beware! " +
"Turn it off by typing " + ChatColor.WHITE + "/pvp off");
}
return true;
} else if (args.length >= 2){
Player player = Bukkit.getPlayer(args[1]);
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
sender.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff +
" seconds before you can turn PVP on for" + player.getDisplayName());
} else {
if (!plugin.PvP.contains(player.getName())) {
plugin.PvP.add(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOnToOff*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is raring to fight", player);
} else {
if (plugin.cooldown.containsKey(player.getName())) plugin.cooldown.remove(player.getName());
}
}
sender.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for " + player.getDisplayName());
return true;
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("off")) {
if (sender instanceof Player && args.length == 1) {
Player player = (Player)sender;
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
player.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff + " seconds before you can turn PVP off");
return true;
} else {
if (plugin.PvP.contains(player.getName())) {
plugin.PvP.remove(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOffToOn*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is done fighting", player);
}
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "Off" + Settings.preFx + " for you. " +
"Just look out for spiders :)");
return true;
}
} else if (args.length >= 2) {
Player player = Bukkit.getPlayer(args[1]);
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
sender.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff +
" seconds before you can turn PVP on for" + player.getDisplayName());
return true;
} else {
if (plugin.PvP.contains(player.getName())) {
plugin.PvP.remove(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOffToOn*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is done fighting", player);
}
sender.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for " + player.getDisplayName());
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("spar")) {
if (sender instanceof Player) {
Player sparrer = (Player)sender;
if (args.length > 1) {
Player sparri = plugin.getServer().getPlayer(args[1]);
if (sparri == null) {
sparrer.sendMessage("Player not Found");
return true;
}
plugin.sparRequest.put(sparri.getName(), sparrer.getName());
sparri.sendMessage(sparrer.getDisplayName() + Settings.preFx + " wants to spar you. ");
sparri.sendMessage(Settings.preFx + "Accept by typing " + ChatColor.WHITE + "/pvp yes" +
Settings.preFx + " or deny with " + ChatColor.WHITE + "/pvp no");
sparrer.sendMessage("Request sent to " + sparri.getDisplayName());
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("yes")) {
if (sender instanceof Player) {
Player sparri = (Player)sender;
if (plugin.sparRequest.containsKey(sparri.getName())) {
if (plugin.sparRequest.get(sparri.getName()) == null) {
plugin.sparRequest.remove(sparri.getName());
new Misc.MapMissmatchException(sparri.getName() + " -> null");
} else {
Player sparrer = Bukkit.getPlayerExact(plugin.sparRequest.get(sparri.getName()));
plugin.sparRequest.remove(sparri.getName());
plugin.spar.put(sparri.getName(), sparrer.getName());
plugin.spar.put(sparrer.getName(), sparri.getName());
sparri.sendMessage(Settings.preFx + "You are now sparring " + ChatColor.WHITE + sparrer.getDisplayName() +
Settings.preFx + ". Good luck");
sparrer.sendMessage(Settings.preFx + "You are now sparring " + ChatColor.WHITE + sparrer.getDisplayName() +
Settings.preFx + ". Good luck");
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + sparri.getDisplayName() + " and " + sparrer.getDisplayName() +
" are noew dueling eachother. Epic", sparrer, sparri);
return true;
}
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("no")) {
if (sender instanceof Player) {
Player sparri = (Player)sender;
if (plugin.sparRequest.containsKey(sparri.getName())) {
if (plugin.sparRequest.get(sparri.getName()) == null) {
plugin.sparRequest.remove(sparri.getName());
new Misc.MapMissmatchException(sparri.getName() + " -> null");
} else {
Player sparrer = Bukkit.getPlayerExact(plugin.sparRequest.get(sparri.getName()));
plugin.sparRequest.remove(sparri.getName());
sparri.sendMessage("You have denied the spar request from " + sparrer.getDisplayName());
sparrer.sendMessage(sparrer.getDisplayName() + " Denied you sparring request. Sorry");
return true;
}
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("killswitch") || args.length >= 1 && args[0].equalsIgnoreCase("ks")) {
if (sender instanceof Player)
if (!((Player)sender).isOp()) {
sender.sendMessage((Settings.preFx + "You don't have permissions to run this command"));
return true;
}
if (args[1].equalsIgnoreCase("dissable") || args[1].equalsIgnoreCase("dis")) {
plugin.killSwitch = 0;
Bukkit.broadcastMessage(Settings.preFx + "Users can now set their own PvP status");
} else {
if (args[1].equalsIgnoreCase("on")) {
plugin.killSwitch = 1;
Bukkit.broadcastMessage(Settings.preFx + "PvP is now forced on for everybody");
} if (args[1].equalsIgnoreCase("off")) {
plugin.killSwitch = -1;
Bukkit.broadcastMessage(Settings.preFx + "PvP is now forced off for everybody");
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("list")) {
if (plugin.PvP.isEmpty()) {
sender.sendMessage(Settings.preFx + "Nobody has PvP on");
return true;
}
int page;
if (args.length >= 2) try {
page = Integer.parseInt(args[1]) - 1;
if (page < 0) {
if (page == -1) sender.sendMessage(Settings.preFx + "no page 0");
else sender.sendMessage(Settings.preFx + "no negative pages");
page = 0;
}
if (plugin.PvP.size() > page * 16) {
sender.sendMessage(Settings.preFx + "there is no page " + page);
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(Settings.preFx + "\"" + args[1] + "\"" + " is not a number");
page = 0;
}
else page = 0;
boolean display = sender instanceof Player;
sender.sendMessage(Settings.preFx + "page " + page + " out of " + Math.ceil((double)plugin.PvP.size()/16));
String[] names = new String[16];
int i = 0, j = 0;
for (String p : plugin.PvP) {
if (i++ < page * 16) continue;
if (display) names[j++] = Bukkit.getPlayer(p).getDisplayName();
else names[j++] = p;
if (j >= 16) break;
}
for (i = 0; i < 4 && (i*4) < j; i++) {
String temp = "";
for (int k = 0; k < 4 && (i*4) + k < j; k++) {
temp += Settings.preFx + names[(i*4) + k];
}
sender.sendMessage(temp);
}
return true;
}
if (args.length >= 1 && args[0].equalsIgnoreCase("help")) {
if (sender instanceof Player) {
Player player = (Player)sender;
player.sendMessage(Settings.preFx + "Usage:");
player.sendMessage(ChatColor.WHITE + " /PvP on" + Settings.preFx + " - you can be attacked by players");
player.sendMessage(ChatColor.WHITE + " /PvP off" + Settings.preFx + " - players can't attack you");
return true;
} else {
System.out.println("Usage:");
System.out.println("\t/PvP on" + Settings.preFx + " - you can be attacked by players");
System.out.println("\t/PvP off" + Settings.preFx + " - players can't attack you");
}
}
if (sender instanceof Player) {
Player player = (Player)sender;
if ( plugin.PvP.contains(player.getName())) {
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for you. Beware!");
} else {
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "Off" + Settings.preFx + " for you. " +
"Just look out for spiders :)");
}
player.sendMessage(Settings.preFx + "Usage:");
player.sendMessage(ChatColor.WHITE + " /PvP on" + Settings.preFx + " - you can be attacked by players");
player.sendMessage(ChatColor.WHITE + " /PvP off" + Settings.preFx + " - players can't attack you");
Long l = plugin.cooldown.get(player.getName());
if (l != null && l <= System.currentTimeMillis()) plugin.cooldown.remove(player.getName());
return true;
} else {
System.out.println("Type \"pvp help\" for a list of commands");
}
return true;
}
| public boolean onCommand (CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (args.length >= 1 && args[0].equalsIgnoreCase("on")) {
if (sender instanceof Player && args.length == 1) {
Player player = (Player)sender;
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
player.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff + " seconds before you can turn PVP on");
} else {
if (!plugin.PvP.contains(player.getName())) {
plugin.PvP.add(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOnToOff*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is raring to fight", player);
} else {
if (plugin.cooldown.containsKey(player.getName())) plugin.cooldown.remove(player.getName());
}
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for you. Beware! " +
"Turn it off by typing " + ChatColor.WHITE + "/pvp off");
}
return true;
} else if (args.length >= 2){
Player player = Bukkit.getPlayer(args[1]);
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
sender.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff +
" seconds before you can turn PVP on for" + player.getDisplayName());
} else {
if (!plugin.PvP.contains(player.getName())) {
plugin.PvP.add(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOnToOff*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is raring to fight", player);
} else {
if (plugin.cooldown.containsKey(player.getName())) plugin.cooldown.remove(player.getName());
}
}
sender.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for " + player.getDisplayName());
return true;
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("off")) {
if (sender instanceof Player && args.length == 1) {
Player player = (Player)sender;
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
player.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff + " seconds before you can turn PVP off");
return true;
} else {
if (plugin.PvP.contains(player.getName())) {
plugin.PvP.remove(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOffToOn*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is done fighting", player);
}
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "Off" + Settings.preFx + " for you. " +
"Just look out for spiders :)");
return true;
}
} else if (args.length >= 2) {
Player player = Bukkit.getPlayer(args[1]);
if (plugin.cooldown.get(player.getName()) != null && plugin.cooldown.get(player.getName()) > System.currentTimeMillis()) {
sender.sendMessage(Settings.preFx + "You need to wait " + plugin.sets.cooldownOnToOff +
" seconds before you can turn PVP on for" + player.getDisplayName());
return true;
} else {
if (plugin.PvP.contains(player.getName())) {
plugin.PvP.remove(player.getName());
plugin.cooldown.put(player.getName(), System.currentTimeMillis() + (plugin.sets.cooldownOffToOn*1000));
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + player.getDisplayName() + " is done fighting", player);
}
sender.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for " + player.getDisplayName());
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("spar")) {
if (sender instanceof Player) {
Player sparrer = (Player)sender;
if (args.length > 1) {
Player sparri = plugin.getServer().getPlayer(args[1]);
if (sparri == null) {
sparrer.sendMessage("Player not Found");
return true;
}
plugin.sparRequest.put(sparri.getName(), sparrer.getName());
sparri.sendMessage(sparrer.getDisplayName() + Settings.preFx + " wants to spar you. ");
sparri.sendMessage(Settings.preFx + "Accept by typing " + ChatColor.WHITE + "/pvp yes" +
Settings.preFx + " or deny with " + ChatColor.WHITE + "/pvp no");
sparrer.sendMessage("Request sent to " + sparri.getDisplayName());
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("yes")) {
if (sender instanceof Player) {
Player sparri = (Player)sender;
if (plugin.sparRequest.containsKey(sparri.getName())) {
if (plugin.sparRequest.get(sparri.getName()) == null) {
plugin.sparRequest.remove(sparri.getName());
new Misc.MapMissmatchException(sparri.getName() + " -> null");
} else {
Player sparrer = Bukkit.getPlayerExact(plugin.sparRequest.get(sparri.getName()));
plugin.sparRequest.remove(sparri.getName());
plugin.spar.put(sparri.getName(), sparrer.getName());
plugin.spar.put(sparrer.getName(), sparri.getName());
sparri.sendMessage(Settings.preFx + "You are now sparring " + ChatColor.WHITE + sparrer.getDisplayName() +
Settings.preFx + ". Good luck");
sparrer.sendMessage(Settings.preFx + "You are now sparring " + ChatColor.WHITE + sparrer.getDisplayName() +
Settings.preFx + ". Good luck");
if (plugin.sets.announce) Misc.announceExclude(Settings.preFx + sparri.getDisplayName() + " and " + sparrer.getDisplayName() +
" are noew dueling eachother. Epic", sparrer, sparri);
return true;
}
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("no")) {
if (sender instanceof Player) {
Player sparri = (Player)sender;
if (plugin.sparRequest.containsKey(sparri.getName())) {
if (plugin.sparRequest.get(sparri.getName()) == null) {
plugin.sparRequest.remove(sparri.getName());
new Misc.MapMissmatchException(sparri.getName() + " -> null");
} else {
Player sparrer = Bukkit.getPlayerExact(plugin.sparRequest.get(sparri.getName()));
plugin.sparRequest.remove(sparri.getName());
sparri.sendMessage("You have denied the spar request from " + sparrer.getDisplayName());
sparrer.sendMessage(sparrer.getDisplayName() + " Denied you sparring request. Sorry");
return true;
}
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("killswitch") || args.length >= 1 && args[0].equalsIgnoreCase("ks")) {
if (sender instanceof Player)
if (!((Player)sender).isOp()) {
sender.sendMessage((Settings.preFx + "You don't have permissions to run this command"));
return true;
}
if (args[1].equalsIgnoreCase("dissable") || args[1].equalsIgnoreCase("dis")) {
plugin.killSwitch = 0;
Bukkit.broadcastMessage(Settings.preFx + "Users can now set their own PvP status");
} else {
if (args[1].equalsIgnoreCase("on")) {
plugin.killSwitch = 1;
Bukkit.broadcastMessage(Settings.preFx + "PvP is now forced on for everybody");
} if (args[1].equalsIgnoreCase("off")) {
plugin.killSwitch = -1;
Bukkit.broadcastMessage(Settings.preFx + "PvP is now forced off for everybody");
return true;
}
}
}
if (args.length >= 1 && args[0].equalsIgnoreCase("list")) {
if (plugin.PvP.isEmpty()) {
sender.sendMessage(Settings.preFx + "Nobody has PvP on");
return true;
}
int page;
if (args.length >= 2) try {
page = Integer.parseInt(args[1]) - 1;
if (page < 0) {
if (page == -1) sender.sendMessage(Settings.preFx + "no page 0");
else sender.sendMessage(Settings.preFx + "no negative pages");
page = 0;
}
if (page * 16 > plugin.PvP.size()) {
sender.sendMessage(Settings.preFx + "there is no page " + page);
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(Settings.preFx + "\"" + args[1] + "\"" + " is not a number");
page = 0;
}
else page = 0;
boolean display = sender instanceof Player;
sender.sendMessage(Settings.preFx + "page " + page + " out of " + Math.ceil((double)plugin.PvP.size()/16));
String[] names = new String[16];
int i = 0, j = 0;
for (String p : plugin.PvP) {
if (i++ < page * 16) continue;
if (display) names[j++] = Bukkit.getPlayer(p).getDisplayName();
else names[j++] = p;
if (j >= 16) break;
}
for (i = 0; i < 4 && (i*4) < j; i++) {
String temp = "";
for (int k = 0; k < 4 && (i*4) + k < j; k++) {
temp += Settings.preFx + names[(i*4) + k];
}
sender.sendMessage(temp);
}
return true;
}
if (args.length >= 1 && args[0].equalsIgnoreCase("help")) {
if (sender instanceof Player) {
Player player = (Player)sender;
player.sendMessage(Settings.preFx + "Usage:");
player.sendMessage(ChatColor.WHITE + " /PvP on" + Settings.preFx + " - you can be attacked by players");
player.sendMessage(ChatColor.WHITE + " /PvP off" + Settings.preFx + " - players can't attack you");
return true;
} else {
System.out.println("Usage:");
System.out.println("\t/PvP on" + Settings.preFx + " - you can be attacked by players");
System.out.println("\t/PvP off" + Settings.preFx + " - players can't attack you");
}
}
if (sender instanceof Player) {
Player player = (Player)sender;
if ( plugin.PvP.contains(player.getName())) {
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "On" + Settings.preFx + " for you. Beware!");
} else {
player.sendMessage(Settings.preFx + "PvP is " + ChatColor.WHITE + "Off" + Settings.preFx + " for you. " +
"Just look out for spiders :)");
}
player.sendMessage(Settings.preFx + "Usage:");
player.sendMessage(ChatColor.WHITE + " /PvP on" + Settings.preFx + " - you can be attacked by players");
player.sendMessage(ChatColor.WHITE + " /PvP off" + Settings.preFx + " - players can't attack you");
Long l = plugin.cooldown.get(player.getName());
if (l != null && l <= System.currentTimeMillis()) plugin.cooldown.remove(player.getName());
return true;
} else {
System.out.println("Type \"pvp help\" for a list of commands");
}
return true;
}
|
diff --git a/src/main/java/org/jfrog/hudson/util/PluginDependencyHelper.java b/src/main/java/org/jfrog/hudson/util/PluginDependencyHelper.java
index 362cbf6a..aee552be 100644
--- a/src/main/java/org/jfrog/hudson/util/PluginDependencyHelper.java
+++ b/src/main/java/org/jfrog/hudson/util/PluginDependencyHelper.java
@@ -1,58 +1,61 @@
package org.jfrog.hudson.util;
import hudson.FilePath;
import hudson.model.AbstractBuild;
import hudson.model.Computer;
import hudson.model.Hudson;
import hudson.slaves.SlaveComputer;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.IOException;
/**
* @author Noam Y. Tenne
*/
public class PluginDependencyHelper {
public static FilePath getActualDependencyDirectory(AbstractBuild build, File localDependencyFile)
throws IOException, InterruptedException {
File localDependencyDir = localDependencyFile.getParentFile();
- if (!(Computer.currentComputer() instanceof SlaveComputer)) {
- return new FilePath(localDependencyDir);
- }
+// if (!(Computer.currentComputer() instanceof SlaveComputer)) {
+// return new FilePath(localDependencyDir);
+// }
String pluginVersion = Hudson.getInstance().getPluginManager().getPlugin("artifactory").getVersion();
if (pluginVersion.contains(" ")) {
//Trim the plugin version in case we're working on a snapshot version (contains illegal chars)
pluginVersion = StringUtils.split(pluginVersion, " ")[0];
}
- FilePath remoteDependencyDir = new FilePath(build.getWorkspace().getParent(),
- "artifactory-plugin/" + pluginVersion);
+ FilePath remoteDependencyDir = new FilePath(build.getBuiltOn().getRootPath(),"cache/artifactory-plugin/" + pluginVersion);
if (!remoteDependencyDir.exists()) {
remoteDependencyDir.mkdirs();
}
//Check if the dependencies have already been transferred successfully
FilePath remoteDependencyMark = new FilePath(remoteDependencyDir, "ok");
if (!remoteDependencyMark.exists()) {
File[] localDependencies = localDependencyDir.listFiles();
for (File localDependency : localDependencies) {
+ if (localDependency.getName().equals("classes.jar"))
+ // skip classes in this plugin source tree.
+ // TODO: for a proper long term fix, see my comment in JENKINS-18401
+ continue;
FilePath remoteDependencyFilePath = new FilePath(remoteDependencyDir, localDependency.getName());
if (!remoteDependencyFilePath.exists()) {
FilePath localDependencyFilePath = new FilePath(localDependency);
localDependencyFilePath.copyTo(remoteDependencyFilePath);
}
}
//Mark that all the dependencies have been transferred successfully for future references
remoteDependencyMark.touch(System.currentTimeMillis());
}
return remoteDependencyDir;
}
}
| false | true | public static FilePath getActualDependencyDirectory(AbstractBuild build, File localDependencyFile)
throws IOException, InterruptedException {
File localDependencyDir = localDependencyFile.getParentFile();
if (!(Computer.currentComputer() instanceof SlaveComputer)) {
return new FilePath(localDependencyDir);
}
String pluginVersion = Hudson.getInstance().getPluginManager().getPlugin("artifactory").getVersion();
if (pluginVersion.contains(" ")) {
//Trim the plugin version in case we're working on a snapshot version (contains illegal chars)
pluginVersion = StringUtils.split(pluginVersion, " ")[0];
}
FilePath remoteDependencyDir = new FilePath(build.getWorkspace().getParent(),
"artifactory-plugin/" + pluginVersion);
if (!remoteDependencyDir.exists()) {
remoteDependencyDir.mkdirs();
}
//Check if the dependencies have already been transferred successfully
FilePath remoteDependencyMark = new FilePath(remoteDependencyDir, "ok");
if (!remoteDependencyMark.exists()) {
File[] localDependencies = localDependencyDir.listFiles();
for (File localDependency : localDependencies) {
FilePath remoteDependencyFilePath = new FilePath(remoteDependencyDir, localDependency.getName());
if (!remoteDependencyFilePath.exists()) {
FilePath localDependencyFilePath = new FilePath(localDependency);
localDependencyFilePath.copyTo(remoteDependencyFilePath);
}
}
//Mark that all the dependencies have been transferred successfully for future references
remoteDependencyMark.touch(System.currentTimeMillis());
}
return remoteDependencyDir;
}
| public static FilePath getActualDependencyDirectory(AbstractBuild build, File localDependencyFile)
throws IOException, InterruptedException {
File localDependencyDir = localDependencyFile.getParentFile();
// if (!(Computer.currentComputer() instanceof SlaveComputer)) {
// return new FilePath(localDependencyDir);
// }
String pluginVersion = Hudson.getInstance().getPluginManager().getPlugin("artifactory").getVersion();
if (pluginVersion.contains(" ")) {
//Trim the plugin version in case we're working on a snapshot version (contains illegal chars)
pluginVersion = StringUtils.split(pluginVersion, " ")[0];
}
FilePath remoteDependencyDir = new FilePath(build.getBuiltOn().getRootPath(),"cache/artifactory-plugin/" + pluginVersion);
if (!remoteDependencyDir.exists()) {
remoteDependencyDir.mkdirs();
}
//Check if the dependencies have already been transferred successfully
FilePath remoteDependencyMark = new FilePath(remoteDependencyDir, "ok");
if (!remoteDependencyMark.exists()) {
File[] localDependencies = localDependencyDir.listFiles();
for (File localDependency : localDependencies) {
if (localDependency.getName().equals("classes.jar"))
// skip classes in this plugin source tree.
// TODO: for a proper long term fix, see my comment in JENKINS-18401
continue;
FilePath remoteDependencyFilePath = new FilePath(remoteDependencyDir, localDependency.getName());
if (!remoteDependencyFilePath.exists()) {
FilePath localDependencyFilePath = new FilePath(localDependency);
localDependencyFilePath.copyTo(remoteDependencyFilePath);
}
}
//Mark that all the dependencies have been transferred successfully for future references
remoteDependencyMark.touch(System.currentTimeMillis());
}
return remoteDependencyDir;
}
|
diff --git a/src/com/android/wallpaper/nexus/NexusRS.java b/src/com/android/wallpaper/nexus/NexusRS.java
index c16ea69..20b7dd3 100644
--- a/src/com/android/wallpaper/nexus/NexusRS.java
+++ b/src/com/android/wallpaper/nexus/NexusRS.java
@@ -1,180 +1,178 @@
/*
* Copyright (C) 2009 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.wallpaper.nexus;
import static android.renderscript.Element.RGBA_8888;
import static android.renderscript.Element.RGB_565;
import static android.renderscript.ProgramStore.DepthFunc.ALWAYS;
import static android.renderscript.Sampler.Value.LINEAR;
import static android.renderscript.Sampler.Value.CLAMP;
import static android.renderscript.Sampler.Value.WRAP;
import com.android.wallpaper.R;
import com.android.wallpaper.RenderScriptScene;
import android.app.WallpaperManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Bundle;
import android.renderscript.*;
import android.renderscript.ProgramStore.BlendDstFunc;
import android.renderscript.ProgramStore.BlendSrcFunc;
import android.view.SurfaceHolder;
import java.util.TimeZone;
class NexusRS extends RenderScriptScene {
private final BitmapFactory.Options mOptionsARGB = new BitmapFactory.Options();
private ProgramVertexFixedFunction.Constants mPvOrthoAlloc;
private float mXOffset;
private ScriptC_nexus mScript;
public NexusRS(int width, int height) {
super(width, height);
mOptionsARGB.inScaled = false;
mOptionsARGB.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
@Override
public void setOffset(float xOffset, float yOffset, int xPixels, int yPixels) {
mXOffset = xOffset;
mScript.set_gXOffset(xOffset);
}
@Override
public void start() {
super.start();
}
@Override
public void resize(int width, int height) {
super.resize(width, height); // updates mWidth, mHeight
// android.util.Log.d("NexusRS", String.format("resize(%d, %d)", width, height));
}
@Override
protected ScriptC createScript() {
mScript = new ScriptC_nexus(mRS, mResources, R.raw.nexus);
createProgramFragmentStore();
createProgramFragment();
createProgramVertex();
createState();
mScript.set_gTBackground(loadTexture(R.drawable.pyramid_background));
mScript.set_gTPulse(loadTextureARGB(R.drawable.pulse));
mScript.set_gTGlow(loadTextureARGB(R.drawable.glow));
mScript.setTimeZone(TimeZone.getDefault().getID());
mScript.invoke_initPulses();
return mScript;
}
private void createState() {
int mode;
try {
mode = mResources.getInteger(R.integer.nexus_mode);
} catch (Resources.NotFoundException exc) {
mode = 0; // standard nexus mode
}
mScript.set_gIsPreview(isPreview() ? 1 : 0);
mScript.set_gMode(mode);
mScript.set_gXOffset(0.f);
}
private Allocation loadTexture(int id) {
return Allocation.createFromBitmapResource(mRS, mResources, id);
}
private Allocation loadTextureARGB(int id) {
Bitmap b = BitmapFactory.decodeResource(mResources, id, mOptionsARGB);
return Allocation.createFromBitmap(mRS, b);
}
private void createProgramFragment() {
// sampler and program fragment for pulses
ProgramFragmentFixedFunction.Builder builder = new ProgramFragmentFixedFunction.Builder(mRS);
builder.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.MODULATE,
ProgramFragmentFixedFunction.Builder.Format.RGBA, 0);
ProgramFragment pft = builder.create();
pft.bindSampler(Sampler.WRAP_LINEAR(mRS), 0);
mScript.set_gPFTexture(pft);
// sampler and program fragment for background image
builder = new ProgramFragmentFixedFunction.Builder(mRS);
builder.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.MODULATE,
ProgramFragmentFixedFunction.Builder.Format.RGB, 0);
ProgramFragment pft565 = builder.create();
pft565.bindSampler(Sampler.CLAMP_NEAREST(mRS), 0);
mScript.set_gPFTexture565(pft565);
}
private void createProgramFragmentStore() {
ProgramStore.Builder builder = new ProgramStore.Builder(mRS);
builder.setDepthFunc(ALWAYS);
builder.setBlendFunc(BlendSrcFunc.ONE, BlendDstFunc.ONE);
builder.setDitherEnabled(false);
ProgramStore solid = builder.create();
mRS.bindProgramStore(solid);
builder.setBlendFunc(BlendSrcFunc.SRC_ALPHA, BlendDstFunc.ONE);
mScript.set_gPSBlend(builder.create());
}
private void createProgramVertex() {
mPvOrthoAlloc = new ProgramVertexFixedFunction.Constants(mRS);
Matrix4f proj = new Matrix4f();
proj.loadOrthoWindow(mWidth, mHeight);
mPvOrthoAlloc.setProjection(proj);
ProgramVertexFixedFunction.Builder pvb = new ProgramVertexFixedFunction.Builder(mRS);
pvb.setTextureMatrixEnable(true);
ProgramVertex pv = pvb.create();
((ProgramVertexFixedFunction)pv).bindConstants(mPvOrthoAlloc);
mRS.bindProgramVertex(pv);
}
@Override
public Bundle onCommand(String action, int x, int y, int z, Bundle extras,
boolean resultRequested) {
- final int dw = mWidth;
- final int bw = 960; // XXX: hardcoded width of background texture
if (mWidth < mHeight) {
// nexus.rs ignores the xOffset when rotated; we shall endeavor to do so as well
- x = (int) (x + mXOffset * (bw-dw));
+ x = (int) (x + mXOffset * mWidth);
}
// android.util.Log.d("NexusRS", String.format(
// "dw=%d, bw=%d, xOffset=%g, x=%d",
// dw, bw, mWorldState.xOffset, x));
if (WallpaperManager.COMMAND_TAP.equals(action)
|| WallpaperManager.COMMAND_SECONDARY_TAP.equals(action)
|| WallpaperManager.COMMAND_DROP.equals(action)) {
mScript.invoke_addTap(x, y);
}
return null;
}
}
| false | true | public Bundle onCommand(String action, int x, int y, int z, Bundle extras,
boolean resultRequested) {
final int dw = mWidth;
final int bw = 960; // XXX: hardcoded width of background texture
if (mWidth < mHeight) {
// nexus.rs ignores the xOffset when rotated; we shall endeavor to do so as well
x = (int) (x + mXOffset * (bw-dw));
}
// android.util.Log.d("NexusRS", String.format(
// "dw=%d, bw=%d, xOffset=%g, x=%d",
// dw, bw, mWorldState.xOffset, x));
if (WallpaperManager.COMMAND_TAP.equals(action)
|| WallpaperManager.COMMAND_SECONDARY_TAP.equals(action)
|| WallpaperManager.COMMAND_DROP.equals(action)) {
mScript.invoke_addTap(x, y);
}
return null;
}
| public Bundle onCommand(String action, int x, int y, int z, Bundle extras,
boolean resultRequested) {
if (mWidth < mHeight) {
// nexus.rs ignores the xOffset when rotated; we shall endeavor to do so as well
x = (int) (x + mXOffset * mWidth);
}
// android.util.Log.d("NexusRS", String.format(
// "dw=%d, bw=%d, xOffset=%g, x=%d",
// dw, bw, mWorldState.xOffset, x));
if (WallpaperManager.COMMAND_TAP.equals(action)
|| WallpaperManager.COMMAND_SECONDARY_TAP.equals(action)
|| WallpaperManager.COMMAND_DROP.equals(action)) {
mScript.invoke_addTap(x, y);
}
return null;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java
index 05fb9825b..d888a2646 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java
@@ -1,1775 +1,1775 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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.mylyn.internal.tasks.ui.views;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonThemes;
import org.eclipse.mylyn.internal.provisional.commons.ui.DelayedRefreshJob;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.core.UncategorizedTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.UnmatchedTaskContainer;
import org.eclipse.mylyn.internal.tasks.ui.AbstractTaskListFilter;
import org.eclipse.mylyn.internal.tasks.ui.CategorizedPresentation;
import org.eclipse.mylyn.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylyn.internal.tasks.ui.ScheduledPresentation;
import org.eclipse.mylyn.internal.tasks.ui.TaskArchiveFilter;
import org.eclipse.mylyn.internal.tasks.ui.TaskCompletionFilter;
import org.eclipse.mylyn.internal.tasks.ui.TaskListPatternFilter;
import org.eclipse.mylyn.internal.tasks.ui.TaskPriorityFilter;
import org.eclipse.mylyn.internal.tasks.ui.TaskTransfer;
import org.eclipse.mylyn.internal.tasks.ui.TaskWorkingSetFilter;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPreferenceConstants;
import org.eclipse.mylyn.internal.tasks.ui.actions.CollapseAllAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.CopyTaskDetailsAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.DeleteAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.EditRepositoryPropertiesAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.ExpandAllAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.FilterCompletedTasksAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.GoIntoAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.GoUpAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.GroupSubTasksAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.LinkWithEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.MarkTaskCompleteAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.MarkTaskIncompleteAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.OpenTaskListElementAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.OpenTasksUiPreferencesAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.OpenWithBrowserAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.PresentationDropDownSelectionAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.RemoveFromCategoryAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.RenameAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.SynchronizeAutomaticallyAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.TaskActivateAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.TaskDeactivateAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.TaskListSortAction;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskListChangeAdapter;
import org.eclipse.mylyn.internal.tasks.ui.util.TaskDragSourceListener;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListTableSorter.SortByIndex;
import org.eclipse.mylyn.internal.tasks.ui.workingsets.TaskWorkingSetUpdater;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskActivityListener;
import org.eclipse.mylyn.tasks.core.ITaskElement;
import org.eclipse.mylyn.tasks.core.ITaskListChangeListener;
import org.eclipse.mylyn.tasks.core.TaskActivityAdapter;
import org.eclipse.mylyn.tasks.core.TaskContainerDelta;
import org.eclipse.mylyn.tasks.core.ITask.PriorityLevel;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.RTFTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Region;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Scrollable;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageListener;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
import org.eclipse.ui.themes.IThemeManager;
/**
* @author Mik Kersten
* @author Ken Sueda
* @author Eugene Kuleshov
*/
public class TaskListView extends ViewPart implements IPropertyChangeListener {
private final class TaskListRefreshJob extends DelayedRefreshJob {
private TaskListRefreshJob(TreeViewer treeViewer, String name) {
super(treeViewer, name);
}
@Override
protected void refresh(Object[] items) {
if (items == null) {
treeViewer.refresh(true);
} else if (items.length > 0) {
try {
for (Object item : items) {
if (item instanceof ITask) {
ITask task = (ITask) item;
treeViewer.refresh(task, true);
} else {
treeViewer.refresh(item, true);
}
updateExpansionState(item);
}
} catch (SWTException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Failed to refresh viewer: "
+ treeViewer, e));
}
}
updateToolTip(false);
}
@Override
protected void updateExpansionState(Object item) {
if (TaskListView.this.isFocusedMode()) {
TaskListView.this.getViewer().expandToLevel(item, 3);
}
}
}
public static final String ID = "org.eclipse.mylyn.tasks.ui.views.tasks";
public static final String LABEL_VIEW = "Tasks";
private static final String MEMENTO_KEY_SORT_DIRECTION = "sortDirection";
private static final String MEMENTO_KEY_SORTER = "sorter";
private static final String MEMENTO_KEY_SORTER2 = "sorter2";
private static final String MEMENTO_KEY_SORT_INDEX = "sortIndex";
private static final String MEMENTO_SORT_INDEX = "org.eclipse.mylyn.tasklist.ui.views.tasklist.sortIndex";
private static final String MEMENTO_LINK_WITH_EDITOR = "linkWithEditor";
private static final String MEMENTO_PRESENTATION = "presentation";
private static final String ID_SEPARATOR_NEW = "new";
public static final String ID_SEPARATOR_OPERATIONS = "operations";
public static final String ID_SEPARATOR_CONTEXT = "context";
public static final String ID_SEPARATOR_TASKS = "tasks";
private static final String ID_SEPARATOR_FILTERS = "filters";
private static final String ID_SEPARATOR_REPOSITORY = "repository";
private static final String ID_SEPARATOR_PROPERTIES = "properties";
private static final String ID_SEPARATOR_NAVIGATE = "navigate";
private static final String LABEL_NO_TASKS = "no task active";
private final static int SIZE_MAX_SELECTION_HISTORY = 10;
private static final String PART_NAME = "Task List";
static final String[] PRIORITY_LEVELS = { PriorityLevel.P1.toString(), PriorityLevel.P2.toString(),
PriorityLevel.P3.toString(), PriorityLevel.P4.toString(), PriorityLevel.P5.toString() };
public static final String[] PRIORITY_LEVEL_DESCRIPTIONS = { PriorityLevel.P1.getDescription(),
PriorityLevel.P2.getDescription(), PriorityLevel.P3.getDescription(), PriorityLevel.P4.getDescription(),
PriorityLevel.P5.getDescription() };
private static List<AbstractTaskListPresentation> presentationsPrimary = new ArrayList<AbstractTaskListPresentation>();
private static List<AbstractTaskListPresentation> presentationsSecondary = new ArrayList<AbstractTaskListPresentation>();
private boolean focusedMode = false;
private boolean linkWithEditor;
private final TaskListCellModifier taskListCellModifier = new TaskListCellModifier(this);
private IThemeManager themeManager;
private TaskListFilteredTree filteredTree;
private DrillDownAdapter drillDownAdapter;
private AbstractTaskContainer drilledIntoCategory = null;
private GoIntoAction goIntoAction;
private GoUpAction goUpAction;
private CopyTaskDetailsAction copyDetailsAction;
private OpenTaskListElementAction openAction;
private OpenWithBrowserAction openWithBrowser;
private RenameAction renameAction;
private CollapseAllAction collapseAll;
private ExpandAllAction expandAll;
private DeleteAction deleteAction;
private RemoveFromCategoryAction removeFromCategoryAction;
private final TaskActivateAction activateAction = new TaskActivateAction();
private final TaskDeactivateAction deactivateAction = new TaskDeactivateAction();
private FilterCompletedTasksAction filterCompleteTask;
private GroupSubTasksAction filterSubTasksAction;
private SynchronizeAutomaticallyAction synchronizeAutomatically;
private OpenTasksUiPreferencesAction openPreferencesAction;
//private FilterArchiveContainerAction filterArchiveCategory;
private PriorityDropDownAction filterOnPriorityAction;
private TaskListSortAction sortDialogAction;
private PresentationDropDownSelectionAction presentationDropDownSelectionAction;
private LinkWithEditorAction linkWithEditorAction;
private final TaskPriorityFilter filterPriority = new TaskPriorityFilter();
private final TaskCompletionFilter filterComplete = new TaskCompletionFilter();
private final TaskArchiveFilter filterArchive = new TaskArchiveFilter();
private TaskWorkingSetFilter filterWorkingSet;
private final Set<AbstractTaskListFilter> filters = new HashSet<AbstractTaskListFilter>();
protected String[] columnNames = new String[] { "Summary" };
protected int[] columnWidths = new int[] { 200 };
private TreeColumn[] columns;
private IMemento taskListMemento;
private AbstractTaskListPresentation currentPresentation;
private TaskTableLabelProvider taskListTableLabelProvider;
private TaskListTableSorter tableSorter;
private Color categoryGradientStart;
private Color categoryGradientEnd;
private final IPageListener PAGE_LISTENER = new IPageListener() {
public void pageActivated(IWorkbenchPage page) {
filteredTree.indicateActiveTaskWorkingSet();
}
public void pageClosed(IWorkbenchPage page) {
// ignore
}
public void pageOpened(IWorkbenchPage page) {
// ignore
}
};
private final LinkedHashMap<String, IStructuredSelection> lastSelectionByTaskHandle = new LinkedHashMap<String, IStructuredSelection>(
SIZE_MAX_SELECTION_HISTORY);
/**
* True if the view should indicate that interaction monitoring is paused
*/
protected boolean isPaused = false;
boolean synchronizationOverlaid = false;
private final Listener CATEGORY_GRADIENT_DRAWER = new Listener() {
public void handleEvent(Event event) {
if (event.item.getData() instanceof ITaskElement && !(event.item.getData() instanceof ITask)) {
Scrollable scrollable = (Scrollable) event.widget;
GC gc = event.gc;
Rectangle area = scrollable.getClientArea();
Rectangle rect = event.getBounds();
/* Paint the selection beyond the end of last column */
expandRegion(event, scrollable, gc, area);
/* Draw Gradient Rectangle */
Color oldForeground = gc.getForeground();
Color oldBackground = gc.getBackground();
gc.setForeground(categoryGradientEnd);
gc.drawLine(0, rect.y, area.width, rect.y);
gc.setForeground(categoryGradientStart);
gc.setBackground(categoryGradientEnd);
// gc.setForeground(categoryGradientStart);
// gc.setBackground(categoryGradientEnd);
// gc.setForeground(new Clr(Display.getCurrent(), 255, 0, 0));
gc.fillGradientRectangle(0, rect.y + 1, area.width, rect.height, true);
/* Bottom Line */
// gc.setForeground();
gc.setForeground(categoryGradientEnd);
gc.drawLine(0, rect.y + rect.height - 1, area.width, rect.y + rect.height - 1);
gc.setForeground(oldForeground);
gc.setBackground(oldBackground);
/* Mark as Background being handled */
event.detail &= ~SWT.BACKGROUND;
}
}
private void expandRegion(Event event, Scrollable scrollable, GC gc, Rectangle area) {
int columnCount;
if (scrollable instanceof Table) {
columnCount = ((Table) scrollable).getColumnCount();
} else {
columnCount = ((Tree) scrollable).getColumnCount();
}
if (event.index == columnCount - 1 || columnCount == 0) {
int width = area.x + area.width - event.x;
if (width > 0) {
Region region = new Region();
gc.getClipping(region);
region.add(event.x, event.y, width, event.height);
gc.setClipping(region);
region.dispose();
}
}
}
};
private boolean gradientListenerAdded = false;
private final ITaskActivityListener TASK_ACTIVITY_LISTENER = new TaskActivityAdapter() {
@Override
public void activityReset() {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshJob.refresh();
}
});
}
@Override
public void taskActivated(final ITask task) {
if (task != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
updateDescription();
selectedAndFocusTask(task);
filteredTree.indicateActiveTask(task);
refresh();
}
});
}
}
@Override
public void taskDeactivated(final ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshJob.refreshTask(task);
updateDescription();
filteredTree.indicateNoActiveTask();
}
});
}
};
private final ITaskListChangeListener TASKLIST_CHANGE_LISTENER = new TaskListChangeAdapter() {
@Override
public void taskListRead() {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshJob.refresh();
}
});
}
@Override
public void containersChanged(final Set<TaskContainerDelta> deltas) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
for (TaskContainerDelta taskContainerDelta : deltas) {
if (ScheduledPresentation.ID.equals(getCurrentPresentation().getId())) {
// TODO: implement refresh policy for scheduled presentation
refreshJob.refresh();
} else {
switch (taskContainerDelta.getKind()) {
case ROOT:
refreshJob.refresh();
break;
case ADDED:
refreshJob.refresh();
break;
case REMOVED:
refreshJob.refresh();
break;
default:
if (taskContainerDelta.getContainer() == null) {
refreshJob.refresh();
} else {
refreshJob.refreshTask(taskContainerDelta.getContainer());
}
}
}
}
}
});
}
};
private final IPropertyChangeListener THEME_CHANGE_LISTENER = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME)
|| CommonThemes.isCommonTheme(event.getProperty())) {
configureGradientColors();
taskListTableLabelProvider.setCategoryBackgroundColor(themeManager.getCurrentTheme()
.getColorRegistry()
.get(CommonThemes.COLOR_CATEGORY));
getViewer().refresh();
}
}
};
private TaskListToolTip taskListToolTip;
private void configureGradientColors() {
categoryGradientStart = themeManager.getCurrentTheme().getColorRegistry().get(
CommonThemes.COLOR_CATEGORY_GRADIENT_START);
categoryGradientEnd = themeManager.getCurrentTheme().getColorRegistry().get(
CommonThemes.COLOR_CATEGORY_GRADIENT_END);
boolean customized = true;
if (categoryGradientStart != null && categoryGradientStart.getRed() == 240
&& categoryGradientStart.getGreen() == 240 && categoryGradientStart.getBlue() == 240
&& categoryGradientEnd != null && categoryGradientEnd.getRed() == 220
&& categoryGradientEnd.getGreen() == 220 && categoryGradientEnd.getBlue() == 220) {
customized = false;
}
if (gradientListenerAdded == false && categoryGradientStart != null
&& !categoryGradientStart.equals(categoryGradientEnd)) {
getViewer().getTree().addListener(SWT.EraseItem, CATEGORY_GRADIENT_DRAWER);
gradientListenerAdded = true;
if (!customized) {
// Set parent-based colors
Color parentBackground = getViewer().getTree().getParent().getBackground();
double GRADIENT_TOP = 1.05;// 1.02;
double GRADIENT_BOTTOM = .995;// 1.035;
int red = Math.min(255, (int) (parentBackground.getRed() * GRADIENT_TOP));
int green = Math.min(255, (int) (parentBackground.getGreen() * GRADIENT_TOP));
int blue = Math.min(255, (int) (parentBackground.getBlue() * GRADIENT_TOP));
try {
categoryGradientStart = new Color(Display.getDefault(), red, green, blue);
} catch (Exception e) {
categoryGradientStart = getViewer().getTree().getParent().getBackground();
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not set color: " + red
+ ", " + green + ", " + blue, e));
}
red = Math.max(0, (int) (parentBackground.getRed() / GRADIENT_BOTTOM));
green = Math.max(0, (int) (parentBackground.getGreen() / GRADIENT_BOTTOM));
blue = Math.max(0, (int) (parentBackground.getBlue() / GRADIENT_BOTTOM));
if (red > 255) {
red = 255;
}
try {
categoryGradientEnd = new Color(Display.getDefault(), red, green, blue);
} catch (Exception e) {
categoryGradientStart = getViewer().getTree().getParent().getBackground();
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not set color: " + red
+ ", " + green + ", " + blue, e));
}
}
} else if (categoryGradientStart != null && categoryGradientStart.equals(categoryGradientEnd)) {
getViewer().getTree().removeListener(SWT.EraseItem, CATEGORY_GRADIENT_DRAWER);
gradientListenerAdded = false;
}
}
public static TaskListView getFromActivePerspective() {
if (PlatformUI.isWorkbenchRunning()) {
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (activePage != null) {
IViewPart view = activePage.findView(ID);
if (view instanceof TaskListView) {
return (TaskListView) view;
}
}
}
return null;
}
public static TaskListView openInActivePerspective() {
try {
return (TaskListView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ID);
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not show Task List view", e));
return null;
}
}
public TaskListView() {
PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(this);
TasksUiPlugin.getTaskActivityManager().addActivityListener(TASK_ACTIVITY_LISTENER);
TasksUiInternal.getTaskList().addChangeListener(TASKLIST_CHANGE_LISTENER);
}
@Override
public void dispose() {
super.dispose();
TasksUiInternal.getTaskList().removeChangeListener(TASKLIST_CHANGE_LISTENER);
TasksUiPlugin.getTaskActivityManager().removeActivityListener(TASK_ACTIVITY_LISTENER);
PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(this);
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().removePageListener(PAGE_LISTENER);
}
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
if (themeManager != null) {
themeManager.removePropertyChangeListener(THEME_CHANGE_LISTENER);
}
categoryGradientStart.dispose();
categoryGradientEnd.dispose();
}
private void updateDescription() {
ITask task = TasksUi.getTaskActivityManager().getActiveTask();
if (getSite() == null || getSite().getPage() == null) {
return;
}
IViewReference reference = getSite().getPage().findViewReference(ID);
boolean shouldSetDescription = false;
if (reference != null && reference.isFastView() && !getSite().getPage().isPartVisible(this)) {
shouldSetDescription = true;
}
if (task != null) {
setTitleToolTip(PART_NAME + " (" + task.getSummary() + ")");
if (shouldSetDescription) {
setContentDescription(task.getSummary());
} else {
setContentDescription("");
}
} else {
setTitleToolTip(PART_NAME);
if (shouldSetDescription) {
setContentDescription(LABEL_NO_TASKS);
} else {
setContentDescription("");
}
}
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
init(site);
this.taskListMemento = memento;
}
@Override
public void saveState(IMemento memento) {
IMemento sorter = memento.createChild(MEMENTO_SORT_INDEX);
IMemento m = sorter.createChild(MEMENTO_KEY_SORTER);
switch (tableSorter.getSortByIndex()) {
case SUMMARY:
m.putInteger(MEMENTO_KEY_SORT_INDEX, 1);
break;
case DATE_CREATED:
m.putInteger(MEMENTO_KEY_SORT_INDEX, 2);
break;
default:
m.putInteger(MEMENTO_KEY_SORT_INDEX, 0);
}
m.putInteger(MEMENTO_KEY_SORT_DIRECTION, tableSorter.getSortDirection());
IMemento m2 = sorter.createChild(MEMENTO_KEY_SORTER2);
switch (tableSorter.getSortByIndex2()) {
case SUMMARY:
m2.putInteger(MEMENTO_KEY_SORT_INDEX, 1);
break;
case DATE_CREATED:
m2.putInteger(MEMENTO_KEY_SORT_INDEX, 2);
break;
default:
m2.putInteger(MEMENTO_KEY_SORT_INDEX, 0);
}
m2.putInteger(MEMENTO_KEY_SORT_DIRECTION, tableSorter.getSortDirection2());
memento.putString(MEMENTO_LINK_WITH_EDITOR, Boolean.toString(linkWithEditor));
memento.putString(MEMENTO_PRESENTATION, currentPresentation.getId());
}
private void restoreState() {
tableSorter = null;
if (taskListMemento != null) {
IMemento sorterMemento = taskListMemento.getChild(MEMENTO_SORT_INDEX);
int restoredSortIndex = 0;
if (sorterMemento != null) {
int sortDirection = -1;
tableSorter = new TaskListTableSorter(this);
IMemento m = sorterMemento.getChild(MEMENTO_KEY_SORTER);
if (m != null) {
Integer sortIndexInt = m.getInteger(MEMENTO_KEY_SORT_INDEX);
if (sortIndexInt != null) {
restoredSortIndex = sortIndexInt.intValue();
}
Integer sortDirInt = m.getInteger(MEMENTO_KEY_SORT_DIRECTION);
if (sortDirInt != null) {
sortDirection = sortDirInt.intValue();
tableSorter.setSortDirection(sortDirection);
switch (restoredSortIndex) {
case 1:
tableSorter.setSortByIndex(SortByIndex.SUMMARY);
break;
case 2:
tableSorter.setSortByIndex(SortByIndex.DATE_CREATED);
break;
default:
tableSorter.setSortByIndex(SortByIndex.PRIORITY);
}
}
}
IMemento m2 = sorterMemento.getChild(MEMENTO_KEY_SORTER2);
if (m2 != null) {
Integer sortIndexInt = m2.getInteger(MEMENTO_KEY_SORT_INDEX);
if (sortIndexInt != null) {
restoredSortIndex = sortIndexInt.intValue();
}
Integer sortDirInt = m2.getInteger(MEMENTO_KEY_SORT_DIRECTION);
if (sortDirInt != null) {
sortDirection = sortDirInt.intValue();
tableSorter.setSortDirection2(sortDirection);
switch (restoredSortIndex) {
case 1:
tableSorter.setSortByIndex2(SortByIndex.SUMMARY);
break;
case 2:
tableSorter.setSortByIndex2(SortByIndex.DATE_CREATED);
break;
default:
tableSorter.setSortByIndex2(SortByIndex.PRIORITY);
}
}
}
}
applyPresentation(taskListMemento.getString(MEMENTO_PRESENTATION));
}
if (tableSorter == null) {
tableSorter = new TaskListTableSorter(this);
}
filterWorkingSet = new TaskWorkingSetFilter();
filterWorkingSet.updateWorkingSet(getSite().getPage().getAggregateWorkingSet());
addFilter(filterWorkingSet);
addFilter(filterPriority);
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TasksUiPreferenceConstants.FILTER_COMPLETE_MODE)) {
addFilter(filterComplete);
}
//if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TasksUiPreferenceConstants.FILTER_ARCHIVE_MODE)) {
addFilter(filterArchive);
//}
// Restore "link with editor" value; by default true
boolean linkValue = true;
if (taskListMemento != null && taskListMemento.getString(MEMENTO_LINK_WITH_EDITOR) != null) {
linkValue = Boolean.parseBoolean(taskListMemento.getString(MEMENTO_LINK_WITH_EDITOR));
}
setLinkWithEditor(linkValue);
getViewer().setSorter(tableSorter);
getViewer().refresh();
}
@Override
public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
- filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | /* SWT.H_SCROLL | */SWT.V_SCROLL
+ filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | /* SWT.H_SCROLL | */SWT.V_SCROLL | SWT.NO_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
// Set to empty string to disable native tooltips (windows only?)
// bug#160897
// http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg29614.html
getViewer().getTree().setToolTipText("");
getViewer().getTree().setHeaderVisible(false);
getViewer().setUseHashlookup(true);
refreshJob = new TaskListRefreshJob(getViewer(), "Task List Refresh");
configureColumns(columnNames, columnWidths);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(CommonThemes.COLOR_CATEGORY);
taskListTableLabelProvider = new TaskTableLabelProvider(new TaskElementLabelProvider(true),
PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground);
getViewer().setLabelProvider(taskListTableLabelProvider);
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = textEditor;
// editors[1] = new ComboBoxCellEditor(getViewer().getTree(),
// editors[2] = new CheckboxCellEditor();
getViewer().setCellEditors(editors);
getViewer().setCellModifier(taskListCellModifier);
tableSorter = new TaskListTableSorter(this);
getViewer().setSorter(tableSorter);
applyPresentation(CategorizedPresentation.ID);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setInput(getViewSite());
final int activationImageOffset = 20;
CustomTaskListDecorationDrawer customDrawer = new CustomTaskListDecorationDrawer(this, activationImageOffset);
getViewer().getTree().addListener(SWT.EraseItem, customDrawer);
getViewer().getTree().addListener(SWT.PaintItem, customDrawer);
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDown(MouseEvent e) {
// NOTE: need e.x offset for Linux/GTK, which does not see
// left-aligned items in tree
Object selectedNode = ((Tree) e.widget).getItem(new Point(e.x + 70, e.y));
if (selectedNode instanceof TreeItem) {
Object selectedObject = ((TreeItem) selectedNode).getData();
if (selectedObject instanceof ITask) {
if (e.x > activationImageOffset && e.x < activationImageOffset + 13) {
taskListCellModifier.toggleTaskActivation((TreeItem) selectedNode);
}
}
}
}
public void mouseDoubleClick(MouseEvent e) {
// ignore
}
public void mouseUp(MouseEvent e) {
// ignore
}
});
// TODO make these proper commands and move code into TaskListViewCommands
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if ((e.keyCode & SWT.KEYCODE_BIT) != 0) {
// Do nothing here since it is key code
} else if (e.keyCode == SWT.ESC) {
taskListToolTip.hide();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char) e.keyCode) || Character.isDigit((char) e.keyCode)) {
String string = new Character((char) e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
getViewer().addTreeListener(new ITreeViewerListener() {
public void treeCollapsed(final TreeExpansionEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
getViewer().refresh(event.getElement());
}
});
}
public void treeExpanded(final TreeExpansionEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
getViewer().refresh(event.getElement());
}
});
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskElement) {
updateActionEnablement(renameAction, (ITaskElement) selectedObject);
updateActionEnablement(deleteAction, (ITaskElement) selectedObject);
}
}
});
taskListToolTip = new TaskListToolTip(getViewer().getControl());
// update tooltip contents
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateToolTip(true);
}
});
getViewer().getTree().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
taskListToolTip.hide();
}
});
makeActions();
hookGlobalActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
configureGradientColors();
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
updateDescription();
IContextService contextSupport = (IContextService) getSite().getService(IContextService.class);
if (contextSupport != null) {
contextSupport.activateContext(TaskListView.ID);
}
getSite().setSelectionProvider(getViewer());
getSite().getPage().addPartListener(editorListener);
// Need to do this because the page, which holds the active working set is not around on creation, see bug 203179
PlatformUI.getWorkbench().getActiveWorkbenchWindow().addPageListener(PAGE_LISTENER);
}
private void hookGlobalActions() {
IActionBars bars = getViewSite().getActionBars();
bars.setGlobalActionHandler(ActionFactory.DELETE.getId(), deleteAction);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyDetailsAction);
}
private void applyPresentation(String id) {
if (id != null) {
for (AbstractTaskListPresentation presentation : presentationsPrimary) {
if (id.equals(presentation.getId())) {
applyPresentation(presentation);
return;
}
}
for (AbstractTaskListPresentation presentation : presentationsSecondary) {
if (id.equals(presentation.getId())) {
applyPresentation(presentation);
return;
}
}
}
}
public void applyPresentation(AbstractTaskListPresentation presentation) {
try {
getViewer().getControl().setRedraw(false);
if (!filteredTree.getFilterControl().getText().equals("")) {
filteredTree.getFilterControl().setText("");
}
AbstractTaskListContentProvider contentProvider = presentation.getContentProvider(this);
getViewer().setContentProvider(contentProvider);
refresh(true);
currentPresentation = presentation;
} finally {
getViewer().getControl().setRedraw(true);
}
}
public AbstractTaskListPresentation getCurrentPresentation() {
return currentPresentation;
}
private void configureColumns(final String[] columnNames, final int[] columnWidths) {
TreeColumnLayout layout = (TreeColumnLayout) getViewer().getTree().getParent().getLayout();
getViewer().setColumnProperties(columnNames);
columns = new TreeColumn[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TreeColumn(getViewer().getTree(), 0);
columns[i].setText(columnNames[i]);
if (i == 0) {
layout.setColumnData(columns[i], new ColumnWeightData(100));
} else {
layout.setColumnData(columns[i], new ColumnPixelData(columnWidths[i]));
}
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tableSorter.setSortDirection(tableSorter.getSortDirection() * -1);
getViewer().refresh(false);
}
});
columns[i].addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
for (int j = 0; j < columnWidths.length; j++) {
if (columns[j].equals(e.getSource())) {
columnWidths[j] = columns[j].getWidth();
}
}
}
public void controlMoved(ControlEvent e) {
// don't care if the control is moved
}
});
}
}
/**
* Tracks editor activation and jump to corresponding task, if applicable
*/
private final IPartListener editorListener = new IPartListener() {
private void jumpToEditor(IWorkbenchPart part) {
if (!linkWithEditor || !(part instanceof IEditorPart)) {
return;
}
jumpToEditorTask((IEditorPart) part);
}
public void partActivated(IWorkbenchPart part) {
if (part == TaskListView.this) {
updateDescription();
} else {
jumpToEditor(part);
}
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
if (part == TaskListView.this) {
IViewReference reference = getSite().getPage().findViewReference(ID);
if (reference != null && reference.isFastView()) {
updateDescription();
}
taskListToolTip.hide();
}
}
public void partOpened(IWorkbenchPart part) {
}
};
private void initDragAndDrop(Composite parent) {
Transfer[] dragTypes = new Transfer[] { TaskTransfer.getInstance(), FileTransfer.getInstance() };
Transfer[] dropTypes = new Transfer[] { TaskTransfer.getInstance(), FileTransfer.getInstance(),
TextTransfer.getInstance(), RTFTransfer.getInstance() };
getViewer().addDragSupport(DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK, dragTypes,
new TaskDragSourceListener(getViewer()));
getViewer().addDropSupport(DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT, dropTypes,
new TaskListDropAdapter(getViewer()));
}
void expandToActiveTasks() {
final IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().asyncExec(new Runnable() {
public void run() {
ITask task = TasksUi.getTaskActivityManager().getActiveTask();
if (task != null) {
getViewer().expandToLevel(task, 0);
}
}
});
}
private void hookContextMenu() {
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
TaskListView.this.fillContextMenu(manager);
}
});
Menu menu = menuManager.createContextMenu(getViewer().getControl());
getViewer().getControl().setMenu(menu);
getSite().registerContextMenu(menuManager, getViewer());
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
updateDrillDownActions();
manager.add(goUpAction);
manager.add(collapseAll);
manager.add(expandAll);
manager.add(new Separator(ID_SEPARATOR_FILTERS));
manager.add(sortDialogAction);
manager.add(filterOnPriorityAction);
manager.add(filterCompleteTask);
//manager.add(filterArchiveCategory);
manager.add(filterSubTasksAction);
manager.add(new Separator(ID_SEPARATOR_TASKS));
manager.add(synchronizeAutomatically);
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
filterOnPriorityAction.updateCheckedState();
}
});
// manager.add(new Separator());
manager.add(linkWithEditorAction);
manager.add(new Separator());
manager.add(openPreferencesAction);
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(new Separator(ID_SEPARATOR_NEW));
// manager.add(new Separator(ID_SEPARATOR_NAVIGATION));
manager.add(presentationDropDownSelectionAction);
// manager.add(previousTaskAction);
manager.add(new Separator(ID_SEPARATOR_CONTEXT));
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
/*
* TODO: clean up, consider relying on extension points for groups
*/
private void fillContextMenu(final IMenuManager manager) {
updateDrillDownActions();
final ITaskElement element;
final Object firstSelectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (firstSelectedObject instanceof ITaskElement) {
element = (ITaskElement) firstSelectedObject;
} else {
element = null;
}
final List<ITaskElement> selectedElements = getSelectedTaskContainers();
AbstractTask task = null;
if (element instanceof ITask) {
task = (AbstractTask) element;
}
manager.add(new Separator(ID_SEPARATOR_NEW));
manager.add(new Separator());
if (element instanceof ITask) {
addAction(openAction, manager, element);
}
addAction(openWithBrowser, manager, element);
if (task != null) {
if (task.isActive()) {
manager.add(deactivateAction);
} else {
manager.add(activateAction);
}
}
manager.add(new Separator());
Map<String, List<IDynamicSubMenuContributor>> dynamicMenuMap = TasksUiPlugin.getDefault().getDynamicMenuMap();
for (String menuPath : dynamicMenuMap.keySet()) {
if (!ID_SEPARATOR_CONTEXT.equals(menuPath)) {
for (final IDynamicSubMenuContributor contributor : dynamicMenuMap.get(menuPath)) {
SafeRunnable.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Menu contributor failed"));
}
public void run() throws Exception {
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
addMenuManager(subMenuManager, manager, element);
}
}
});
}
}
}
manager.add(new Separator(ID_SEPARATOR_NAVIGATE));
// manager.add(new Separator(ID_SEPARATOR_OPERATIONS));
manager.add(new Separator());
addAction(copyDetailsAction, manager, element);
if (task != null) {
// TODO: if selection parent is an Orphan container don't add this action
addAction(removeFromCategoryAction, manager, element);
}
// This should also test for null, or else nothing to delete!
addAction(deleteAction, manager, element);
if (!(element instanceof ITask)) {
addAction(renameAction, manager, element);
}
if (element != null && !(element instanceof ITask)) {
manager.add(goIntoAction);
}
if (drilledIntoCategory != null) {
manager.add(goUpAction);
}
manager.add(new Separator(ID_SEPARATOR_CONTEXT));
manager.add(new Separator(ID_SEPARATOR_OPERATIONS));
if (element instanceof ITask) {
for (String menuPath : dynamicMenuMap.keySet()) {
if (ID_SEPARATOR_CONTEXT.equals(menuPath)) {
for (IDynamicSubMenuContributor contributor : dynamicMenuMap.get(menuPath)) {
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
addMenuManager(subMenuManager, manager, element);
}
}
}
}
}
if (element instanceof IRepositoryQuery) {
EditRepositoryPropertiesAction repositoryPropertiesAction = new EditRepositoryPropertiesAction();
repositoryPropertiesAction.selectionChanged(new StructuredSelection(element));
if (repositoryPropertiesAction.isEnabled()) {
MenuManager subMenu = new MenuManager("Repository");
manager.add(subMenu);
UpdateRepositoryConfigurationAction resetRepositoryConfigurationAction = new UpdateRepositoryConfigurationAction();
resetRepositoryConfigurationAction.selectionChanged(new StructuredSelection(element));
subMenu.add(resetRepositoryConfigurationAction);
subMenu.add(new Separator());
subMenu.add(repositoryPropertiesAction);
}
}
manager.add(new Separator(ID_SEPARATOR_REPOSITORY));
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.add(new Separator());
manager.add(new Separator(ID_SEPARATOR_PROPERTIES));
}
public List<ITaskElement> getSelectedTaskContainers() {
List<ITaskElement> selectedElements = new ArrayList<ITaskElement>();
for (Iterator<?> i = ((IStructuredSelection) getViewer().getSelection()).iterator(); i.hasNext();) {
Object object = i.next();
if (object instanceof ITaskElement) {
selectedElements.add((ITaskElement) object);
}
}
return selectedElements;
}
private void addMenuManager(IMenuManager menuToAdd, IMenuManager manager, ITaskElement element) {
if ((element instanceof ITask) || element instanceof IRepositoryQuery) {
manager.add(menuToAdd);
}
}
private void addAction(Action action, IMenuManager manager, ITaskElement element) {
manager.add(action);
if (element != null) {
updateActionEnablement(action, element);
}
}
// FIXME move the enablement to the action classes
private void updateActionEnablement(Action action, ITaskElement element) {
if (element instanceof ITask) {
if (action instanceof OpenWithBrowserAction) {
if (TasksUiInternal.isValidUrl(((ITask) element).getUrl())) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof DeleteAction) {
action.setEnabled(true);
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyTaskDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
action.setEnabled(true);
}
} else if (element != null) {
if (action instanceof MarkTaskCompleteAction) {
action.setEnabled(false);
} else if (action instanceof MarkTaskIncompleteAction) {
action.setEnabled(false);
} else if (action instanceof DeleteAction) {
if (element instanceof UncategorizedTaskContainer || element instanceof UnmatchedTaskContainer) {
action.setEnabled(false);
} else {
action.setEnabled(true);
}
} else if (action instanceof GoIntoAction) {
TaskCategory cat = (TaskCategory) element;
if (cat.getChildren().size() > 0) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyTaskDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
if (element instanceof AbstractTaskCategory) {
AbstractTaskCategory container = (AbstractTaskCategory) element;
action.setEnabled(container.isUserManaged());
} else if (element instanceof IRepositoryQuery) {
action.setEnabled(true);
}
}
} else {
action.setEnabled(true);
}
}
private void makeActions() {
copyDetailsAction = new CopyTaskDetailsAction();
copyDetailsAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
goIntoAction = new GoIntoAction();
goUpAction = new GoUpAction(drillDownAdapter);
//newLocalTaskAction = new NewLocalTaskAction(this);
removeFromCategoryAction = new RemoveFromCategoryAction(this);
renameAction = new RenameAction(this);
filteredTree.getViewer().addSelectionChangedListener(renameAction);
deleteAction = new DeleteAction();
collapseAll = new CollapseAllAction(this);
expandAll = new ExpandAllAction(this);
openAction = new OpenTaskListElementAction(this.getViewer());
openWithBrowser = new OpenWithBrowserAction();
filterCompleteTask = new FilterCompletedTasksAction(this);
filterSubTasksAction = new GroupSubTasksAction(this);
synchronizeAutomatically = new SynchronizeAutomaticallyAction();
openPreferencesAction = new OpenTasksUiPreferencesAction();
//filterArchiveCategory = new FilterArchiveContainerAction(this);
sortDialogAction = new TaskListSortAction(getSite(), this);
filterOnPriorityAction = new PriorityDropDownAction(this);
linkWithEditorAction = new LinkWithEditorAction(this);
presentationDropDownSelectionAction = new PresentationDropDownSelectionAction(this);
filteredTree.getViewer().addSelectionChangedListener(openWithBrowser);
filteredTree.getViewer().addSelectionChangedListener(copyDetailsAction);
}
private void hookOpenAction() {
getViewer().addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
openAction.run();
}
});
getViewer().addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
if (TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
TasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED)) {
AbstractTask selectedTask = TaskListView.getFromActivePerspective().getSelectedTask();
if (selectedTask != null) {
activateAction.run(selectedTask);
}
}
}
});
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
filteredTree.getViewer().getControl().setFocus();
}
public String getBugIdFromUser() {
InputDialog dialog = new InputDialog(getSite().getWorkbenchWindow().getShell(), "Enter Bugzilla ID",
"Enter the Bugzilla ID: ", "", null);
int dialogResult = dialog.open();
if (dialogResult == Window.OK) {
return dialog.getValue();
} else {
return null;
}
}
public void refresh(boolean expandIfFocused) {
if (expandIfFocused && isFocusedMode()) {
try {
getViewer().getControl().setRedraw(false);
refreshJob.forceRefresh();
getViewer().expandAll();
} finally {
getViewer().getControl().setRedraw(true);
}
} else {
refreshJob.forceRefresh();
}
}
public void refresh() {
refreshJob.forceRefresh();
// if (expand) {
// getViewer().expandAll();
// }
// getViewer().refresh();
// refresh(null);
// selectedAndFocusTask(TasksUiPlugin.getTaskList().getActiveTask());
}
public TaskListToolTip getToolTip() {
return taskListToolTip;
}
public TreeViewer getViewer() {
return filteredTree.getViewer();
}
public TaskCompletionFilter getCompleteFilter() {
return filterComplete;
}
public TaskPriorityFilter getPriorityFilter() {
return filterPriority;
}
public void addFilter(AbstractTaskListFilter filter) {
if (!filters.contains(filter)) {
filters.add(filter);
}
}
/**
* @API-3.0 eliminate parameter from this method
*/
public void clearFilters(boolean preserveArchiveFilter) {
filters.clear();
filters.add(filterArchive);
filters.add(filterWorkingSet);
}
public void removeFilter(AbstractTaskListFilter filter) {
filters.remove(filter);
}
public void updateDrillDownActions() {
if (drillDownAdapter.canGoBack()) {
goUpAction.setEnabled(true);
} else {
goUpAction.setEnabled(false);
}
}
boolean isInRenameAction = false;
private DelayedRefreshJob refreshJob;
public void setInRenameAction(boolean b) {
isInRenameAction = b;
}
public void goIntoCategory() {
ISelection selection = getViewer().getSelection();
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof ITaskElement) {
drilledIntoCategory = (AbstractTaskContainer) element;
drillDownAdapter.goInto();
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().remove(goUpAction.getId());
bars.getToolBarManager().add(goUpAction);
bars.updateActionBars();
updateDrillDownActions();
}
}
}
public void goUpToRoot() {
drilledIntoCategory = null;
drillDownAdapter.goBack();
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().remove(GoUpAction.ID);
bars.updateActionBars();
updateDrillDownActions();
}
public AbstractTask getSelectedTask() {
ISelection selection = getViewer().getSelection();
if (selection.isEmpty()) {
return null;
}
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (AbstractTask) structuredSelection.getFirstElement();
}
}
return null;
}
public static AbstractTask getSelectedTask(ISelection selection) {
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
if (structuredSelection.size() != 1) {
return null;
}
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (AbstractTask) structuredSelection.getFirstElement();
}
}
return null;
}
public void indicatePaused(boolean paused) {
isPaused = paused;
IStatusLineManager statusLineManager = getViewSite().getActionBars().getStatusLineManager();
if (isPaused) {
statusLineManager.setMessage(CommonImages.getImage(TasksUiImages.TASKS_VIEW),
"Mylyn context capture paused");
setPartName("(paused) " + PART_NAME);
} else {
statusLineManager.setMessage("");
setPartName(PART_NAME);
}
}
public AbstractTaskContainer getDrilledIntoCategory() {
return drilledIntoCategory;
}
public TaskListFilteredTree getFilteredTree() {
return filteredTree;
}
public void selectedAndFocusTask(ITask task) {
if (task == null || getViewer().getControl().isDisposed()) {
return;
}
saveSelection();
IStructuredSelection selection = restoreSelection(task);
getViewer().setSelection(selection, true);
}
private void saveSelection() {
IStructuredSelection selection = (IStructuredSelection) getViewer().getSelection();
if (!selection.isEmpty()) {
if (selection.getFirstElement() instanceof ITaskElement) {
// make sure the new selection is inserted at the end of the
// list
String handle = ((ITaskElement) selection.getFirstElement()).getHandleIdentifier();
lastSelectionByTaskHandle.remove(handle);
lastSelectionByTaskHandle.put(handle, selection);
if (lastSelectionByTaskHandle.size() > SIZE_MAX_SELECTION_HISTORY) {
Iterator<String> it = lastSelectionByTaskHandle.keySet().iterator();
it.next();
it.remove();
}
}
}
}
private IStructuredSelection restoreSelection(ITaskElement task) {
IStructuredSelection selection = lastSelectionByTaskHandle.get(task.getHandleIdentifier());
if (selection != null) {
return selection;
} else {
return new StructuredSelection(task);
}
}
public Image[] getPirorityImages() {
Image[] images = new Image[PriorityLevel.values().length];
for (int i = 0; i < PriorityLevel.values().length; i++) {
images[i] = TasksUiImages.getImageForPriority(PriorityLevel.values()[i]);
}
return images;
}
public Set<AbstractTaskListFilter> getFilters() {
return filters;
}
public static String getCurrentPriorityLevel() {
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TasksUiPreferenceConstants.FILTER_PRIORITY)) {
return TasksUiPlugin.getDefault()
.getPreferenceStore()
.getString(TasksUiPreferenceConstants.FILTER_PRIORITY);
} else {
return PriorityLevel.P5.toString();
}
}
public TaskArchiveFilter getArchiveFilter() {
return filterArchive;
}
public void setManualFiltersEnabled(boolean enabled) {
sortDialogAction.setEnabled(enabled);
filterOnPriorityAction.setEnabled(enabled);
filterCompleteTask.setEnabled(enabled);
//filterArchiveCategory.setEnabled(enabled);
}
public boolean isFocusedMode() {
return focusedMode;
}
public void setFocusedMode(boolean focusedMode) {
this.focusedMode = focusedMode;
}
public void setSynchronizationOverlaid(boolean synchronizationOverlaid) {
this.synchronizationOverlaid = synchronizationOverlaid;
getViewer().refresh();
}
public void displayPrioritiesAbove(String priority) {
filterPriority.displayPrioritiesAbove(priority);
getViewer().refresh();
}
public void propertyChange(PropertyChangeEvent event) {
String property = event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)
|| IWorkingSetManager.CHANGE_WORKING_SET_REMOVE.equals(property)) {
if (getSite() != null && getSite().getPage() != null) {
if (filterWorkingSet.updateWorkingSet(getSite().getPage().getAggregateWorkingSet())) {
try {
getViewer().getControl().setRedraw(false);
// XXX why is this needed?
//getViewer().collapseAll();
getViewer().refresh();
if (isFocusedMode()) {
getViewer().expandAll();
}
} finally {
getViewer().getControl().setRedraw(true);
}
}
}
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
filteredTree.indicateActiveTaskWorkingSet();
}
});
}
}
public void setLinkWithEditor(boolean linkWithEditor) {
this.linkWithEditor = linkWithEditor;
linkWithEditorAction.setChecked(linkWithEditor);
if (linkWithEditor) {
IEditorPart activeEditor = getSite().getPage().getActiveEditor();
if (activeEditor != null) {
jumpToEditorTask(activeEditor);
}
}
}
private void jumpToEditorTask(IEditorPart editor) {
IEditorInput input = editor.getEditorInput();
if (input instanceof TaskEditorInput) {
ITask task = ((TaskEditorInput) input).getTask();
ITask selected = getSelectedTask();
if (selected == null || !selected.equals(task)) {
selectedAndFocusTask(task);
}
}
}
private void updateToolTip(boolean force) {
if (taskListToolTip != null && taskListToolTip.isVisible()) {
if (!force && taskListToolTip.isTriggeredByMouse()) {
return;
}
TreeItem[] selection = getViewer().getTree().getSelection();
if (selection != null && selection.length > 0) {
Rectangle bounds = selection[0].getBounds();
taskListToolTip.show(new Point(bounds.x, bounds.y));
}
}
}
public static Set<IWorkingSet> getActiveWorkingSets() {
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() != null) {
Set<IWorkingSet> allSets = new HashSet<IWorkingSet>(Arrays.asList(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage()
.getWorkingSets()));
Set<IWorkingSet> tasksSets = new HashSet<IWorkingSet>(allSets);
for (IWorkingSet workingSet : allSets) {
if (workingSet.getId() == null
|| !workingSet.getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) {
tasksSets.remove(workingSet);
}
}
return tasksSets;
} else {
return Collections.emptySet();
}
}
/**
* This can be used for experimentally adding additional presentations, but note that this convention is extremely
* likely to change in the Mylyn 3.0 cycle.
*/
public static List<AbstractTaskListPresentation> getPresentations() {
List<AbstractTaskListPresentation> presentations = new ArrayList<AbstractTaskListPresentation>();
presentations.addAll(presentationsPrimary);
presentations.addAll(presentationsSecondary);
return presentations;
}
public static void addPresentation(AbstractTaskListPresentation presentation) {
if (presentation.isPrimary()) {
presentationsPrimary.add(presentation);
} else {
presentationsSecondary.add(presentation);
}
}
public TaskListTableSorter getSorter() {
return tableSorter;
}
}
| true | true | public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | /* SWT.H_SCROLL | */SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
// Set to empty string to disable native tooltips (windows only?)
// bug#160897
// http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg29614.html
getViewer().getTree().setToolTipText("");
getViewer().getTree().setHeaderVisible(false);
getViewer().setUseHashlookup(true);
refreshJob = new TaskListRefreshJob(getViewer(), "Task List Refresh");
configureColumns(columnNames, columnWidths);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(CommonThemes.COLOR_CATEGORY);
taskListTableLabelProvider = new TaskTableLabelProvider(new TaskElementLabelProvider(true),
PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground);
getViewer().setLabelProvider(taskListTableLabelProvider);
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = textEditor;
// editors[1] = new ComboBoxCellEditor(getViewer().getTree(),
// editors[2] = new CheckboxCellEditor();
getViewer().setCellEditors(editors);
getViewer().setCellModifier(taskListCellModifier);
tableSorter = new TaskListTableSorter(this);
getViewer().setSorter(tableSorter);
applyPresentation(CategorizedPresentation.ID);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setInput(getViewSite());
final int activationImageOffset = 20;
CustomTaskListDecorationDrawer customDrawer = new CustomTaskListDecorationDrawer(this, activationImageOffset);
getViewer().getTree().addListener(SWT.EraseItem, customDrawer);
getViewer().getTree().addListener(SWT.PaintItem, customDrawer);
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDown(MouseEvent e) {
// NOTE: need e.x offset for Linux/GTK, which does not see
// left-aligned items in tree
Object selectedNode = ((Tree) e.widget).getItem(new Point(e.x + 70, e.y));
if (selectedNode instanceof TreeItem) {
Object selectedObject = ((TreeItem) selectedNode).getData();
if (selectedObject instanceof ITask) {
if (e.x > activationImageOffset && e.x < activationImageOffset + 13) {
taskListCellModifier.toggleTaskActivation((TreeItem) selectedNode);
}
}
}
}
public void mouseDoubleClick(MouseEvent e) {
// ignore
}
public void mouseUp(MouseEvent e) {
// ignore
}
});
// TODO make these proper commands and move code into TaskListViewCommands
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if ((e.keyCode & SWT.KEYCODE_BIT) != 0) {
// Do nothing here since it is key code
} else if (e.keyCode == SWT.ESC) {
taskListToolTip.hide();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char) e.keyCode) || Character.isDigit((char) e.keyCode)) {
String string = new Character((char) e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
getViewer().addTreeListener(new ITreeViewerListener() {
public void treeCollapsed(final TreeExpansionEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
getViewer().refresh(event.getElement());
}
});
}
public void treeExpanded(final TreeExpansionEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
getViewer().refresh(event.getElement());
}
});
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskElement) {
updateActionEnablement(renameAction, (ITaskElement) selectedObject);
updateActionEnablement(deleteAction, (ITaskElement) selectedObject);
}
}
});
taskListToolTip = new TaskListToolTip(getViewer().getControl());
// update tooltip contents
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateToolTip(true);
}
});
getViewer().getTree().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
taskListToolTip.hide();
}
});
makeActions();
hookGlobalActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
configureGradientColors();
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
updateDescription();
IContextService contextSupport = (IContextService) getSite().getService(IContextService.class);
if (contextSupport != null) {
contextSupport.activateContext(TaskListView.ID);
}
getSite().setSelectionProvider(getViewer());
getSite().getPage().addPartListener(editorListener);
// Need to do this because the page, which holds the active working set is not around on creation, see bug 203179
PlatformUI.getWorkbench().getActiveWorkbenchWindow().addPageListener(PAGE_LISTENER);
}
| public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | /* SWT.H_SCROLL | */SWT.V_SCROLL | SWT.NO_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
// Set to empty string to disable native tooltips (windows only?)
// bug#160897
// http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg29614.html
getViewer().getTree().setToolTipText("");
getViewer().getTree().setHeaderVisible(false);
getViewer().setUseHashlookup(true);
refreshJob = new TaskListRefreshJob(getViewer(), "Task List Refresh");
configureColumns(columnNames, columnWidths);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(CommonThemes.COLOR_CATEGORY);
taskListTableLabelProvider = new TaskTableLabelProvider(new TaskElementLabelProvider(true),
PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground);
getViewer().setLabelProvider(taskListTableLabelProvider);
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = textEditor;
// editors[1] = new ComboBoxCellEditor(getViewer().getTree(),
// editors[2] = new CheckboxCellEditor();
getViewer().setCellEditors(editors);
getViewer().setCellModifier(taskListCellModifier);
tableSorter = new TaskListTableSorter(this);
getViewer().setSorter(tableSorter);
applyPresentation(CategorizedPresentation.ID);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setInput(getViewSite());
final int activationImageOffset = 20;
CustomTaskListDecorationDrawer customDrawer = new CustomTaskListDecorationDrawer(this, activationImageOffset);
getViewer().getTree().addListener(SWT.EraseItem, customDrawer);
getViewer().getTree().addListener(SWT.PaintItem, customDrawer);
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDown(MouseEvent e) {
// NOTE: need e.x offset for Linux/GTK, which does not see
// left-aligned items in tree
Object selectedNode = ((Tree) e.widget).getItem(new Point(e.x + 70, e.y));
if (selectedNode instanceof TreeItem) {
Object selectedObject = ((TreeItem) selectedNode).getData();
if (selectedObject instanceof ITask) {
if (e.x > activationImageOffset && e.x < activationImageOffset + 13) {
taskListCellModifier.toggleTaskActivation((TreeItem) selectedNode);
}
}
}
}
public void mouseDoubleClick(MouseEvent e) {
// ignore
}
public void mouseUp(MouseEvent e) {
// ignore
}
});
// TODO make these proper commands and move code into TaskListViewCommands
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if ((e.keyCode & SWT.KEYCODE_BIT) != 0) {
// Do nothing here since it is key code
} else if (e.keyCode == SWT.ESC) {
taskListToolTip.hide();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char) e.keyCode) || Character.isDigit((char) e.keyCode)) {
String string = new Character((char) e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
getViewer().addTreeListener(new ITreeViewerListener() {
public void treeCollapsed(final TreeExpansionEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
getViewer().refresh(event.getElement());
}
});
}
public void treeExpanded(final TreeExpansionEvent event) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
getViewer().refresh(event.getElement());
}
});
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskElement) {
updateActionEnablement(renameAction, (ITaskElement) selectedObject);
updateActionEnablement(deleteAction, (ITaskElement) selectedObject);
}
}
});
taskListToolTip = new TaskListToolTip(getViewer().getControl());
// update tooltip contents
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateToolTip(true);
}
});
getViewer().getTree().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
taskListToolTip.hide();
}
});
makeActions();
hookGlobalActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
configureGradientColors();
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
updateDescription();
IContextService contextSupport = (IContextService) getSite().getService(IContextService.class);
if (contextSupport != null) {
contextSupport.activateContext(TaskListView.ID);
}
getSite().setSelectionProvider(getViewer());
getSite().getPage().addPartListener(editorListener);
// Need to do this because the page, which holds the active working set is not around on creation, see bug 203179
PlatformUI.getWorkbench().getActiveWorkbenchWindow().addPageListener(PAGE_LISTENER);
}
|
diff --git a/src/gamesincommon/GamesInCommon.java b/src/gamesincommon/GamesInCommon.java
index f887411..68933e0 100644
--- a/src/gamesincommon/GamesInCommon.java
+++ b/src/gamesincommon/GamesInCommon.java
@@ -1,294 +1,299 @@
package gamesincommon;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException;
import com.github.koraktor.steamcondenser.steam.community.SteamGame;
import com.github.koraktor.steamcondenser.steam.community.SteamId;
public class GamesInCommon {
Connection connection = null;
private Logger logger;
public GamesInCommon() {
// initialise logger
logger = Logger.getLogger(GamesInCommon.class.getName());
logger.setLevel(Level.ALL);
// initialise database connector
connection = InitialDBCheck();
if (connection == null) {
throw new RuntimeException("Connection could not be establised to local database.");
}
}
public Logger getLogger() {
return logger;
}
/**
* Creates local database, if necessary, and creates tables for all enum entries.
*
* @return A Connection object to the database.
*/
private Connection InitialDBCheck() {
// newDB is TRUE if the database is about to be created by DriverManager.getConnection();
File dbFile = new File("gamedata.db");
boolean newDB = (!(dbFile).exists());
Connection result = null;
try {
Class.forName("org.sqlite.JDBC");
// attempt to connect to the database
result = DriverManager.getConnection("jdbc:sqlite:gamedata.db");
// check all tables from the information schema
Statement statement = result.createStatement();
ResultSet resultSet = null;
// and copy resultset to List object to enable random access
List<String> tableList = new ArrayList<String>();
// skip if new database, as it'll all be new anyway
if (!newDB) {
// query db
resultSet = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
// copy to tableList
while (resultSet.next()) {
tableList.add(resultSet.getString("name"));
}
} else {
logger.log(Level.INFO, "New database created.");
}
// check all filtertypes have a corresponding table, create if one if not present
// skip check and create if the database is new
for (FilterType filter : FilterType.values()) {
boolean filterFound = false;
if (!newDB) {
for (String tableName : tableList) {
if (tableName.equals(filter.getValue())) {
filterFound = true;
}
}
}
// if the tableList is traversed and the filter was not found, create a table for it
if (!filterFound) {
statement.executeUpdate("CREATE TABLE [" + filter.getValue() + "] ( AppID VARCHAR( 16 ) PRIMARY KEY ON CONFLICT FAIL,"
+ "Name VARCHAR( 64 )," + "HasProperty BOOLEAN NOT NULL ON CONFLICT FAIL );");
}
}
} catch (ClassNotFoundException | SQLException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
return result;
}
/**
* Finds common games between an arbitrarily long list of users
*
* @param users
* A list of names to find common games for.
* @return A collection of games common to all users
*/
public Collection<SteamGame> findCommonGames(List<SteamId> users) {
List<Collection<SteamGame>> userGames = new ArrayList<Collection<SteamGame>>();
for (SteamId name : users) {
try {
userGames.add(getGames(name));
logger.log(Level.INFO, "Added user " + name.getNickname() + " (" + name.getSteamId64() + ").");
} catch (SteamCondenserException e) {
logger.log(Level.SEVERE, e.getMessage());
return null;
}
}
Collection<SteamGame> commonGames = mergeSets(userGames);
logger.log(Level.INFO, "Search complete.");
return commonGames;
}
public SteamId checkSteamId(String nameToCheck) throws SteamCondenserException {
try {
return SteamId.create(nameToCheck);
} catch (SteamCondenserException e1) {
try {
return SteamId.create(Long.parseLong(nameToCheck));
} catch (SteamCondenserException | NumberFormatException e2) {
throw e1;
}
}
}
/**
* Finds all games from the given steam user.
*
* @param sId
* The SteamId of the user to get games from.
* @return A set of all games for the give user.
* @throws SteamCondenserException
*/
public Collection<SteamGame> getGames(SteamId sId) throws SteamCondenserException {
return sId.getGames().values();
}
/**
* Returns games that match one or more of the given filter types
*
* @param gameList
* Collection of games to be filtered.
* @param filterList
* Collection of filters to apply.
* @return A collection of games matching one or more of filters.
*/
public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) {
Collection<SteamGame> result = new HashSet<SteamGame>();
// get list of tables
- ResultSet tableSet = null;
Statement s = null;
for (SteamGame game : gameList) {
+ ResultSet tableSet = null;
// first run a query through the local db
try {
s = connection.createStatement();
tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
} catch (SQLException e1) {
logger.log(Level.SEVERE, e1.getMessage(), e1);
}
// filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB
Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>();
// default to "needs checking"
boolean needsWebCheck = true;
try {
// query the table that matches the filter
while (tableSet.next()) {
- ResultSet rSet = null;
- for (FilterType filter : filterList) {
- // default to "needs checking"
- filtersToCheck.put(filter, true);
- // if the game is not already in the result Collection
- if (!result.contains(game)) {
+ ResultSet rSet = null;;
+ // if the game is not already in the result Collection
+ if (!result.contains(game)) {
+ for (FilterType filter : filterList) {
if (filter.getValue().equals((tableSet.getString("name")))) {
+ s = connection.createStatement();
rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '"
+ game.getAppId() + "'");
}
// if rSet.next() indicates a match
- while ((rSet != null) && (rSet.next())) {
+ if ((rSet != null) && (rSet.next())) {
// if the game passes the filter and is not already in the result collection, add it
if (rSet.getBoolean("HasProperty")) {
result.add(game);
}
// if there's an entry in the database, no need to check anywhere else
filtersToCheck.put(filter, false);
needsWebCheck = false;
logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'");
rSet.close();
+ } else {
+ // "needs checking"
+ filtersToCheck.put(filter, true);
}
}
}
if (rSet != null) {
rSet.close();
}
}
+ if (tableSet != null) {
+ tableSet.close();
+ }
} catch (SQLException e2) {
- logger.log(Level.SEVERE, e2.getMessage());
+ logger.log(Level.SEVERE, e2.getMessage(), e2);
}
// if any games need checking, we'll need to send requests to the steampowered.com website for data
if (needsWebCheck) {
// foundProperties records whether it has or does not have each of the filters
HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) {
// Read lines in until there are no more to be read, run filter on each line looking for specified package IDs.
String line;
while (((line = br.readLine()) != null) && (!result.contains(game))) {
for (FilterType filter : filterList) {
// default false until set to true
foundProperties.put(filter, false);
if (line.contains("\"" + filter.getValue() + "\"")) {
result.add(game);
// success - add to foundProperties as TRUE
foundProperties.put(filter, true);
}
}
}
// if we have any filters that needed data, match them up with foundProperties and insert them into the database
for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) {
if (filterToCheck.getValue().equals(new Boolean(true))) {
for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) {
// SQL takes booleans as 1 or 0 intead of TRUE or FALSE
int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0;
connection.createStatement().executeUpdate(
"INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('"
+ game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")");
}
}
}
logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'");
} catch (IOException | SQLException e3) {
logger.log(Level.SEVERE, e3.getMessage(), e3);
}
}
}
return result;
}
/**
* Merges multiple user game sets together to keep all games that are the same.
*
* @param userGames
* A list of user game sets.
* @return A set containing all common games.
*/
public Collection<SteamGame> mergeSets(List<Collection<SteamGame>> userGames) {
if (userGames.size() == 0) {
return null;
}
Collection<SteamGame> result = new ArrayList<SteamGame>();
int size = 0;
int index = 0;
for (int i = 0; i < userGames.size(); i++) {
if (userGames.get(i).size() > size) {
size = userGames.get(i).size();
index = i;
}
}
result.addAll(userGames.get(index));
for (int i = 0; i < userGames.size(); i++) {
result.retainAll(userGames.get(i));
}
return result;
}
public String sanitiseInputString(String input) {
return input.replace("'", "''");
}
}
| false | true | public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) {
Collection<SteamGame> result = new HashSet<SteamGame>();
// get list of tables
ResultSet tableSet = null;
Statement s = null;
for (SteamGame game : gameList) {
// first run a query through the local db
try {
s = connection.createStatement();
tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
} catch (SQLException e1) {
logger.log(Level.SEVERE, e1.getMessage(), e1);
}
// filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB
Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>();
// default to "needs checking"
boolean needsWebCheck = true;
try {
// query the table that matches the filter
while (tableSet.next()) {
ResultSet rSet = null;
for (FilterType filter : filterList) {
// default to "needs checking"
filtersToCheck.put(filter, true);
// if the game is not already in the result Collection
if (!result.contains(game)) {
if (filter.getValue().equals((tableSet.getString("name")))) {
rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '"
+ game.getAppId() + "'");
}
// if rSet.next() indicates a match
while ((rSet != null) && (rSet.next())) {
// if the game passes the filter and is not already in the result collection, add it
if (rSet.getBoolean("HasProperty")) {
result.add(game);
}
// if there's an entry in the database, no need to check anywhere else
filtersToCheck.put(filter, false);
needsWebCheck = false;
logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'");
rSet.close();
}
}
}
if (rSet != null) {
rSet.close();
}
}
} catch (SQLException e2) {
logger.log(Level.SEVERE, e2.getMessage());
}
// if any games need checking, we'll need to send requests to the steampowered.com website for data
if (needsWebCheck) {
// foundProperties records whether it has or does not have each of the filters
HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) {
// Read lines in until there are no more to be read, run filter on each line looking for specified package IDs.
String line;
while (((line = br.readLine()) != null) && (!result.contains(game))) {
for (FilterType filter : filterList) {
// default false until set to true
foundProperties.put(filter, false);
if (line.contains("\"" + filter.getValue() + "\"")) {
result.add(game);
// success - add to foundProperties as TRUE
foundProperties.put(filter, true);
}
}
}
// if we have any filters that needed data, match them up with foundProperties and insert them into the database
for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) {
if (filterToCheck.getValue().equals(new Boolean(true))) {
for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) {
// SQL takes booleans as 1 or 0 intead of TRUE or FALSE
int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0;
connection.createStatement().executeUpdate(
"INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('"
+ game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")");
}
}
}
logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'");
} catch (IOException | SQLException e3) {
logger.log(Level.SEVERE, e3.getMessage(), e3);
}
}
}
return result;
}
| public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) {
Collection<SteamGame> result = new HashSet<SteamGame>();
// get list of tables
Statement s = null;
for (SteamGame game : gameList) {
ResultSet tableSet = null;
// first run a query through the local db
try {
s = connection.createStatement();
tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';");
} catch (SQLException e1) {
logger.log(Level.SEVERE, e1.getMessage(), e1);
}
// filtersToCheck tells the following webcheck loop which filters need checking and insertion into the DB
Map<FilterType, Boolean> filtersToCheck = new HashMap<FilterType, Boolean>();
// default to "needs checking"
boolean needsWebCheck = true;
try {
// query the table that matches the filter
while (tableSet.next()) {
ResultSet rSet = null;;
// if the game is not already in the result Collection
if (!result.contains(game)) {
for (FilterType filter : filterList) {
if (filter.getValue().equals((tableSet.getString("name")))) {
s = connection.createStatement();
rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '"
+ game.getAppId() + "'");
}
// if rSet.next() indicates a match
if ((rSet != null) && (rSet.next())) {
// if the game passes the filter and is not already in the result collection, add it
if (rSet.getBoolean("HasProperty")) {
result.add(game);
}
// if there's an entry in the database, no need to check anywhere else
filtersToCheck.put(filter, false);
needsWebCheck = false;
logger.log(Level.INFO, "[SQL] Checked game '" + game.getName() + "'");
rSet.close();
} else {
// "needs checking"
filtersToCheck.put(filter, true);
}
}
}
if (rSet != null) {
rSet.close();
}
}
if (tableSet != null) {
tableSet.close();
}
} catch (SQLException e2) {
logger.log(Level.SEVERE, e2.getMessage(), e2);
}
// if any games need checking, we'll need to send requests to the steampowered.com website for data
if (needsWebCheck) {
// foundProperties records whether it has or does not have each of the filters
HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) {
// Read lines in until there are no more to be read, run filter on each line looking for specified package IDs.
String line;
while (((line = br.readLine()) != null) && (!result.contains(game))) {
for (FilterType filter : filterList) {
// default false until set to true
foundProperties.put(filter, false);
if (line.contains("\"" + filter.getValue() + "\"")) {
result.add(game);
// success - add to foundProperties as TRUE
foundProperties.put(filter, true);
}
}
}
// if we have any filters that needed data, match them up with foundProperties and insert them into the database
for (Map.Entry<FilterType, Boolean> filterToCheck : filtersToCheck.entrySet()) {
if (filterToCheck.getValue().equals(new Boolean(true))) {
for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) {
// SQL takes booleans as 1 or 0 intead of TRUE or FALSE
int boolVal = (entry.getValue().equals(new Boolean(true))) ? 1 : 0;
connection.createStatement().executeUpdate(
"INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('"
+ game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', " + boolVal + ")");
}
}
}
logger.log(Level.INFO, "[WEB] Checked game '" + game.getName() + "'");
} catch (IOException | SQLException e3) {
logger.log(Level.SEVERE, e3.getMessage(), e3);
}
}
}
return result;
}
|
diff --git a/src/java/org/infoglue/cms/util/RemoteCacheUpdater.java b/src/java/org/infoglue/cms/util/RemoteCacheUpdater.java
index 7f2e94ffd..6ecd6a54f 100755
--- a/src/java/org/infoglue/cms/util/RemoteCacheUpdater.java
+++ b/src/java/org/infoglue/cms/util/RemoteCacheUpdater.java
@@ -1,326 +1,323 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* 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. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.cms.util;
import java.util.*;
import java.io.*;
import java.net.*;
import org.apache.log4j.Logger;
/**
* This class is a class that sends a update-message to all registered instances of delivery-engine.
*
* @author Mattias Bogeblad
*
*/
public class RemoteCacheUpdater implements NotificationListener
{
private final static Logger logger = Logger.getLogger(RemoteCacheUpdater.class.getName());
//A list of system changes that will either be published upon the next publication or on a manual publishing of them.
private static List waitingSystemNotificationMessages = new ArrayList();
/**
* Default Constructor
*/
public RemoteCacheUpdater()
{
}
/**
* This method sets the context/arguments the listener should operate with. Could be debuglevels and stuff
* like that.
*/
public void setContextParameters(Map map)
{
}
public static List getSystemNotificationMessages()
{
return waitingSystemNotificationMessages;
}
public static void clearSystemNotificationMessages()
{
synchronized(waitingSystemNotificationMessages)
{
waitingSystemNotificationMessages.clear();
}
}
/**
* This method gets called when a new NotificationMessage is available.
* The writer just calls the transactionHistoryController which stores it.
*/
public void notify(NotificationMessage notificationMessage)
{
try
{
logger.info("Update Remote caches....");
updateRemoteCaches(notificationMessage);
logger.info("Done updating remote caches....");
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* This method serializes the notificationMessage and calls the remote actions.
* As a content-tool can have several preview instances we iterate through the instances that have
* been indexed in the propertyfile starting with 0.
*/
public void updateRemoteCaches(NotificationMessage notificationMessage) throws Exception
{
Hashtable hashedMessage = notificationMessageToHashtable(notificationMessage);
List urls = new ArrayList();
if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING || notificationMessage.getType() == NotificationMessage.SYSTEM)
{
String appPrefix = "publicDeliverUrl";
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
- String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
- urls.add(address);
+ urls.add(deliverUrl);
i++;
}
if(notificationMessage.getType() == NotificationMessage.SYSTEM)
{
appPrefix = "internalDeliverUrl";
i = 0;
deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
- String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
- urls.add(address);
+ urls.add(deliverUrl);
i++;
}
}
}
else
{
String appPrefix = "internalDeliverUrl";
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
- String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
- urls.add(address);
+ urls.add(deliverUrl);
i++;
}
}
Iterator urlsIterator = urls.iterator();
while(urlsIterator.hasNext())
{
String deliverUrl = (String)urlsIterator.next();
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
logger.info("Updating cache at " + address);
String response = postToUrl(address, hashedMessage);
}
/*
String appPrefix = "internalDeliverUrl";
if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING)
{
appPrefix = "publicDeliverUrl";
}
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
logger.info("Updating cache at " + address);
String response = postToUrl(address, hashedMessage);
i++;
}
*/
}
private Hashtable notificationMessageToHashtable(NotificationMessage notificationMessage)
{
Hashtable hash = new Hashtable();
logger.info("Serializing:" + notificationMessage);
hash.put("className", notificationMessage.getClassName());
hash.put("objectId", notificationMessage.getObjectId());
hash.put("objectName", notificationMessage.getObjectName());
hash.put("typeId", "" + notificationMessage.getType());
return hash;
}
/**
* This method post information to an URL and returns a string.It throws
* an exception if anything goes wrong.
* (Works like most 'doPost' methods)
*
* @param urlAddress The address of the URL you would like to post to.
* @param inHash The parameters you would like to post to the URL.
* @return The result of the postToUrl method as a string.
* @exception java.lang.Exception
*/
private String postToUrl(String urlAddress, Hashtable inHash) throws Exception
{
URL url = new URL(urlAddress);
URLConnection urlConn = url.openConnection();
urlConn.setAllowUserInteraction(false);
urlConn.setDoOutput (true);
urlConn.setDoInput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true);
String argString = "";
if(inHash != null)
{
argString = toEncodedString(inHash);
}
printout.print(argString);
printout.flush();
printout.close ();
InputStream inStream = null;
inStream = urlConn.getInputStream();
InputStreamReader inStreamReader = new InputStreamReader(inStream);
BufferedReader buffer = new BufferedReader(inStreamReader);
StringBuffer strbuf = new StringBuffer();
String line;
while((line = buffer.readLine()) != null)
{
strbuf.append(line);
}
String readData = strbuf.toString();
buffer.close();
return readData;
}
/**
* Encodes a hash table to an URL encoded string.
*
* @param inHash The hash table you would like to encode
* @return A URL encoded string.
*/
private String toEncodedString(Hashtable inHash) throws Exception
{
StringBuffer buffer = new StringBuffer();
Enumeration names = inHash.keys();
while(names.hasMoreElements())
{
String name = names.nextElement().toString();
String value = inHash.get(name).toString();
buffer.append(URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"));
if(names.hasMoreElements())
{
buffer.append("&");
}
}
return buffer.toString();
}
/**
* As the name indicates, this method takes a URL-encoded string and
* converts it to a normal javastring. That is, all Mime-encoding is
* removed.
*
* @param encoded The encoded string.
* @return An decoded string.
*/
public String decodeHTTPEncodedString(String encoded)
{
StringBuffer decoded = new StringBuffer(encoded.length());
int i = 0;
int j = 0;
while (i < encoded.length()) {
char tecken = encoded.charAt(i);
i++;
if (tecken == '+')
tecken = ' ';
else if (tecken == '%') {
tecken = (char)Integer.parseInt(encoded.substring(i,i+2), 16);
i+=2;
}
decoded.append(tecken);
j++;
}
return new String(decoded);
}
/**
* Converts a serialized hashtable in the url-encoded format to
* a Hashtable that one can use within the program.
* A good technique when exchanging information between different
* applications.
*
* @param encodedstrang The url-encoded string.
* @return A Hashtable.
*/
public Hashtable httpEncodedStringToHashtable(String encodedstrang)
{
Hashtable anropin = new Hashtable();
StringTokenizer andsplitter = new StringTokenizer(encodedstrang,"&");
while (andsplitter.hasMoreTokens())
{
String namevaluepair = andsplitter.nextToken();
StringTokenizer equalsplitter = new StringTokenizer(namevaluepair,"=");
if (equalsplitter.countTokens() == 2)
{
String name = equalsplitter.nextToken();
String value = equalsplitter.nextToken();
anropin.put(decodeHTTPEncodedString(name),decodeHTTPEncodedString(value));
}
}
return anropin;
}
}
| false | true | public void updateRemoteCaches(NotificationMessage notificationMessage) throws Exception
{
Hashtable hashedMessage = notificationMessageToHashtable(notificationMessage);
List urls = new ArrayList();
if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING || notificationMessage.getType() == NotificationMessage.SYSTEM)
{
String appPrefix = "publicDeliverUrl";
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
urls.add(address);
i++;
}
if(notificationMessage.getType() == NotificationMessage.SYSTEM)
{
appPrefix = "internalDeliverUrl";
i = 0;
deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
urls.add(address);
i++;
}
}
}
else
{
String appPrefix = "internalDeliverUrl";
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
urls.add(address);
i++;
}
}
Iterator urlsIterator = urls.iterator();
while(urlsIterator.hasNext())
{
String deliverUrl = (String)urlsIterator.next();
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
logger.info("Updating cache at " + address);
String response = postToUrl(address, hashedMessage);
}
/*
String appPrefix = "internalDeliverUrl";
if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING)
{
appPrefix = "publicDeliverUrl";
}
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
logger.info("Updating cache at " + address);
String response = postToUrl(address, hashedMessage);
i++;
}
*/
}
| public void updateRemoteCaches(NotificationMessage notificationMessage) throws Exception
{
Hashtable hashedMessage = notificationMessageToHashtable(notificationMessage);
List urls = new ArrayList();
if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING || notificationMessage.getType() == NotificationMessage.SYSTEM)
{
String appPrefix = "publicDeliverUrl";
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
urls.add(deliverUrl);
i++;
}
if(notificationMessage.getType() == NotificationMessage.SYSTEM)
{
appPrefix = "internalDeliverUrl";
i = 0;
deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
urls.add(deliverUrl);
i++;
}
}
}
else
{
String appPrefix = "internalDeliverUrl";
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
urls.add(deliverUrl);
i++;
}
}
Iterator urlsIterator = urls.iterator();
while(urlsIterator.hasNext())
{
String deliverUrl = (String)urlsIterator.next();
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
logger.info("Updating cache at " + address);
String response = postToUrl(address, hashedMessage);
}
/*
String appPrefix = "internalDeliverUrl";
if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING)
{
appPrefix = "publicDeliverUrl";
}
int i = 0;
String deliverUrl = null;
while((deliverUrl = CmsPropertyHandler.getProperty(appPrefix + "." + i)) != null)
{
String address = deliverUrl + "/" + CmsPropertyHandler.getProperty("cacheUpdateAction");
logger.info("Updating cache at " + address);
String response = postToUrl(address, hashedMessage);
i++;
}
*/
}
|
diff --git a/src/main/java/net/dandielo/citizens/trader/denizen/AbstractDenizenCommand.java b/src/main/java/net/dandielo/citizens/trader/denizen/AbstractDenizenCommand.java
index 19708a1..0614404 100644
--- a/src/main/java/net/dandielo/citizens/trader/denizen/AbstractDenizenCommand.java
+++ b/src/main/java/net/dandielo/citizens/trader/denizen/AbstractDenizenCommand.java
@@ -1,34 +1,34 @@
package net.dandielo.citizens.trader.denizen;
import net.aufdemrand.denizen.Denizen;
import net.aufdemrand.denizen.scripts.commands.AbstractCommand;
import net.dandielo.citizens.trader.CitizensTrader;
import net.dandielo.citizens.trader.NpcManager;
import net.dandielo.citizens.trader.denizen.commands.TraderCommand;
import net.dandielo.citizens.trader.denizen.commands.TraderCreateCommand;
import net.dandielo.citizens.trader.denizen.commands.TransactionCommand;
abstract public class AbstractDenizenCommand extends AbstractCommand {
protected static NpcManager npcManager;
public AbstractDenizenCommand()
{
npcManager = CitizensTrader.getNpcEcoManager();
}
public static void initializeDenizenCommands(Denizen denizen)
{
if ( denizen != null )
{
CitizensTrader.info("Hooked into " + denizen.getDescription().getFullName());
CitizensTrader.info("Registering commands... ");
- new TransactionCommand();
- new TraderCreateCommand();
- new TraderCommand();
+ new TransactionCommand().activate().as("TRANSACTION").withOptions("({SELL}|BUY) [ITEM:#(:#)] (QTY:#)", 1);
+ new TraderCommand().activate().as("TRADER").withOptions("({OPEN}|CLOSE|PATTERN|WALLET) (ACTION:action) (PATTERN:pattern_name)",0);
+ new TraderCreateCommand().activate().as("TRADERCREATE").withOptions("({SERVER}|MARKET|PLAYER) [NAME:trader_name] (WALLET:SERVER|{NPC}|OWNER) (PATTERN:pattern_name) (LOC:location) (OWNER:owner) (ENTITY:entity)",1);
}
}
}
| true | true | public static void initializeDenizenCommands(Denizen denizen)
{
if ( denizen != null )
{
CitizensTrader.info("Hooked into " + denizen.getDescription().getFullName());
CitizensTrader.info("Registering commands... ");
new TransactionCommand();
new TraderCreateCommand();
new TraderCommand();
}
}
| public static void initializeDenizenCommands(Denizen denizen)
{
if ( denizen != null )
{
CitizensTrader.info("Hooked into " + denizen.getDescription().getFullName());
CitizensTrader.info("Registering commands... ");
new TransactionCommand().activate().as("TRANSACTION").withOptions("({SELL}|BUY) [ITEM:#(:#)] (QTY:#)", 1);
new TraderCommand().activate().as("TRADER").withOptions("({OPEN}|CLOSE|PATTERN|WALLET) (ACTION:action) (PATTERN:pattern_name)",0);
new TraderCreateCommand().activate().as("TRADERCREATE").withOptions("({SERVER}|MARKET|PLAYER) [NAME:trader_name] (WALLET:SERVER|{NPC}|OWNER) (PATTERN:pattern_name) (LOC:location) (OWNER:owner) (ENTITY:entity)",1);
}
}
|
diff --git a/code/app/src/ca/uwaterloo/lkc/WindowConfig.java b/code/app/src/ca/uwaterloo/lkc/WindowConfig.java
index ec53faa..7bb3870 100644
--- a/code/app/src/ca/uwaterloo/lkc/WindowConfig.java
+++ b/code/app/src/ca/uwaterloo/lkc/WindowConfig.java
@@ -1,208 +1,211 @@
package ca.uwaterloo.lkc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import org.gnome.gdk.Event;
import org.gnome.glade.Glade;
import org.gnome.glade.XML;
import org.gnome.gtk.Gtk;
import org.gnome.gtk.ResponseType;
import org.gnome.gtk.ToolButton;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;
import org.gnome.gtk.WindowPosition;
public class WindowConfig {
public final Window w;
public final ToolButton tbtnNew;
public final ToolButton tbtnOpen;
public final ToolButton tbtnSave;
public final ToolButton tbtnUndo;
public final ToolButton tbtnRedo;
public final ToolButton tbtnAdvanced;
private FeatureScreenHandler fsh;
public WindowConfig(final String gladeFile) throws FileNotFoundException {
this(gladeFile, null);
}
public WindowConfig(final String gladeFile, final URI configFile) throws FileNotFoundException {
final XML xmlWndConfig = Glade.parse(gladeFile, "wndConfig");
w = (Window) xmlWndConfig.getWidget("wndConfig");
w.connect(new Window.DeleteEvent() {
@Override
public boolean onDeleteEvent(Widget arg0, Event arg1) {
Gtk.mainQuit();
return false;
}
});
fsh = new FeatureScreenHandler(xmlWndConfig);
// Adding events for tool bar buttons
/* New */
tbtnNew = (ToolButton) xmlWndConfig.getWidget("tbtnNew");
tbtnNew.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
// not implemented yet
}
});
/* Open */
tbtnOpen = (ToolButton) xmlWndConfig.getWidget("tbtnOpen");
tbtnOpen.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
FcdChooseFile fcdChooseFile;
fcdChooseFile = new FcdChooseFile(gladeFile);
ResponseType responseType = fcdChooseFile.run();
/*
* If a file is chosen, hide the current WindowConfig,
* instantiate a new one with the new configuration.
*/
fcdChooseFile.hide();
if (responseType == ResponseType.OK) {
fsh.load(fcdChooseFile.getURI());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
/* Save */
tbtnSave = (ToolButton) xmlWndConfig.getWidget("tbtnSave");
tbtnSave.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
FcdChooseFile fcdChooseFile;
fcdChooseFile = new FcdChooseFile(gladeFile);
fcdChooseFile.setFileChooserActionSave();
ResponseType responseType = fcdChooseFile.run();
/*
* If a file is chosen, save the current configuration.
*/
fcdChooseFile.hide();
if (responseType == ResponseType.OK) {
fsh.save(fcdChooseFile.getURI());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/* Advanced (i.e. calling xconfig) */
tbtnAdvanced = (ToolButton) xmlWndConfig.getWidget("tbtnAdvanced");
tbtnAdvanced.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
// Run xconfig
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "make xconfig");
pb.directory(new File("/usr/src/linux"));
pb.start();
- w.hide();
+ Thread.sleep(100); // wait until xconfig loads
+ Gtk.mainQuit(); // quit our tool
} catch (IOException e) {
e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
}
}
});
/* Undo */
tbtnUndo = (ToolButton) xmlWndConfig.getWidget("tbtnUndo");
tbtnUndo.setSensitive(false);
tbtnUndo.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
if(fsh.decrementCurrentFeaturesIndex()) {
updateUndoRedo(false, true);
} else {
updateUndoRedo(true, true);
}
// Update current features
try {
fsh.updateCurrentFeatures();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
/* Redo */
tbtnRedo = (ToolButton) xmlWndConfig.getWidget("tbtnRedo");
tbtnRedo.setSensitive(false);
tbtnRedo.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
if(fsh.incrementCurrentFeaturesIndex()) {
updateUndoRedo(true, false);
} else {
updateUndoRedo(true, true);
}
// Update current features
try {
fsh.updateCurrentFeatures();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
// Load config file
if(configFile != null) {
try {
fsh.load(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
w.setPosition(WindowPosition.CENTER);
}
public void updateUndoRedo(boolean undoSensitive, boolean redoSensitive) {
tbtnUndo.setSensitive(undoSensitive);
tbtnRedo.setSensitive(redoSensitive);
}
public void run()
{
w.show();
fsh.showScreen();
}
}
| false | true | public WindowConfig(final String gladeFile, final URI configFile) throws FileNotFoundException {
final XML xmlWndConfig = Glade.parse(gladeFile, "wndConfig");
w = (Window) xmlWndConfig.getWidget("wndConfig");
w.connect(new Window.DeleteEvent() {
@Override
public boolean onDeleteEvent(Widget arg0, Event arg1) {
Gtk.mainQuit();
return false;
}
});
fsh = new FeatureScreenHandler(xmlWndConfig);
// Adding events for tool bar buttons
/* New */
tbtnNew = (ToolButton) xmlWndConfig.getWidget("tbtnNew");
tbtnNew.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
// not implemented yet
}
});
/* Open */
tbtnOpen = (ToolButton) xmlWndConfig.getWidget("tbtnOpen");
tbtnOpen.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
FcdChooseFile fcdChooseFile;
fcdChooseFile = new FcdChooseFile(gladeFile);
ResponseType responseType = fcdChooseFile.run();
/*
* If a file is chosen, hide the current WindowConfig,
* instantiate a new one with the new configuration.
*/
fcdChooseFile.hide();
if (responseType == ResponseType.OK) {
fsh.load(fcdChooseFile.getURI());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
/* Save */
tbtnSave = (ToolButton) xmlWndConfig.getWidget("tbtnSave");
tbtnSave.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
FcdChooseFile fcdChooseFile;
fcdChooseFile = new FcdChooseFile(gladeFile);
fcdChooseFile.setFileChooserActionSave();
ResponseType responseType = fcdChooseFile.run();
/*
* If a file is chosen, save the current configuration.
*/
fcdChooseFile.hide();
if (responseType == ResponseType.OK) {
fsh.save(fcdChooseFile.getURI());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/* Advanced (i.e. calling xconfig) */
tbtnAdvanced = (ToolButton) xmlWndConfig.getWidget("tbtnAdvanced");
tbtnAdvanced.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
// Run xconfig
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "make xconfig");
pb.directory(new File("/usr/src/linux"));
pb.start();
w.hide();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/* Undo */
tbtnUndo = (ToolButton) xmlWndConfig.getWidget("tbtnUndo");
tbtnUndo.setSensitive(false);
tbtnUndo.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
if(fsh.decrementCurrentFeaturesIndex()) {
updateUndoRedo(false, true);
} else {
updateUndoRedo(true, true);
}
// Update current features
try {
fsh.updateCurrentFeatures();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
/* Redo */
tbtnRedo = (ToolButton) xmlWndConfig.getWidget("tbtnRedo");
tbtnRedo.setSensitive(false);
tbtnRedo.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
if(fsh.incrementCurrentFeaturesIndex()) {
updateUndoRedo(true, false);
} else {
updateUndoRedo(true, true);
}
// Update current features
try {
fsh.updateCurrentFeatures();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
// Load config file
if(configFile != null) {
try {
fsh.load(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
w.setPosition(WindowPosition.CENTER);
}
| public WindowConfig(final String gladeFile, final URI configFile) throws FileNotFoundException {
final XML xmlWndConfig = Glade.parse(gladeFile, "wndConfig");
w = (Window) xmlWndConfig.getWidget("wndConfig");
w.connect(new Window.DeleteEvent() {
@Override
public boolean onDeleteEvent(Widget arg0, Event arg1) {
Gtk.mainQuit();
return false;
}
});
fsh = new FeatureScreenHandler(xmlWndConfig);
// Adding events for tool bar buttons
/* New */
tbtnNew = (ToolButton) xmlWndConfig.getWidget("tbtnNew");
tbtnNew.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
// not implemented yet
}
});
/* Open */
tbtnOpen = (ToolButton) xmlWndConfig.getWidget("tbtnOpen");
tbtnOpen.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
FcdChooseFile fcdChooseFile;
fcdChooseFile = new FcdChooseFile(gladeFile);
ResponseType responseType = fcdChooseFile.run();
/*
* If a file is chosen, hide the current WindowConfig,
* instantiate a new one with the new configuration.
*/
fcdChooseFile.hide();
if (responseType == ResponseType.OK) {
fsh.load(fcdChooseFile.getURI());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
/* Save */
tbtnSave = (ToolButton) xmlWndConfig.getWidget("tbtnSave");
tbtnSave.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
FcdChooseFile fcdChooseFile;
fcdChooseFile = new FcdChooseFile(gladeFile);
fcdChooseFile.setFileChooserActionSave();
ResponseType responseType = fcdChooseFile.run();
/*
* If a file is chosen, save the current configuration.
*/
fcdChooseFile.hide();
if (responseType == ResponseType.OK) {
fsh.save(fcdChooseFile.getURI());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/* Advanced (i.e. calling xconfig) */
tbtnAdvanced = (ToolButton) xmlWndConfig.getWidget("tbtnAdvanced");
tbtnAdvanced.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
try {
// Run xconfig
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "make xconfig");
pb.directory(new File("/usr/src/linux"));
pb.start();
Thread.sleep(100); // wait until xconfig loads
Gtk.mainQuit(); // quit our tool
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
/* Undo */
tbtnUndo = (ToolButton) xmlWndConfig.getWidget("tbtnUndo");
tbtnUndo.setSensitive(false);
tbtnUndo.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
if(fsh.decrementCurrentFeaturesIndex()) {
updateUndoRedo(false, true);
} else {
updateUndoRedo(true, true);
}
// Update current features
try {
fsh.updateCurrentFeatures();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
/* Redo */
tbtnRedo = (ToolButton) xmlWndConfig.getWidget("tbtnRedo");
tbtnRedo.setSensitive(false);
tbtnRedo.connect(new ToolButton.Clicked() {
@Override
public void onClicked(ToolButton source) {
if(fsh.incrementCurrentFeaturesIndex()) {
updateUndoRedo(true, false);
} else {
updateUndoRedo(true, true);
}
// Update current features
try {
fsh.updateCurrentFeatures();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
// Load config file
if(configFile != null) {
try {
fsh.load(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
w.setPosition(WindowPosition.CENTER);
}
|
diff --git a/src/it/crs4/seal/demux/DemuxOptionParser.java b/src/it/crs4/seal/demux/DemuxOptionParser.java
index 11129a5..5665fae 100644
--- a/src/it/crs4/seal/demux/DemuxOptionParser.java
+++ b/src/it/crs4/seal/demux/DemuxOptionParser.java
@@ -1,123 +1,123 @@
// Copyright (C) 2011 CRS4.
//
// This file is part of Seal.
//
// Seal 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.
//
// Seal 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 Seal. If not, see <http://www.gnu.org/licenses/>.
package it.crs4.seal.demux;
import it.crs4.seal.common.SealToolParser;
import java.util.ArrayList;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.commons.cli.*;
public class DemuxOptionParser {
public static final int DEFAULT_N_REDUCERS = 1;
public static final String ConfigSection = "demux";
private SealToolParser parser;
private Options demuxOptions;
private Option sampleSheetOpt;
private Path sampleSheetPath;
private Option laneContentOpt;
private boolean createLaneContent;
public DemuxOptionParser()
{
// define the options
demuxOptions = new Options();
sampleSheetOpt = OptionBuilder
.withDescription("Sample sheet for the experiment")
.hasArg()
.withArgName("FILE")
.withLongOpt("sample-sheet")
.create("s");
demuxOptions.addOption(sampleSheetOpt);
laneContentOpt = OptionBuilder
.withDescription("create LaneContent files")
.withLongOpt("create-lane-content")
.create("l");
createLaneContent = false;
demuxOptions.addOption(laneContentOpt);
parser = new SealToolParser(ConfigSection, demuxOptions);
}
public void parse(Configuration conf, String[] args) throws IOException
{
try
{
CommandLine line = parser.parseOptions(conf, args);
// options
if (line.hasOption( sampleSheetOpt.getOpt() ))
{
sampleSheetPath = new Path(line.getOptionValue(sampleSheetOpt.getOpt()));
if (sampleSheetPath.getFileSystem(conf).exists(sampleSheetPath))
{
sampleSheetPath = sampleSheetPath.makeQualified(sampleSheetPath.getFileSystem(conf));
if ( !"hdfs".equals(sampleSheetPath.toUri().getScheme()) )
throw new ParseException("Sample sheet must be on HDFS");
}
else
throw new ParseException("Sample sheet " + sampleSheetPath.toString() + " doesn't exist");
}
else
throw new ParseException("Missing --" + sampleSheetOpt.getLongOpt() + " argument");
if (line.hasOption(laneContentOpt.getOpt()))
createLaneContent = true;
if (parser.getNReducers() != null)
{
int r = parser.getNReducers();
if (r <= 0)
- throw new ParseException("Number of reducers, when specified, must be > 0");
+ throw new ParseException("Number of reduce tasks, when specified, must be > 0");
}
}
catch( ParseException e )
{
parser.defaultUsageError("it.crs4.seal.demux.Demux", e.getMessage()); // doesn't return
}
}
public ArrayList<Path> getInputPaths()
{
ArrayList<Path> retval = new ArrayList<Path>(parser.getNumInputPaths());
for (Path p: parser.getInputPaths())
retval.add(p);
return retval;
}
public Path getOutputPath() { return parser.getOutputPath(); }
public Path getSampleSheetPath() { return sampleSheetPath; }
public boolean getCreateLaneContent() { return createLaneContent; }
public boolean isNReducersSpecified() { return parser.getNReducers() != null; }
public int getNReducers()
{
if (parser.getNReducers() == null)
return DEFAULT_N_REDUCERS;
else
return parser.getNReducers();
}
}
| true | true | public void parse(Configuration conf, String[] args) throws IOException
{
try
{
CommandLine line = parser.parseOptions(conf, args);
// options
if (line.hasOption( sampleSheetOpt.getOpt() ))
{
sampleSheetPath = new Path(line.getOptionValue(sampleSheetOpt.getOpt()));
if (sampleSheetPath.getFileSystem(conf).exists(sampleSheetPath))
{
sampleSheetPath = sampleSheetPath.makeQualified(sampleSheetPath.getFileSystem(conf));
if ( !"hdfs".equals(sampleSheetPath.toUri().getScheme()) )
throw new ParseException("Sample sheet must be on HDFS");
}
else
throw new ParseException("Sample sheet " + sampleSheetPath.toString() + " doesn't exist");
}
else
throw new ParseException("Missing --" + sampleSheetOpt.getLongOpt() + " argument");
if (line.hasOption(laneContentOpt.getOpt()))
createLaneContent = true;
if (parser.getNReducers() != null)
{
int r = parser.getNReducers();
if (r <= 0)
throw new ParseException("Number of reducers, when specified, must be > 0");
}
}
catch( ParseException e )
{
parser.defaultUsageError("it.crs4.seal.demux.Demux", e.getMessage()); // doesn't return
}
}
| public void parse(Configuration conf, String[] args) throws IOException
{
try
{
CommandLine line = parser.parseOptions(conf, args);
// options
if (line.hasOption( sampleSheetOpt.getOpt() ))
{
sampleSheetPath = new Path(line.getOptionValue(sampleSheetOpt.getOpt()));
if (sampleSheetPath.getFileSystem(conf).exists(sampleSheetPath))
{
sampleSheetPath = sampleSheetPath.makeQualified(sampleSheetPath.getFileSystem(conf));
if ( !"hdfs".equals(sampleSheetPath.toUri().getScheme()) )
throw new ParseException("Sample sheet must be on HDFS");
}
else
throw new ParseException("Sample sheet " + sampleSheetPath.toString() + " doesn't exist");
}
else
throw new ParseException("Missing --" + sampleSheetOpt.getLongOpt() + " argument");
if (line.hasOption(laneContentOpt.getOpt()))
createLaneContent = true;
if (parser.getNReducers() != null)
{
int r = parser.getNReducers();
if (r <= 0)
throw new ParseException("Number of reduce tasks, when specified, must be > 0");
}
}
catch( ParseException e )
{
parser.defaultUsageError("it.crs4.seal.demux.Demux", e.getMessage()); // doesn't return
}
}
|
diff --git a/src/main/java/net/pterodactylus/sone/web/ajax/GetTimesAjaxPage.java b/src/main/java/net/pterodactylus/sone/web/ajax/GetTimesAjaxPage.java
index 4f545714..b0d9dacc 100644
--- a/src/main/java/net/pterodactylus/sone/web/ajax/GetTimesAjaxPage.java
+++ b/src/main/java/net/pterodactylus/sone/web/ajax/GetTimesAjaxPage.java
@@ -1,256 +1,256 @@
/*
* Sone - GetTimesAjaxPage.java - Copyright © 2010–2013 David Roden
*
* 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 net.pterodactylus.sone.web.ajax;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.sone.data.PostReply;
import net.pterodactylus.sone.web.WebInterface;
import net.pterodactylus.sone.web.page.FreenetRequest;
import net.pterodactylus.util.json.JsonObject;
import com.google.common.base.Optional;
/**
* Ajax page that returns a formatted, relative timestamp for replies or posts.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class GetTimesAjaxPage extends JsonPage {
/** Formatter for tooltips. */
private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss");
/**
* Creates a new get times AJAX page.
*
* @param webInterface
* The Sone web interface
*/
public GetTimesAjaxPage(WebInterface webInterface) {
super("getTimes.ajax", webInterface);
}
/**
* {@inheritDoc}
*/
@Override
protected JsonObject createJsonObject(FreenetRequest request) {
String allIds = request.getHttpRequest().getParam("posts");
JsonObject postTimes = new JsonObject();
if (allIds.length() > 0) {
String[] ids = allIds.split(",");
for (String id : ids) {
Optional<Post> post = webInterface.getCore().getPost(id);
if (!post.isPresent()) {
continue;
}
JsonObject postTime = new JsonObject();
Time time = getTime(post.get().getTime());
postTime.put("timeText", time.getText());
postTime.put("refreshTime", TimeUnit.MILLISECONDS.toSeconds(time.getRefresh()));
synchronized (dateFormat) {
postTime.put("tooltip", dateFormat.format(new Date(post.get().getTime())));
}
postTimes.put(id, postTime);
}
}
JsonObject replyTimes = new JsonObject();
allIds = request.getHttpRequest().getParam("replies");
if (allIds.length() > 0) {
String[] ids = allIds.split(",");
for (String id : ids) {
Optional<PostReply> reply = webInterface.getCore().getPostReply(id);
if (!reply.isPresent()) {
continue;
}
JsonObject replyTime = new JsonObject();
Time time = getTime(reply.get().getTime());
replyTime.put("timeText", time.getText());
replyTime.put("refreshTime", TimeUnit.MILLISECONDS.toSeconds(time.getRefresh()));
synchronized (dateFormat) {
replyTime.put("tooltip", dateFormat.format(new Date(reply.get().getTime())));
}
replyTimes.put(id, replyTime);
}
}
return createSuccessJsonObject().put("postTimes", postTimes).put("replyTimes", replyTimes);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean needsFormPassword() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean requiresLogin() {
return false;
}
//
// PRIVATE METHODS
//
/**
* Returns the formatted relative time for a given time.
*
* @param time
* The time to format the difference from (in milliseconds)
* @return The formatted age
*/
private Time getTime(long time) {
return getTime(webInterface, time);
}
//
// STATIC METHODS
//
/**
* Returns the formatted relative time for a given time.
*
* @param webInterface
* The Sone web interface (for l10n access)
* @param time
* The time to format the difference from (in milliseconds)
* @return The formatted age
*/
public static Time getTime(WebInterface webInterface, long time) {
if (time == 0) {
return new Time(webInterface.getL10n().getString("View.Sone.Text.UnknownDate"), TimeUnit.HOURS.toMillis(12));
}
long age = System.currentTimeMillis() - time;
String text;
long refresh;
if (age < 0) {
text = webInterface.getL10n().getDefaultString("View.Time.InTheFuture");
refresh = TimeUnit.MINUTES.toMillis(5);
} else if (age < TimeUnit.SECONDS.toMillis(20)) {
text = webInterface.getL10n().getDefaultString("View.Time.AFewSecondsAgo");
refresh = TimeUnit.SECONDS.toMillis(10);
} else if (age < TimeUnit.SECONDS.toMillis(45)) {
text = webInterface.getL10n().getString("View.Time.HalfAMinuteAgo");
refresh = TimeUnit.SECONDS.toMillis(20);
} else if (age < TimeUnit.SECONDS.toMillis(90)) {
text = webInterface.getL10n().getString("View.Time.AMinuteAgo");
refresh = TimeUnit.MINUTES.toMillis(1);
} else if (age < TimeUnit.MINUTES.toMillis(30)) {
text = webInterface.getL10n().getString("View.Time.XMinutesAgo", "min", String.valueOf(TimeUnit.MILLISECONDS.toMinutes(age + TimeUnit.SECONDS.toMillis(30))));
refresh = TimeUnit.MINUTES.toMillis(1);
} else if (age < TimeUnit.MINUTES.toMillis(45)) {
text = webInterface.getL10n().getString("View.Time.HalfAnHourAgo");
refresh = TimeUnit.MINUTES.toMillis(10);
} else if (age < TimeUnit.MINUTES.toMillis(90)) {
text = webInterface.getL10n().getString("View.Time.AnHourAgo");
refresh = TimeUnit.HOURS.toMillis(1);
} else if (age < TimeUnit.HOURS.toMillis(21)) {
text = webInterface.getL10n().getString("View.Time.XHoursAgo", "hour", String.valueOf(TimeUnit.MILLISECONDS.toHours(age + TimeUnit.MINUTES.toMillis(30))));
refresh = TimeUnit.HOURS.toMillis(1);
} else if (age < TimeUnit.HOURS.toMillis(42)) {
text = webInterface.getL10n().getString("View.Time.ADayAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(6)) {
text = webInterface.getL10n().getString("View.Time.XDaysAgo", "day", String.valueOf(TimeUnit.MILLISECONDS.toDays(age + TimeUnit.HOURS.toMillis(12))));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(11)) {
text = webInterface.getL10n().getString("View.Time.AWeekAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(28)) {
- text = webInterface.getL10n().getString("View.Time.XWeeksAgo", "week", String.valueOf((TimeUnit.MILLISECONDS.toHours(age) + 84) / 24));
+ text = webInterface.getL10n().getString("View.Time.XWeeksAgo", "week", String.valueOf((TimeUnit.MILLISECONDS.toHours(age) + 84) / (7 * 24)));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(42)) {
text = webInterface.getL10n().getString("View.Time.AMonthAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(330)) {
text = webInterface.getL10n().getString("View.Time.XMonthsAgo", "month", String.valueOf((TimeUnit.MILLISECONDS.toDays(age) + 15) / 30));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(540)) {
text = webInterface.getL10n().getString("View.Time.AYearAgo");
refresh = TimeUnit.DAYS.toMillis(7);
} else {
text = webInterface.getL10n().getString("View.Time.XYearsAgo", "year", String.valueOf((long) ((TimeUnit.MILLISECONDS.toDays(age) + 182.64) / 365.28)));
refresh = TimeUnit.DAYS.toMillis(7);
}
return new Time(text, refresh);
}
/**
* Container for a formatted time.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public static class Time {
/** The formatted time. */
private final String text;
/** The time after which to refresh the time. */
private final long refresh;
/**
* Creates a new formatted time container.
*
* @param text
* The formatted time
* @param refresh
* The time after which to refresh the time (in milliseconds)
*/
public Time(String text, long refresh) {
this.text = text;
this.refresh = refresh;
}
/**
* Returns the formatted time.
*
* @return The formatted time
*/
public String getText() {
return text;
}
/**
* Returns the time after which to refresh the time.
*
* @return The time after which to refresh the time (in milliseconds)
*/
public long getRefresh() {
return refresh;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return text;
}
}
}
| true | true | public static Time getTime(WebInterface webInterface, long time) {
if (time == 0) {
return new Time(webInterface.getL10n().getString("View.Sone.Text.UnknownDate"), TimeUnit.HOURS.toMillis(12));
}
long age = System.currentTimeMillis() - time;
String text;
long refresh;
if (age < 0) {
text = webInterface.getL10n().getDefaultString("View.Time.InTheFuture");
refresh = TimeUnit.MINUTES.toMillis(5);
} else if (age < TimeUnit.SECONDS.toMillis(20)) {
text = webInterface.getL10n().getDefaultString("View.Time.AFewSecondsAgo");
refresh = TimeUnit.SECONDS.toMillis(10);
} else if (age < TimeUnit.SECONDS.toMillis(45)) {
text = webInterface.getL10n().getString("View.Time.HalfAMinuteAgo");
refresh = TimeUnit.SECONDS.toMillis(20);
} else if (age < TimeUnit.SECONDS.toMillis(90)) {
text = webInterface.getL10n().getString("View.Time.AMinuteAgo");
refresh = TimeUnit.MINUTES.toMillis(1);
} else if (age < TimeUnit.MINUTES.toMillis(30)) {
text = webInterface.getL10n().getString("View.Time.XMinutesAgo", "min", String.valueOf(TimeUnit.MILLISECONDS.toMinutes(age + TimeUnit.SECONDS.toMillis(30))));
refresh = TimeUnit.MINUTES.toMillis(1);
} else if (age < TimeUnit.MINUTES.toMillis(45)) {
text = webInterface.getL10n().getString("View.Time.HalfAnHourAgo");
refresh = TimeUnit.MINUTES.toMillis(10);
} else if (age < TimeUnit.MINUTES.toMillis(90)) {
text = webInterface.getL10n().getString("View.Time.AnHourAgo");
refresh = TimeUnit.HOURS.toMillis(1);
} else if (age < TimeUnit.HOURS.toMillis(21)) {
text = webInterface.getL10n().getString("View.Time.XHoursAgo", "hour", String.valueOf(TimeUnit.MILLISECONDS.toHours(age + TimeUnit.MINUTES.toMillis(30))));
refresh = TimeUnit.HOURS.toMillis(1);
} else if (age < TimeUnit.HOURS.toMillis(42)) {
text = webInterface.getL10n().getString("View.Time.ADayAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(6)) {
text = webInterface.getL10n().getString("View.Time.XDaysAgo", "day", String.valueOf(TimeUnit.MILLISECONDS.toDays(age + TimeUnit.HOURS.toMillis(12))));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(11)) {
text = webInterface.getL10n().getString("View.Time.AWeekAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(28)) {
text = webInterface.getL10n().getString("View.Time.XWeeksAgo", "week", String.valueOf((TimeUnit.MILLISECONDS.toHours(age) + 84) / 24));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(42)) {
text = webInterface.getL10n().getString("View.Time.AMonthAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(330)) {
text = webInterface.getL10n().getString("View.Time.XMonthsAgo", "month", String.valueOf((TimeUnit.MILLISECONDS.toDays(age) + 15) / 30));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(540)) {
text = webInterface.getL10n().getString("View.Time.AYearAgo");
refresh = TimeUnit.DAYS.toMillis(7);
} else {
text = webInterface.getL10n().getString("View.Time.XYearsAgo", "year", String.valueOf((long) ((TimeUnit.MILLISECONDS.toDays(age) + 182.64) / 365.28)));
refresh = TimeUnit.DAYS.toMillis(7);
}
return new Time(text, refresh);
}
| public static Time getTime(WebInterface webInterface, long time) {
if (time == 0) {
return new Time(webInterface.getL10n().getString("View.Sone.Text.UnknownDate"), TimeUnit.HOURS.toMillis(12));
}
long age = System.currentTimeMillis() - time;
String text;
long refresh;
if (age < 0) {
text = webInterface.getL10n().getDefaultString("View.Time.InTheFuture");
refresh = TimeUnit.MINUTES.toMillis(5);
} else if (age < TimeUnit.SECONDS.toMillis(20)) {
text = webInterface.getL10n().getDefaultString("View.Time.AFewSecondsAgo");
refresh = TimeUnit.SECONDS.toMillis(10);
} else if (age < TimeUnit.SECONDS.toMillis(45)) {
text = webInterface.getL10n().getString("View.Time.HalfAMinuteAgo");
refresh = TimeUnit.SECONDS.toMillis(20);
} else if (age < TimeUnit.SECONDS.toMillis(90)) {
text = webInterface.getL10n().getString("View.Time.AMinuteAgo");
refresh = TimeUnit.MINUTES.toMillis(1);
} else if (age < TimeUnit.MINUTES.toMillis(30)) {
text = webInterface.getL10n().getString("View.Time.XMinutesAgo", "min", String.valueOf(TimeUnit.MILLISECONDS.toMinutes(age + TimeUnit.SECONDS.toMillis(30))));
refresh = TimeUnit.MINUTES.toMillis(1);
} else if (age < TimeUnit.MINUTES.toMillis(45)) {
text = webInterface.getL10n().getString("View.Time.HalfAnHourAgo");
refresh = TimeUnit.MINUTES.toMillis(10);
} else if (age < TimeUnit.MINUTES.toMillis(90)) {
text = webInterface.getL10n().getString("View.Time.AnHourAgo");
refresh = TimeUnit.HOURS.toMillis(1);
} else if (age < TimeUnit.HOURS.toMillis(21)) {
text = webInterface.getL10n().getString("View.Time.XHoursAgo", "hour", String.valueOf(TimeUnit.MILLISECONDS.toHours(age + TimeUnit.MINUTES.toMillis(30))));
refresh = TimeUnit.HOURS.toMillis(1);
} else if (age < TimeUnit.HOURS.toMillis(42)) {
text = webInterface.getL10n().getString("View.Time.ADayAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(6)) {
text = webInterface.getL10n().getString("View.Time.XDaysAgo", "day", String.valueOf(TimeUnit.MILLISECONDS.toDays(age + TimeUnit.HOURS.toMillis(12))));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(11)) {
text = webInterface.getL10n().getString("View.Time.AWeekAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(28)) {
text = webInterface.getL10n().getString("View.Time.XWeeksAgo", "week", String.valueOf((TimeUnit.MILLISECONDS.toHours(age) + 84) / (7 * 24)));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(42)) {
text = webInterface.getL10n().getString("View.Time.AMonthAgo");
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(330)) {
text = webInterface.getL10n().getString("View.Time.XMonthsAgo", "month", String.valueOf((TimeUnit.MILLISECONDS.toDays(age) + 15) / 30));
refresh = TimeUnit.DAYS.toMillis(1);
} else if (age < TimeUnit.DAYS.toMillis(540)) {
text = webInterface.getL10n().getString("View.Time.AYearAgo");
refresh = TimeUnit.DAYS.toMillis(7);
} else {
text = webInterface.getL10n().getString("View.Time.XYearsAgo", "year", String.valueOf((long) ((TimeUnit.MILLISECONDS.toDays(age) + 182.64) / 365.28)));
refresh = TimeUnit.DAYS.toMillis(7);
}
return new Time(text, refresh);
}
|
diff --git a/drools-jbrms/src/main/java/org/drools/brms/client/ruleeditor/RuleViewer.java b/drools-jbrms/src/main/java/org/drools/brms/client/ruleeditor/RuleViewer.java
index ed975d72a..5a4643958 100644
--- a/drools-jbrms/src/main/java/org/drools/brms/client/ruleeditor/RuleViewer.java
+++ b/drools-jbrms/src/main/java/org/drools/brms/client/ruleeditor/RuleViewer.java
@@ -1,204 +1,204 @@
package org.drools.brms.client.ruleeditor;
import org.drools.brms.client.common.ErrorPopup;
import org.drools.brms.client.common.LoadingPopup;
import org.drools.brms.client.rpc.RepositoryServiceFactory;
import org.drools.brms.client.rpc.RuleAsset;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
/**
* The main layout parent/controller the rule viewer.
*
* @author Michael Neale
*/
public class RuleViewer extends Composite {
private Command closeCommand;
protected RuleAsset asset;
private final FlexTable layout;
private boolean readOnly;
private MetaDataWidget metaWidget;
private ActionToolbar toolbar;
private Widget editor;
private RuleDocumentWidget doco;
public RuleViewer(RuleAsset asset) {
this(asset, false);
}
/**
* @param UUID The resource to open.
* @param format The type of resource (may determine what editor is used).
* @param name The name to be displayed.
* @param historicalReadOnly true if this is a read only view for historical purposes.
*/
public RuleViewer(RuleAsset asset, boolean historicalReadOnly) {
this.asset = asset;
this.readOnly = historicalReadOnly;
layout = new FlexTable();
doWidgets();
initWidget( this.layout );
LoadingPopup.close();
}
/**
* This will actually load up the data (this is called by the callback
* when we get the data back from the server,
* also determines what widgets to load up).
*/
private void doWidgets() {
this.layout.clear();
metaWidget = new MetaDataWidget( this.asset.metaData,
readOnly, this.asset.uuid, new Command() {
public void execute() {
refreshDataAndView();
}
});
//metaWidget.setWidth( "100%" );
//now the main layout table
FlexCellFormatter formatter = layout.getFlexCellFormatter();
layout.setWidget( 0,
1,
metaWidget );
formatter.setRowSpan( 0,
1,
3 );
- formatter.setVerticalAlignment( 0, 0, HasVerticalAlignment.ALIGN_TOP );
+ formatter.setVerticalAlignment( 0, 1, HasVerticalAlignment.ALIGN_TOP );
formatter.setWidth( 0,
1,
"30%" );
//and now the action widgets (checkin/close etc).
toolbar = new ActionToolbar( asset,
new Command() {
public void execute() {
doCheckin();
}
},
new Command() {
public void execute() {
zoomIntoAsset();
}
},
readOnly);
toolbar.setCloseCommand( new Command() {
public void execute() {
closeCommand.execute();
}
} );
layout.setWidget( 0,
0,
toolbar );
formatter.setAlignment( 0,
0,
HasHorizontalAlignment.ALIGN_RIGHT,
HasVerticalAlignment.ALIGN_MIDDLE );
//REMEMBER: subsequent rows have only one column, doh that is confusing !
//GAAAAAAAAAAAAAAAAAAAAAAAAAAH
editor = EditorLauncher.getEditorViewer(asset, this);
layout.setWidget( 1, 0, editor);
//the document widget
doco = new RuleDocumentWidget(asset.metaData);
layout.setWidget( 2,
0,
doco );
}
/**
* This responds to the checkin command.
*/
void doCheckin() {
this.layout.clear();
LoadingPopup.showMessage( "Saving, please wait..." );
RepositoryServiceFactory.getService().checkinVersion( this.asset, new AsyncCallback() {
public void onFailure(Throwable err) {
ErrorPopup.showMessage( err.getMessage() );
}
public void onSuccess(Object o) {
String uuid = (String)o;
if (uuid == null) {
ErrorPopup.showMessage( "Failed to check in the item. Please contact your system administrator." );
return;
}
refreshDataAndView( );
}
});
}
/**
* This will reload the contents from the database, and refresh the widgets.
*/
public void refreshDataAndView() {
RepositoryServiceFactory.getService().loadRuleAsset( asset.uuid, new AsyncCallback() {
public void onFailure(Throwable t) {
ErrorPopup.showMessage( t.getMessage() );
}
public void onSuccess(Object a) {
asset = (RuleAsset) a;
doWidgets();
LoadingPopup.close();
}
});
}
/**
* Calling this will toggle the visibility of the meta-data widget (effectively zooming
* in the rule asset).
*/
public void zoomIntoAsset() {
boolean vis = !layout.getFlexCellFormatter().isVisible( 2, 0 );
this.layout.getFlexCellFormatter().setVisible( 0, 1, vis );
this.layout.getFlexCellFormatter().setVisible( 2, 0, vis );
}
/**
* This needs to be called to allow the opened viewer to close itself.
* @param c
*/
public void setCloseCommand(Command c) {
this.closeCommand = c;
}
}
| true | true | private void doWidgets() {
this.layout.clear();
metaWidget = new MetaDataWidget( this.asset.metaData,
readOnly, this.asset.uuid, new Command() {
public void execute() {
refreshDataAndView();
}
});
//metaWidget.setWidth( "100%" );
//now the main layout table
FlexCellFormatter formatter = layout.getFlexCellFormatter();
layout.setWidget( 0,
1,
metaWidget );
formatter.setRowSpan( 0,
1,
3 );
formatter.setVerticalAlignment( 0, 0, HasVerticalAlignment.ALIGN_TOP );
formatter.setWidth( 0,
1,
"30%" );
//and now the action widgets (checkin/close etc).
toolbar = new ActionToolbar( asset,
new Command() {
public void execute() {
doCheckin();
}
},
new Command() {
public void execute() {
zoomIntoAsset();
}
},
readOnly);
toolbar.setCloseCommand( new Command() {
public void execute() {
closeCommand.execute();
}
} );
layout.setWidget( 0,
0,
toolbar );
formatter.setAlignment( 0,
0,
HasHorizontalAlignment.ALIGN_RIGHT,
HasVerticalAlignment.ALIGN_MIDDLE );
//REMEMBER: subsequent rows have only one column, doh that is confusing !
//GAAAAAAAAAAAAAAAAAAAAAAAAAAH
editor = EditorLauncher.getEditorViewer(asset, this);
layout.setWidget( 1, 0, editor);
//the document widget
doco = new RuleDocumentWidget(asset.metaData);
layout.setWidget( 2,
0,
doco );
}
| private void doWidgets() {
this.layout.clear();
metaWidget = new MetaDataWidget( this.asset.metaData,
readOnly, this.asset.uuid, new Command() {
public void execute() {
refreshDataAndView();
}
});
//metaWidget.setWidth( "100%" );
//now the main layout table
FlexCellFormatter formatter = layout.getFlexCellFormatter();
layout.setWidget( 0,
1,
metaWidget );
formatter.setRowSpan( 0,
1,
3 );
formatter.setVerticalAlignment( 0, 1, HasVerticalAlignment.ALIGN_TOP );
formatter.setWidth( 0,
1,
"30%" );
//and now the action widgets (checkin/close etc).
toolbar = new ActionToolbar( asset,
new Command() {
public void execute() {
doCheckin();
}
},
new Command() {
public void execute() {
zoomIntoAsset();
}
},
readOnly);
toolbar.setCloseCommand( new Command() {
public void execute() {
closeCommand.execute();
}
} );
layout.setWidget( 0,
0,
toolbar );
formatter.setAlignment( 0,
0,
HasHorizontalAlignment.ALIGN_RIGHT,
HasVerticalAlignment.ALIGN_MIDDLE );
//REMEMBER: subsequent rows have only one column, doh that is confusing !
//GAAAAAAAAAAAAAAAAAAAAAAAAAAH
editor = EditorLauncher.getEditorViewer(asset, this);
layout.setWidget( 1, 0, editor);
//the document widget
doco = new RuleDocumentWidget(asset.metaData);
layout.setWidget( 2,
0,
doco );
}
|
diff --git a/webapp/src/main/java/com/seo/webapp/BaseController.java b/webapp/src/main/java/com/seo/webapp/BaseController.java
index d5538e6..6421f48 100644
--- a/webapp/src/main/java/com/seo/webapp/BaseController.java
+++ b/webapp/src/main/java/com/seo/webapp/BaseController.java
@@ -1,80 +1,81 @@
package com.seo.webapp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class BaseController {
@RequestMapping(value="/search", method = RequestMethod.GET)
public ModelAndView search() {
//model.addAttribute("message", "Maven Web Project + Spring 3 MVC - welcome()");
//return "index";
return new ModelAndView("index", "command", new Query());
}
@RequestMapping(value="/welcome", method = RequestMethod.GET)
public String welcome(ModelMap model) {
model.addAttribute("message", "Maven Web Project + Spring 3 MVC - welcome()");
//Spring uses InternalResourceViewResolver and return back sample.jsp
return "sample";
}
@RequestMapping(value="/result", method = RequestMethod.POST)
public String result(@ModelAttribute("SpringWeb")Query q, ModelMap model) {
//model.addAttribute("message", "Results page.");
model.addAttribute("query", q.getQuery());
model.addAttribute("siteToCompare", q.getSiteToCompare());
try {
model.addAttribute("json", q.HTTP_Request());
} catch (Exception e) {
e.printStackTrace();
- System.err.println("Could not connect to localhost:5000");
- System.exit(-1);
+ System.err.println("Warning!! Could not connect to localhost:5000/*");
+ model.addAttribute("errMsg", "Could not connect to webservice.");
+ return "error";
}
return "result";
}
@RequestMapping(value="/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student, ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "studentResult";
}
@RequestMapping(value="/test", method = RequestMethod.GET)
public String test(ModelMap model) {
model.addAttribute("message", "Test completed successfully.");
//Spring uses InternalResourceViewResolver and return back sample.jsp
return "result";
}
@RequestMapping(value="/welcome/{name}", method = RequestMethod.GET)
public String welcomeName(@PathVariable String name, ModelMap model) {
model.addAttribute("message", "Maven Web Project + Spring 3 MVC - " + name);
return "sample";
}
}
| true | true | public String result(@ModelAttribute("SpringWeb")Query q, ModelMap model) {
//model.addAttribute("message", "Results page.");
model.addAttribute("query", q.getQuery());
model.addAttribute("siteToCompare", q.getSiteToCompare());
try {
model.addAttribute("json", q.HTTP_Request());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Could not connect to localhost:5000");
System.exit(-1);
}
return "result";
}
| public String result(@ModelAttribute("SpringWeb")Query q, ModelMap model) {
//model.addAttribute("message", "Results page.");
model.addAttribute("query", q.getQuery());
model.addAttribute("siteToCompare", q.getSiteToCompare());
try {
model.addAttribute("json", q.HTTP_Request());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Warning!! Could not connect to localhost:5000/*");
model.addAttribute("errMsg", "Could not connect to webservice.");
return "error";
}
return "result";
}
|
diff --git a/src/main/java/org/spout/vanilla/material/block/Solid.java b/src/main/java/org/spout/vanilla/material/block/Solid.java
index 052b3412..4b305864 100644
--- a/src/main/java/org/spout/vanilla/material/block/Solid.java
+++ b/src/main/java/org/spout/vanilla/material/block/Solid.java
@@ -1,80 +1,80 @@
/*
* This file is part of Vanilla (http://www.spout.org/).
*
* Vanilla is licensed under the SpoutDev License Version 1.
*
* Vanilla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Vanilla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.material.block;
import org.spout.api.geo.World;
import org.spout.api.geo.discrete.Point;
import org.spout.vanilla.VanillaMaterials;
import org.spout.vanilla.entity.object.falling.FallingBlock;
import org.spout.vanilla.material.Block;
import org.spout.vanilla.material.MovingBlock;
import org.spout.vanilla.material.generic.GenericBlock;
public class Solid extends GenericBlock implements MovingBlock {
private final boolean moving;
public Solid(String name, int id, int data, boolean falling) {
super(name, id, data);
moving = falling;
}
public Solid(String name, int id, boolean falling) {
super(name, id, 0);
moving = falling;
}
public Solid(String name, int id) {
super(name, id, 0);
moving = false;
}
public Solid(String name, int id, int data) {
super(name, id, data);
moving = false;
}
@Override
public boolean isMoving() {
return moving;
}
@Override
public boolean hasPhysics() {
return isMoving();
}
@Override
public void onUpdate(World world, int x, int y, int z) {
if (moving) {
Block material = (Block) world.getBlockMaterial(x, y - 1, z);
if (material == VanillaMaterials.AIR || material.isLiquid()) {
if (world.setBlockId(x, y, z, (short) 0, world)) {
- world.createAndSpawnEntity(new Point(world, x, y, z), new FallingBlock(this));
+// world.createAndSpawnEntity(new Point(world, x, y, z), new FallingBlock(this));
}
}
}
}
}
| true | true | public void onUpdate(World world, int x, int y, int z) {
if (moving) {
Block material = (Block) world.getBlockMaterial(x, y - 1, z);
if (material == VanillaMaterials.AIR || material.isLiquid()) {
if (world.setBlockId(x, y, z, (short) 0, world)) {
world.createAndSpawnEntity(new Point(world, x, y, z), new FallingBlock(this));
}
}
}
}
| public void onUpdate(World world, int x, int y, int z) {
if (moving) {
Block material = (Block) world.getBlockMaterial(x, y - 1, z);
if (material == VanillaMaterials.AIR || material.isLiquid()) {
if (world.setBlockId(x, y, z, (short) 0, world)) {
// world.createAndSpawnEntity(new Point(world, x, y, z), new FallingBlock(this));
}
}
}
}
|
diff --git a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
index 232066c..50c2ef9 100644
--- a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
+++ b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
@@ -1,1480 +1,1488 @@
/**
* Copyright (C) 2009-2013 enstratius, Inc.
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.cloudstack.compute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.Tag;
import org.dasein.cloud.cloudstack.CSCloud;
import org.dasein.cloud.cloudstack.CSException;
import org.dasein.cloud.cloudstack.CSMethod;
import org.dasein.cloud.cloudstack.CSServiceProvider;
import org.dasein.cloud.cloudstack.CSTopology;
import org.dasein.cloud.cloudstack.CSVersion;
import org.dasein.cloud.cloudstack.Param;
import org.dasein.cloud.cloudstack.network.Network;
import org.dasein.cloud.cloudstack.network.SecurityGroup;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.network.RawAddress;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.logicblaze.lingo.util.DefaultTimeoutMap;
public class VirtualMachines extends AbstractVMSupport {
static public final Logger logger = Logger.getLogger(VirtualMachines.class);
static private final String DEPLOY_VIRTUAL_MACHINE = "deployVirtualMachine";
static private final String DESTROY_VIRTUAL_MACHINE = "destroyVirtualMachine";
static private final String GET_VIRTUAL_MACHINE_PASSWORD = "getVMPassword";
static private final String LIST_VIRTUAL_MACHINES = "listVirtualMachines";
static private final String LIST_SERVICE_OFFERINGS = "listServiceOfferings";
static private final String REBOOT_VIRTUAL_MACHINE = "rebootVirtualMachine";
static private final String RESET_VIRTUAL_MACHINE_PASSWORD = "resetPasswordForVirtualMachine";
static private final String RESIZE_VIRTUAL_MACHINE = "scaleVirtualMachine";
static private final String START_VIRTUAL_MACHINE = "startVirtualMachine";
static private final String STOP_VIRTUAL_MACHINE = "stopVirtualMachine";
static private Properties cloudMappings;
static private Map<String,Map<String,String>> customNetworkMappings;
static private Map<String,Map<String,Set<String>>> customServiceMappings;
static private DefaultTimeoutMap productCache = new DefaultTimeoutMap();
private CSCloud provider;
public VirtualMachines(CSCloud provider) {
super(provider);
this.provider = provider;
}
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.alterVM");
try {
String productId = options.getProviderProductId();
if (vmId == null || options.getProviderProductId() == null) {
throw new CloudException("No vmid and/or product id set for this operation");
}
CSMethod method = new CSMethod(provider);
VirtualMachine vm = getVirtualMachine(vmId);
if (vm.getProductId().equals(productId)) {
return vm;
}
boolean restart = false;
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
restart = true;
stop(vmId, true);
}
long timeout = System.currentTimeMillis()+(CalendarWrapper.MINUTE*20L);
while (System.currentTimeMillis() < timeout) {
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
try {
Thread.sleep(15000L);
vm = getVirtualMachine(vmId);
}
catch (InterruptedException ignore) {}
}
else {
break;
}
}
vm = getVirtualMachine(vmId);
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
throw new CloudException("Unable to stop vm for scaling");
}
Document doc = method.get(method.buildUrl(RESIZE_VIRTUAL_MACHINE, new Param("id", vmId), new Param("serviceOfferingId", productId)), RESIZE_VIRTUAL_MACHINE);
NodeList matches = doc.getElementsByTagName("scalevirtualmachineresponse");
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
}
if( jobId == null ) {
throw new CloudException("Could not scale server");
}
Document responseDoc = provider.waitForJob(doc, "Scale Server");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
if (restart) {
start(vmId);
}
return vm;
}
}
}
if (restart) {
start(vmId);
}
return getVirtualMachine(vmId);
}
finally {
APITrace.end();
}
}
@Nullable
@Override
public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException {
return VMScalingCapabilities.getInstance(false,true,Requirement.NONE,Requirement.NONE);
}
@Override
public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException {
return 100;
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getProduct");
try {
for( Architecture architecture : Architecture.values() ) {
for( VirtualMachineProduct product : listProducts(architecture) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
}
if( logger.isDebugEnabled() ) {
logger.debug("Unknown product ID for cloud.com: " + productId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "virtual machine";
}
private String getRootPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.getPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(GET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), GET_VIRTUAL_MACHINE_PASSWORD);
if (doc != null){
NodeList matches = doc.getElementsByTagName("getvmpasswordresponse");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
NodeList nodes = attribute.getChildNodes();
for( int k=0; k<nodes.getLength(); k++ ) {
Node password = nodes.item(k);
name = password.getNodeName().toLowerCase();
if( password.getChildNodes().getLength() > 0 ) {
value = password.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("encryptedpassword") ) {
return value;
}
}
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
catch (CSException e) {
if (e.getHttpCode() == 431) {
logger.warn("No password found for vm "+serverId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getVirtualMachine");
try {
CSMethod method = new CSMethod(provider);
try {
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("id", serverId)), LIST_VIRTUAL_MACHINES);
NodeList matches = doc.getElementsByTagName("virtualmachine");
if( matches.getLength() < 1 ) {
return null;
}
for( int i=0; i<matches.getLength(); i++ ) {
VirtualMachine s = toVirtualMachine(matches.item(i));
if( s != null && s.getProviderVirtualMachineId().equals(serverId) ) {
return s;
}
}
}
catch( CloudException e ) {
if( e.getMessage().contains("does not exist") ) {
return null;
}
throw e;
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.OPTIONAL;
}
@Override
public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.identifyVlanRequirement");
try {
if( provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) ) {
return Requirement.NONE;
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request");
}
return (provider.getDataCenterServices().requiresNetwork(regionId) ? Requirement.REQUIRED : Requirement.OPTIONAL);
}
return Requirement.OPTIONAL;
}
finally {
APITrace.end();
}
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.isSubscribed");
try {
CSMethod method = new CSMethod(provider);
try {
method.get(method.buildUrl(CSTopology.LIST_ZONES, new Param("available", "true")), CSTopology.LIST_ZONES);
return true;
}
catch( CSException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == 401 || code == 531 ) {
return false;
}
throw e;
}
catch( CloudException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED ) {
return false;
}
throw e;
}
}
finally {
APITrace.end();
}
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return true;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.launch");
try {
String id = withLaunchOptions.getStandardProductId();
VirtualMachineProduct product = getProduct(id);
if( product == null ) {
throw new CloudException("Invalid product ID: " + id);
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
return launch22(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName(), withLaunchOptions.getBootstrapKey(), withLaunchOptions.getVlanId(), withLaunchOptions.getFirewallIds(), withLaunchOptions.getUserData());
}
else {
return launch21(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName());
}
}
finally {
APITrace.end();
}
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public @Nonnull VirtualMachine launch(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nonnull String inZoneId, @Nonnull String name, @Nonnull String description, @Nullable String usingKey, @Nullable String withVlanId, boolean withMonitoring, boolean asSandbox, @Nullable String[] protectedByFirewalls, @Nullable Tag ... tags) throws InternalException, CloudException {
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
StringBuilder userData = new StringBuilder();
if( tags != null && tags.length > 0 ) {
for( Tag tag : tags ) {
userData.append(tag.getKey());
userData.append("=");
userData.append(tag.getValue());
userData.append("\n");
}
}
else {
userData.append("created=Dasein Cloud\n");
}
return launch22(imageId, product, inZoneId, name, usingKey, withVlanId, protectedByFirewalls, userData.toString());
}
else {
return launch21(imageId, product, inZoneId, name);
}
}
private VirtualMachine launch21(String imageId, VirtualMachineProduct product, String inZoneId, String name) throws InternalException, CloudException {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, new Param("zoneId", getContext().getRegionId()), new Param("serviceOfferingId", product.getProviderProductId()), new Param("templateId", imageId), new Param("displayName", name) ), DEPLOY_VIRTUAL_MACHINE));
}
private void load() {
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/cloudMappings.cfg");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
Properties properties = new Properties();
String line;
while( (line = reader.readLine()) != null ) {
if( line.startsWith("#") ) {
continue;
}
int idx = line.indexOf('=');
if( idx < 0 || line.endsWith("=") ) {
continue;
}
String cloudUrl = line.substring(0, idx);
String cloudId = line.substring(idx+1);
properties.put(cloudUrl, cloudId);
}
cloudMappings = properties;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customNetworkMappings.cfg");
HashMap<String,Map<String,String>> mapping = new HashMap<String,Map<String,String>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String[] trueKey = ((String)key).split(",");
Map<String,String> current = mapping.get(trueKey[0]);
if( current == null ) {
current = new HashMap<String,String>();
mapping.put(trueKey[0], current);
}
current.put(trueKey[1], (String)properties.get(key));
}
customNetworkMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customServiceMappings.cfg");
HashMap<String,Map<String,Set<String>>> mapping = new HashMap<String,Map<String,Set<String>>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String value = (String)properties.get(key);
if( value != null ) {
String[] trueKey = ((String)key).split(",");
Map<String,Set<String>> tmp = mapping.get(trueKey[0]);
if( tmp == null ) {
tmp =new HashMap<String,Set<String>>();
mapping.put(trueKey[0], tmp);
}
TreeSet<String> m = new TreeSet<String>();
String[] offerings = value.split(",");
if( offerings == null || offerings.length < 1 ) {
m.add(value);
}
else {
Collections.addAll(m, offerings);
}
tmp.put(trueKey[1], m);
}
}
customServiceMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
}
private @Nonnull VirtualMachine launch22(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nullable String inZoneId, @Nonnull String name, @Nullable String withKeypair, @Nullable String targetVlanId, @Nullable String[] protectedByFirewalls, @Nullable String userData) throws InternalException, CloudException {
ProviderContext ctx = provider.getContext();
List<String> vlans = null;
if( ctx == null ) {
throw new InternalException("No context was provided for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new InternalException("No region is established for this request");
}
String prdId = product.getProviderProductId();
if( customNetworkMappings == null ) {
load();
}
if( customNetworkMappings != null ) {
String cloudId = cloudMappings.getProperty(ctx.getEndpoint());
if( cloudId != null ) {
Map<String,String> map = customNetworkMappings.get(cloudId);
if( map != null ) {
String id = map.get(prdId);
if( id != null ) {
targetVlanId = id;
}
}
}
}
if( targetVlanId != null && targetVlanId.length() < 1 ) {
targetVlanId = null;
}
if( userData == null ) {
userData = "";
}
String securityGroupIds = null;
Param[] params;
if( protectedByFirewalls != null && protectedByFirewalls.length > 0 ) {
StringBuilder str = new StringBuilder();
int idx = 0;
for( String fw : protectedByFirewalls ) {
fw = fw.trim();
if( !fw.equals("") ) {
str.append(fw);
if( (idx++) < protectedByFirewalls.length-1 ) {
str.append(",");
}
}
}
securityGroupIds = str.toString();
}
int count = 4;
if( userData != null && userData.length() > 0 ) {
count++;
}
if( withKeypair != null ) {
count++;
}
if( targetVlanId == null ) {
Network vlan = provider.getNetworkServices().getVlanSupport();
if( vlan != null && vlan.isSubscribed() ) {
if( provider.getDataCenterServices().requiresNetwork(regionId) ) {
vlans = vlan.findFreeNetworks();
}
}
}
else {
vlans = new ArrayList<String>();
vlans.add(targetVlanId);
}
if( vlans != null && vlans.size() > 0 ) {
count++;
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
if( !provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) && !provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
securityGroupIds = null;
}
else {
count++;
}
}
else if( provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
/*
String sgId = null;
if( withVlanId == null ) {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( fw.getName().equalsIgnoreCase("default") && fw.getProviderVlanId() == null ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().create("default", "Default security group");
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
if( sgId != null ) {
securityGroupIds = sgId;
}
}
else {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( (fw.getName().equalsIgnoreCase("default") || fw.getName().equalsIgnoreCase("default-" + withVlanId)) && withVlanId.equals(fw.getProviderVlanId()) ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().createInVLAN("default-" + withVlanId, "Default " + withVlanId + " security group", withVlanId);
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
}
if( sgId != null ) {
securityGroupIds = sgId;
count++;
}
*/
}
params = new Param[count];
params[0] = new Param("zoneId", getContext().getRegionId());
params[1] = new Param("serviceOfferingId", prdId);
params[2] = new Param("templateId", imageId);
params[3] = new Param("displayName", name);
int i = 4;
if( userData != null && userData.length() > 0 ) {
try {
params[i++] = new Param("userdata", new String(Base64.encodeBase64(userData.getBytes("utf-8")), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
e.printStackTrace();
}
}
if( withKeypair != null ) {
params[i++] = new Param("keypair", withKeypair);
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
params[i++] = new Param("securitygroupids", securityGroupIds);
}
if( vlans != null && vlans.size() > 0 ) {
CloudException lastError = null;
for( String withVlanId : vlans ) {
params[i] = new Param("networkIds", withVlanId);
try {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
catch( CloudException e ) {
if( e.getMessage().contains("sufficient address capacity") ) {
lastError = e;
continue;
}
throw e;
}
}
if( lastError == null ) {
throw lastError;
}
throw new CloudException("Unable to identify a network into which a VM can be launched");
}
else {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
}
private @Nonnull VirtualMachine launch(@Nonnull Document doc) throws InternalException, CloudException {
NodeList matches = doc.getElementsByTagName("deployvirtualmachineresponse");
String serverId = null;
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if( node != null && (node.getNodeName().equalsIgnoreCase("virtualmachineid") || node.getNodeName().equalsIgnoreCase("id")) ) {
serverId = node.getFirstChild().getNodeValue();
break;
}
else if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
if( serverId != null ) {
break;
}
}
if( serverId == null && jobId == null ) {
throw new CloudException("Could not launch server");
}
// TODO: very odd logic below; figure out what it thinks it is doing
VirtualMachine vm = null;
// have to wait on jobs as sometimes they fail and we need to bubble error message up
Document responseDoc = provider.waitForJob(doc, "Launch Server");
//parse vm from job completion response to capture vm passwords on initial launch.
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
return vm;
}
}
}
if (vm == null){
vm = getVirtualMachine(serverId);
}
if( vm == null ) {
throw new CloudException("No virtual machine provided: " + serverId);
}
return vm;
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return Collections.emptyList();
}
return support.listFirewallsForVM(vmId);
}
finally {
APITrace.end();
}
}
private void setFirewalls(@Nonnull VirtualMachine vm) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.setFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return;
}
ArrayList<String> ids = new ArrayList<String>();
Iterable<String> firewalls;
try {
firewalls = support.listFirewallsForVM(vm.getProviderVirtualMachineId());
} catch (Throwable t) {
logger.error("Problem listing firewalls (listSecurityGroups) for '" + vm.getProviderVirtualMachineId() + "': " + t.getMessage());
return;
}
for( String id : firewalls ) {
ids.add(id);
}
vm.setProviderFirewallIds(ids.toArray(new String[ids.size()]));
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listProducts");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was configured for this request");
}
Map<Architecture,Collection<VirtualMachineProduct>> cached;
String endpoint = provider.getContext().getEndpoint();
String accountId = provider.getContext().getAccountNumber();
String regionId = provider.getContext().getRegionId();
productCache.purge();
cached = (HashMap<Architecture, Collection<VirtualMachineProduct>>) productCache.get(endpoint+"_"+accountId+"_"+regionId);
if (cached != null && !cached.isEmpty()) {
if( cached.containsKey(architecture) ) {
Collection<VirtualMachineProduct> products = cached.get(architecture);
if( products != null ) {
return products;
}
}
}
else {
cached = new HashMap<Architecture, Collection<VirtualMachineProduct>>();
productCache.put(endpoint+"_"+accountId+"_"+regionId, cached, CalendarWrapper.HOUR * 4);
}
List<VirtualMachineProduct> products;
Set<String> mapping = null;
if( customServiceMappings == null ) {
load();
}
if( customServiceMappings != null ) {
String cloudId = cloudMappings.getProperty(provider.getContext().getEndpoint());
if( cloudId != null ) {
Map<String,Set<String>> map = customServiceMappings.get(cloudId);
if( map != null ) {
mapping = map.get(provider.getContext().getRegionId());
}
}
}
products = new ArrayList<VirtualMachineProduct>();
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_SERVICE_OFFERINGS, new Param("zoneId", ctx.getRegionId())), LIST_SERVICE_OFFERINGS);
NodeList matches = doc.getElementsByTagName("serviceoffering");
for( int i=0; i<matches.getLength(); i++ ) {
String id = null, name = null;
Node node = matches.item(i);
NodeList attributes;
int memory = 0;
int cpu = 0;
attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node n = attributes.item(j);
String value;
if( n.getChildNodes().getLength() > 0 ) {
value = n.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( n.getNodeName().equals("id") ) {
id = value;
}
else if( n.getNodeName().equals("name") ) {
name = value;
}
else if( n.getNodeName().equals("cpunumber") ) {
cpu = Integer.parseInt(value);
}
else if( n.getNodeName().equals("memory") ) {
memory = Integer.parseInt(value);
}
if( id != null && name != null && cpu > 0 && memory > 0 ) {
break;
}
}
if( id != null ) {
if( mapping == null || mapping.contains(id) ) {
VirtualMachineProduct product;
product = new VirtualMachineProduct();
product.setProviderProductId(id);
product.setName(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setDescription(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setRamSize(new Storage<Megabyte>(memory, Storage.MEGABYTE));
product.setCpuCount(cpu);
product.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
products.add(product);
}
}
}
cached.put(architecture, products);
return products;
}
finally {
APITrace.end();
}
}
private transient Collection<Architecture> architectures;
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
if( architectures == null ) {
ArrayList<Architecture> a = new ArrayList<Architecture>();
a.add(Architecture.I32);
a.add(Architecture.I64);
architectures = Collections.unmodifiableList(a);
}
return architectures;
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachineStatus");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
ResourceStatus vm = toStatus(node);
if( vm != null ) {
servers.add(vm);
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachines");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
try {
VirtualMachine vm = toVirtualMachine(node);
if( vm != null ) {
servers.add(vm);
}
} catch (Throwable t) {
logger.error("Problem discovering a virtual machine: " + t.getMessage());
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
private String resetPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.resetPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(RESET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), RESET_VIRTUAL_MACHINE_PASSWORD);
Document responseDoc = provider.waitForJob(doc, "reset vm password");
if (responseDoc != null){
NodeList matches = responseDoc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
return value;
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.reboot");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(REBOOT_VIRTUAL_MACHINE, new Param("id", serverId)), REBOOT_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.start");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(START_VIRTUAL_MACHINE, new Param("id", serverId)), START_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.stop");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(STOP_VIRTUAL_MACHINE, new Param("id", vmId), new Param("forced", String.valueOf(force))), STOP_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return true;
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public void terminate(@Nonnull String serverId, @Nullable String explanation) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.terminate");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(DESTROY_VIRTUAL_MACHINE, new Param("id", serverId)), DESTROY_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
NodeList attributes = node.getChildNodes();
VmState state = null;
String serverId = null;
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
serverId = value;
}
else if( name.equals("state") ) {
if( value == null ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
}
if( serverId != null && state != null ) {
break;
}
}
if( serverId == null ) {
return null;
}
if( state == null ) {
state = VmState.PENDING;
}
return new ResourceStatus(serverId, state);
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setTags(properties);
- server.setArchitecture(Architecture.I64);
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN)){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setPlatform(image.getPlatform());
}
}
}
+ if (server.getArchitecture() == null) {
+ Templates support = provider.getComputeServices().getImageSupport();
+ if (support != null){
+ MachineImage image =support.getImage(server.getProviderMachineImageId());
+ if (image != null){
+ server.setArchitecture(image.getArchitecture());
+ }
+ }
+ }
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
return server;
}
private Platform guessForWindows(String name){
if (name == null){
return Platform.UNKNOWN;
}
String platform = name.toLowerCase();
if (platform.contains("windows") || platform.contains("win") ){
return Platform.WINDOWS;
}
return Platform.UNKNOWN;
}
}
| false | true | private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setTags(properties);
server.setArchitecture(Architecture.I64);
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN)){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setPlatform(image.getPlatform());
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
return server;
}
| private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setTags(properties);
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN)){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setPlatform(image.getPlatform());
}
}
}
if (server.getArchitecture() == null) {
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setArchitecture(image.getArchitecture());
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
return server;
}
|
diff --git a/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java b/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java
index a2dc9781..ae4b8e19 100644
--- a/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java
+++ b/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java
@@ -1,70 +1,71 @@
package com.redshape.servlet.core.format;
import com.redshape.servlet.core.IHttpRequest;
import com.redshape.servlet.core.SupportType;
import com.redshape.servlet.core.controllers.ProcessingException;
import net.sf.json.JSONObject;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: cyril
* Date: 7/10/12
* Time: 3:47 PM
* To change this template use File | Settings | File Templates.
*/
public class JSONFormatProcessor implements IRequestFormatProcessor {
public static final String MARKER_HEADER = "XMLHttpRequest";
@Override
public SupportType check(IHttpRequest request) throws ProcessingException {
try {
if ( !request.isPost() ) {
return SupportType.NO;
}
- if ( request.getHeader(MARKER_HEADER) != null ) {
+ String requestedWith = request.getHeader("X-Requested-With");
+ if ( requestedWith != null && requestedWith.equals( MARKER_HEADER) ) {
return SupportType.SHOULD;
}
if ( request.getBody().startsWith("{")
&& request.getBody().endsWith("}") ) {
return SupportType.MAY;
}
return SupportType.NO;
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
protected JSONObject readJSONRequest( IHttpRequest request )
throws IOException {
String requestData = request.getBody();
if ( requestData.isEmpty() ) {
throw new IllegalArgumentException("Request is empty");
}
return this.readJSONRequest( requestData );
}
protected JSONObject readJSONRequest(String data) {
return JSONObject.fromObject(data);
}
@Override
public void process(IHttpRequest request) throws ProcessingException {
try {
JSONObject object = this.readJSONRequest( request );
for ( Object key : object.keySet() ) {
request.setParameter( String.valueOf( key ), object.get(key) );
}
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
}
| true | true | public SupportType check(IHttpRequest request) throws ProcessingException {
try {
if ( !request.isPost() ) {
return SupportType.NO;
}
if ( request.getHeader(MARKER_HEADER) != null ) {
return SupportType.SHOULD;
}
if ( request.getBody().startsWith("{")
&& request.getBody().endsWith("}") ) {
return SupportType.MAY;
}
return SupportType.NO;
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
| public SupportType check(IHttpRequest request) throws ProcessingException {
try {
if ( !request.isPost() ) {
return SupportType.NO;
}
String requestedWith = request.getHeader("X-Requested-With");
if ( requestedWith != null && requestedWith.equals( MARKER_HEADER) ) {
return SupportType.SHOULD;
}
if ( request.getBody().startsWith("{")
&& request.getBody().endsWith("}") ) {
return SupportType.MAY;
}
return SupportType.NO;
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
|
diff --git a/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java b/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java
index a50e2bc2..e13fcdc4 100644
--- a/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java
+++ b/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java
@@ -1,157 +1,157 @@
/* Copyright 2005-2006 Tim Fennell
*
* 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 net.sourceforge.stripes.tag;
import net.sourceforge.stripes.exception.StripesJspException;
import net.sourceforge.stripes.util.HtmlUtil;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTag;
import java.io.IOException;
/**
* <p>Generates an {@literal <option value="foo">Fooey</option>} HTML tag. Coordinates with an
* enclosing select tag to determine it's state (i.e. whether or not it is selected.) As a result
* some of the logic regarding state repopulation is a bit complex.</p>
*
* <p>Since options can have only a single value per option the value attribute of the tag
* must be a scalar, which will be converted into a String using a Formatter if an
* appropriate one can be found, otherwise the toString() method will be invoked. The presence of
* a "selected" attribute is used as an indication that this option believes it should be selected
* by default - the value (as opposed to the presence) of the selected attribute is never used....</p>
*
* <p>The option tag delegates to its enclosing select tag to determine whether or not it should
* be selected. See the {@link InputSelectTag "select tag"} for documentation on how it
* determines selection status. If the select tag <em>has no opinion</em> on selection state
* (note that this is not the same as select tag deeming the option should not be selected) then
* the presence of the selected attribute (or lack thereof) is used to turn selection on or off.</p>
*
* <p>If the option has a body then the String value of that body will be used to generate the
* body of the generated HTML option. If the body is empty or not present then the label attribute
* will be written into the body of the tag.</p>
*
* @author Tim Fennell
*/
public class InputOptionTag extends InputTagSupport implements BodyTag {
private String selected;
private String label;
private Object value;
/** Sets the value of this option. */
public void setValue(Object value) { this.value = value; }
/** Returns the value of the option as set with setValue(). */
public Object getValue() { return this.value; }
/** Sets the label that will be used as the option body if no body is supplied. */
public void setLabel(String label) { this.label = label; }
/** Returns the value set with setLabel(). */
public String getLabel() { return this.label; }
/** Sets whether or not this option believes it should be selected by default. */
public void setSelected(String selected) { this.selected = selected; }
/** Returns the value set with setSelected(). */
public String getSelected() { return this.selected; }
/**
* Does nothing.
* @return EVAL_BODY_BUFFERED in all cases.
*/
@Override
public int doStartInputTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
/** Does nothing. */
public void doInitBody() throws JspException {
}
/**
* Does nothing.
* @return SKIP_BODY in all cases.
*/
public int doAfterBody() throws JspException {
return SKIP_BODY;
}
/**
* Locates the option's parent select tag, determines selection state and then writes out
* an option tag with an appropriate body.
*
* @return EVAL_PAGE in all cases.
* @throws JspException if the option is not contained inside an InputSelectTag or output
* cannot be written.
*/
@Override
public int doEndInputTag() throws JspException {
// Find our mandatory enclosing select tag
InputSelectTag selectTag = getParentTag(InputSelectTag.class);
if (selectTag == null) {
throw new StripesJspException
("Option tags must always be contained inside a select tag.");
}
// Decide if the label will come from the body of the option, of the label attr
String actualLabel = getBodyContentAsString();
if (actualLabel == null) {
- actualLabel = this.label;
+ actualLabel = HtmlUtil.encode(this.label);
}
// If no explicit value attribute set, use the tag label as the value
Object actualValue;
if (this.value == null) {
actualValue = actualLabel;
}
else {
actualValue = this.value;
}
getAttributes().put("value", format(actualValue));
// Determine if the option should be selected
if (selectTag.isOptionSelected(actualValue, (this.selected != null))) {
getAttributes().put("selected", "selected");
}
// And finally write the tag out to the page
try {
writeOpenTag(getPageContext().getOut(), "option");
if (actualLabel != null) {
- getPageContext().getOut().write(HtmlUtil.encode(actualLabel));
+ getPageContext().getOut().write(actualLabel);
}
writeCloseTag(getPageContext().getOut(), "option");
// Clean out the attributes we modified
getAttributes().remove("selected");
getAttributes().remove("value");
}
catch (IOException ioe) {
throw new JspException("IOException in InputOptionTag.doEndTag().", ioe);
}
return EVAL_PAGE;
}
/**
* Overridden to make sure that options do not try and register themselves with
* the form tag. This is done because options are not standalone input tags, but
* always part of a select tag (which gets registered).
*/
@Override
protected void registerWithParentForm() throws StripesJspException {
// Do nothing, options are not standalone fields and should not register
}
}
| false | true | public int doEndInputTag() throws JspException {
// Find our mandatory enclosing select tag
InputSelectTag selectTag = getParentTag(InputSelectTag.class);
if (selectTag == null) {
throw new StripesJspException
("Option tags must always be contained inside a select tag.");
}
// Decide if the label will come from the body of the option, of the label attr
String actualLabel = getBodyContentAsString();
if (actualLabel == null) {
actualLabel = this.label;
}
// If no explicit value attribute set, use the tag label as the value
Object actualValue;
if (this.value == null) {
actualValue = actualLabel;
}
else {
actualValue = this.value;
}
getAttributes().put("value", format(actualValue));
// Determine if the option should be selected
if (selectTag.isOptionSelected(actualValue, (this.selected != null))) {
getAttributes().put("selected", "selected");
}
// And finally write the tag out to the page
try {
writeOpenTag(getPageContext().getOut(), "option");
if (actualLabel != null) {
getPageContext().getOut().write(HtmlUtil.encode(actualLabel));
}
writeCloseTag(getPageContext().getOut(), "option");
// Clean out the attributes we modified
getAttributes().remove("selected");
getAttributes().remove("value");
}
catch (IOException ioe) {
throw new JspException("IOException in InputOptionTag.doEndTag().", ioe);
}
return EVAL_PAGE;
}
| public int doEndInputTag() throws JspException {
// Find our mandatory enclosing select tag
InputSelectTag selectTag = getParentTag(InputSelectTag.class);
if (selectTag == null) {
throw new StripesJspException
("Option tags must always be contained inside a select tag.");
}
// Decide if the label will come from the body of the option, of the label attr
String actualLabel = getBodyContentAsString();
if (actualLabel == null) {
actualLabel = HtmlUtil.encode(this.label);
}
// If no explicit value attribute set, use the tag label as the value
Object actualValue;
if (this.value == null) {
actualValue = actualLabel;
}
else {
actualValue = this.value;
}
getAttributes().put("value", format(actualValue));
// Determine if the option should be selected
if (selectTag.isOptionSelected(actualValue, (this.selected != null))) {
getAttributes().put("selected", "selected");
}
// And finally write the tag out to the page
try {
writeOpenTag(getPageContext().getOut(), "option");
if (actualLabel != null) {
getPageContext().getOut().write(actualLabel);
}
writeCloseTag(getPageContext().getOut(), "option");
// Clean out the attributes we modified
getAttributes().remove("selected");
getAttributes().remove("value");
}
catch (IOException ioe) {
throw new JspException("IOException in InputOptionTag.doEndTag().", ioe);
}
return EVAL_PAGE;
}
|
diff --git a/src/java/org/wings/plaf/css/BorderLayoutCG.java b/src/java/org/wings/plaf/css/BorderLayoutCG.java
index 8f86e7ee..1ea8494f 100644
--- a/src/java/org/wings/plaf/css/BorderLayoutCG.java
+++ b/src/java/org/wings/plaf/css/BorderLayoutCG.java
@@ -1,120 +1,121 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.wings.SBorderLayout;
import org.wings.SComponent;
import org.wings.SLayoutManager;
import org.wings.io.Device;
import java.io.IOException;
import java.awt.*;
public class BorderLayoutCG extends AbstractLayoutCG {
public void write(Device d, SLayoutManager l)
throws IOException {
final SBorderLayout layout = (SBorderLayout) l;
final SComponent north = (SComponent) layout.getComponents().get(SBorderLayout.NORTH);
final SComponent east = (SComponent) layout.getComponents().get(SBorderLayout.EAST);
final SComponent center = (SComponent) layout.getComponents().get(SBorderLayout.CENTER);
final SComponent west = (SComponent) layout.getComponents().get(SBorderLayout.WEST);
final SComponent south = (SComponent) layout.getComponents().get(SBorderLayout.SOUTH);
final Insets layoutInsets = convertGapsToInset(layout.getHgap(), layout.getVgap());
- int cols = 0;
+ int cols = 1;
if (west != null) cols++;
- if (center != null) cols++;
if (east != null) cols++;
printLayouterTableHeader(d, "SBorderLayout", layoutInsets, layout.getBorder(),layout);
if (north != null) {
d.print("<tr style=\"height: 0%\">");
Utils.printNewline(d, north);
d.print("<td colspan=\"").print(cols).print("\"");
Utils.printTableCellAlignment(d, north);
Utils.optAttribute(d, "style", decorateLayoutCell(north));
d.print(">");
north.write(d);
d.print("</td>");
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
Utils.printNewline(d, layout.getContainer());
}
d.print("<tr style=\"height: 100%\">");
if (west != null) {
Utils.printNewline(d, west);
d.print("<td width=\"0%\"");
Utils.printTableCellAlignment(d, west);
Utils.optAttribute(d, "style", decorateLayoutCell(west));
d.print(">");
west.write(d);
d.print("</td>");
}
if (center != null) {
Utils.printNewline(d, center);
d.print("<td width=\"100%\"");
Utils.printTableCellAlignment(d, center);
Utils.optAttribute(d, "style", decorateLayoutCell(center));
d.print(">");
center.write(d);
d.print("</td>");
+ } else {
+ d.print("<td width=\"100%\"></td>");
}
if (east != null) {
Utils.printNewline(d, east);
d.print("<td width=\"0%\"");
Utils.printTableCellAlignment(d, east);
Utils.optAttribute(d, "style", decorateLayoutCell(east));
d.print(">");
east.write(d);
d.print("</td>");
}
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
if (south != null) {
Utils.printNewline(d, layout.getContainer());
d.print("<tr style=\"height: 0%\">");
Utils.printNewline(d, south);
d.print("<td colspan=\"").print(cols).print("\"");
Utils.printTableCellAlignment(d, south);
Utils.optAttribute(d, "style", decorateLayoutCell(south));
d.print(">");
south.write(d);
d.print("</td>");
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
}
printLayouterTableFooter(d, "SBorderLayout", layout);
}
/**
* To be ovverriden by MSIE an other variants.
* @param containedComponent
* @return Style string
*/
protected String decorateLayoutCell(SComponent containedComponent) {
return null;
}
}
| false | true | public void write(Device d, SLayoutManager l)
throws IOException {
final SBorderLayout layout = (SBorderLayout) l;
final SComponent north = (SComponent) layout.getComponents().get(SBorderLayout.NORTH);
final SComponent east = (SComponent) layout.getComponents().get(SBorderLayout.EAST);
final SComponent center = (SComponent) layout.getComponents().get(SBorderLayout.CENTER);
final SComponent west = (SComponent) layout.getComponents().get(SBorderLayout.WEST);
final SComponent south = (SComponent) layout.getComponents().get(SBorderLayout.SOUTH);
final Insets layoutInsets = convertGapsToInset(layout.getHgap(), layout.getVgap());
int cols = 0;
if (west != null) cols++;
if (center != null) cols++;
if (east != null) cols++;
printLayouterTableHeader(d, "SBorderLayout", layoutInsets, layout.getBorder(),layout);
if (north != null) {
d.print("<tr style=\"height: 0%\">");
Utils.printNewline(d, north);
d.print("<td colspan=\"").print(cols).print("\"");
Utils.printTableCellAlignment(d, north);
Utils.optAttribute(d, "style", decorateLayoutCell(north));
d.print(">");
north.write(d);
d.print("</td>");
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
Utils.printNewline(d, layout.getContainer());
}
d.print("<tr style=\"height: 100%\">");
if (west != null) {
Utils.printNewline(d, west);
d.print("<td width=\"0%\"");
Utils.printTableCellAlignment(d, west);
Utils.optAttribute(d, "style", decorateLayoutCell(west));
d.print(">");
west.write(d);
d.print("</td>");
}
if (center != null) {
Utils.printNewline(d, center);
d.print("<td width=\"100%\"");
Utils.printTableCellAlignment(d, center);
Utils.optAttribute(d, "style", decorateLayoutCell(center));
d.print(">");
center.write(d);
d.print("</td>");
}
if (east != null) {
Utils.printNewline(d, east);
d.print("<td width=\"0%\"");
Utils.printTableCellAlignment(d, east);
Utils.optAttribute(d, "style", decorateLayoutCell(east));
d.print(">");
east.write(d);
d.print("</td>");
}
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
if (south != null) {
Utils.printNewline(d, layout.getContainer());
d.print("<tr style=\"height: 0%\">");
Utils.printNewline(d, south);
d.print("<td colspan=\"").print(cols).print("\"");
Utils.printTableCellAlignment(d, south);
Utils.optAttribute(d, "style", decorateLayoutCell(south));
d.print(">");
south.write(d);
d.print("</td>");
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
}
printLayouterTableFooter(d, "SBorderLayout", layout);
}
| public void write(Device d, SLayoutManager l)
throws IOException {
final SBorderLayout layout = (SBorderLayout) l;
final SComponent north = (SComponent) layout.getComponents().get(SBorderLayout.NORTH);
final SComponent east = (SComponent) layout.getComponents().get(SBorderLayout.EAST);
final SComponent center = (SComponent) layout.getComponents().get(SBorderLayout.CENTER);
final SComponent west = (SComponent) layout.getComponents().get(SBorderLayout.WEST);
final SComponent south = (SComponent) layout.getComponents().get(SBorderLayout.SOUTH);
final Insets layoutInsets = convertGapsToInset(layout.getHgap(), layout.getVgap());
int cols = 1;
if (west != null) cols++;
if (east != null) cols++;
printLayouterTableHeader(d, "SBorderLayout", layoutInsets, layout.getBorder(),layout);
if (north != null) {
d.print("<tr style=\"height: 0%\">");
Utils.printNewline(d, north);
d.print("<td colspan=\"").print(cols).print("\"");
Utils.printTableCellAlignment(d, north);
Utils.optAttribute(d, "style", decorateLayoutCell(north));
d.print(">");
north.write(d);
d.print("</td>");
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
Utils.printNewline(d, layout.getContainer());
}
d.print("<tr style=\"height: 100%\">");
if (west != null) {
Utils.printNewline(d, west);
d.print("<td width=\"0%\"");
Utils.printTableCellAlignment(d, west);
Utils.optAttribute(d, "style", decorateLayoutCell(west));
d.print(">");
west.write(d);
d.print("</td>");
}
if (center != null) {
Utils.printNewline(d, center);
d.print("<td width=\"100%\"");
Utils.printTableCellAlignment(d, center);
Utils.optAttribute(d, "style", decorateLayoutCell(center));
d.print(">");
center.write(d);
d.print("</td>");
} else {
d.print("<td width=\"100%\"></td>");
}
if (east != null) {
Utils.printNewline(d, east);
d.print("<td width=\"0%\"");
Utils.printTableCellAlignment(d, east);
Utils.optAttribute(d, "style", decorateLayoutCell(east));
d.print(">");
east.write(d);
d.print("</td>");
}
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
if (south != null) {
Utils.printNewline(d, layout.getContainer());
d.print("<tr style=\"height: 0%\">");
Utils.printNewline(d, south);
d.print("<td colspan=\"").print(cols).print("\"");
Utils.printTableCellAlignment(d, south);
Utils.optAttribute(d, "style", decorateLayoutCell(south));
d.print(">");
south.write(d);
d.print("</td>");
Utils.printNewline(d, layout.getContainer());
d.print("</tr>");
}
printLayouterTableFooter(d, "SBorderLayout", layout);
}
|
diff --git a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java
index e243909c5..eef83d322 100644
--- a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java
+++ b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java
@@ -1,132 +1,143 @@
/*
* Copyright 2006 Wyona
*/
package org.wyona.yanel.impl.resources.navigation;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yanel.core.navigation.Node;
import org.wyona.yanel.core.navigation.Sitetree;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.apache.log4j.Logger;
/**
*
*/
public class DataRepoSitetreeResource extends BasicXMLResource {
private static Logger log = Logger.getLogger(DataRepoSitetreeResource.class);
/**
*
*/
public DataRepoSitetreeResource() {
}
/**
*
*/
public long getSize() throws Exception {
return -1;
}
/**
*
*/
public boolean exists() throws Exception {
return true;
}
/**
*
*/
public java.io.InputStream getContentXML(String viewId) throws Exception {
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
sb.append(getSitetreeAsXML());
//sb.append(getSitetreeAsXML(getPath().toString()));
return new java.io.StringBufferInputStream(sb.toString());
}
/**
* Get sitetree as XML
*/
private String getSitetreeAsXML() {
StringBuffer sb = new StringBuffer("<sitetree>");
if (getRequest().getParameter("path") != null) {
sb.append(getNodeAsXML(request.getParameter("path")));
} else {
sb.append(getNodeAsXML("/"));
}
// TODO: Sitetree generated out of RDF resources and statements
/*
com.hp.hpl.jena.rdf.model.Resource rootResource = getRealm().getSitetreeRootResource();
sb.append(getNodeAsXML(rootResource));
*/
sb.append("</sitetree>");
return sb.toString();
}
/**
* Get node as XML
*/
private String getNodeAsXML(String path) {
//private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) {
//log.error("DEBUG: Path: " + path);
Sitetree sitetree = getRealm().getRepoNavigation();
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
// TODO: Check for statements "parentOf" for this resource
/*
Statement[] st = resource.getStatements("parentOf");
if (st.length > 0) {
for (int i = 0; i < st.length; i++) {
Resource child = st.getObject();
URL url = getReal().getURLBuilder(child);
}
} else {
// Is not a collection, there are no children
}
*/
if (node != null) {
if (node.isCollection()) {
sb.append("<collection path=\"" + path + "\" name=\"" + node.getName() + "\">");
+ // TODO: ...
+ sb.append("<label><![CDATA[" + node.getName() + "]]></label>");
+ //sb.append("<label><![CDATA[" + node.getLabel() + "]]></label>");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
String childPath = path + "/" + children[i].getName();
if (path.equals("/")) {
childPath = path + children[i].getName();
}
//log.debug("Child path: " + childPath);
if (children[i].isCollection()) {
sb.append(getNodeAsXML(childPath));
//sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
- sb.append("<resource path=\"" + childPath + "\" name=\"" + children[i].getName() + "\"/>");
- //sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
+ sb.append("<resource path=\"" + childPath + "\" name=\"" + children[i].getName() + "\">");
+ //sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\">");
+ // TODO ...
+ sb.append("<label><![CDATA[" + children[i].getName() + "]]></label>");
+ //sb.append("<label><![CDATA[" + children[i].getLabel() + "]]></label>");
+ sb.append("</resource>");
} else {
sb.append("<neither-resource-nor-collection path=\"" + childPath + "\" name=\"" + children[i].getName() + "\"/>");
//sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
}
}
sb.append("</collection>");
} else {
- sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>");
+ sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\">");
+ // TODO ...
+ sb.append("<label><![CDATA[" + node.getName() + "]]></label>");
+ //sb.append("<label><![CDATA[" + node.getLabel() + "]]></label>");
+ sb.append("</resource>");
}
} else {
String errorMessage = "node is null for path: " + path;
sb.append("<exception>" + errorMessage + "</exception>");
log.error(errorMessage);
}
return sb.toString();
}
}
| false | true | private String getNodeAsXML(String path) {
//private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) {
//log.error("DEBUG: Path: " + path);
Sitetree sitetree = getRealm().getRepoNavigation();
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
// TODO: Check for statements "parentOf" for this resource
/*
Statement[] st = resource.getStatements("parentOf");
if (st.length > 0) {
for (int i = 0; i < st.length; i++) {
Resource child = st.getObject();
URL url = getReal().getURLBuilder(child);
}
} else {
// Is not a collection, there are no children
}
*/
if (node != null) {
if (node.isCollection()) {
sb.append("<collection path=\"" + path + "\" name=\"" + node.getName() + "\">");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
String childPath = path + "/" + children[i].getName();
if (path.equals("/")) {
childPath = path + children[i].getName();
}
//log.debug("Child path: " + childPath);
if (children[i].isCollection()) {
sb.append(getNodeAsXML(childPath));
//sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
sb.append("<resource path=\"" + childPath + "\" name=\"" + children[i].getName() + "\"/>");
//sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
} else {
sb.append("<neither-resource-nor-collection path=\"" + childPath + "\" name=\"" + children[i].getName() + "\"/>");
//sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
}
}
sb.append("</collection>");
} else {
sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>");
}
} else {
String errorMessage = "node is null for path: " + path;
sb.append("<exception>" + errorMessage + "</exception>");
log.error(errorMessage);
}
return sb.toString();
}
| private String getNodeAsXML(String path) {
//private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) {
//log.error("DEBUG: Path: " + path);
Sitetree sitetree = getRealm().getRepoNavigation();
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
// TODO: Check for statements "parentOf" for this resource
/*
Statement[] st = resource.getStatements("parentOf");
if (st.length > 0) {
for (int i = 0; i < st.length; i++) {
Resource child = st.getObject();
URL url = getReal().getURLBuilder(child);
}
} else {
// Is not a collection, there are no children
}
*/
if (node != null) {
if (node.isCollection()) {
sb.append("<collection path=\"" + path + "\" name=\"" + node.getName() + "\">");
// TODO: ...
sb.append("<label><![CDATA[" + node.getName() + "]]></label>");
//sb.append("<label><![CDATA[" + node.getLabel() + "]]></label>");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
String childPath = path + "/" + children[i].getName();
if (path.equals("/")) {
childPath = path + children[i].getName();
}
//log.debug("Child path: " + childPath);
if (children[i].isCollection()) {
sb.append(getNodeAsXML(childPath));
//sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
sb.append("<resource path=\"" + childPath + "\" name=\"" + children[i].getName() + "\">");
//sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\">");
// TODO ...
sb.append("<label><![CDATA[" + children[i].getName() + "]]></label>");
//sb.append("<label><![CDATA[" + children[i].getLabel() + "]]></label>");
sb.append("</resource>");
} else {
sb.append("<neither-resource-nor-collection path=\"" + childPath + "\" name=\"" + children[i].getName() + "\"/>");
//sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
}
}
sb.append("</collection>");
} else {
sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\">");
// TODO ...
sb.append("<label><![CDATA[" + node.getName() + "]]></label>");
//sb.append("<label><![CDATA[" + node.getLabel() + "]]></label>");
sb.append("</resource>");
}
} else {
String errorMessage = "node is null for path: " + path;
sb.append("<exception>" + errorMessage + "</exception>");
log.error(errorMessage);
}
return sb.toString();
}
|
diff --git a/src/com/anjlab/ping/pages/Feedback.java b/src/com/anjlab/ping/pages/Feedback.java
index dbbe49b..17451a4 100644
--- a/src/com/anjlab/ping/pages/Feedback.java
+++ b/src/com/anjlab/ping/pages/Feedback.java
@@ -1,72 +1,74 @@
package com.anjlab.ping.pages;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import com.anjlab.ping.services.GAEHelper;
import com.anjlab.ping.services.Mailer;
import com.anjlab.tapestry5.Utils;
public class Feedback {
@Property
private String message;
@Property
private String note;
@AfterRender
public void cleanup() {
message = null;
thanks = null;
note = null;
}
@Property
@Persist
@SuppressWarnings("unused")
private String thanks;
@Inject
private Request request;
public void onActivate() {
String subject = request.getParameter("subject");
this.message = Utils.isNullOrEmpty(subject) ? null : subject + "\n\n";
if (!Utils.isNullOrEmpty(subject)) {
this.note = "Please, provide more information so that we can help you";
}
if (gaeHelper.getUserPrincipal() == null) {
String replyToReminder = "specify your email address in the message text in case you want us to contact you.";
if (this.note != null) {
this.note += ", and don't forget to " + replyToReminder;
} else {
this.note = "Please, " + replyToReminder;
}
} else {
- this.note += ".";
+ if (this.note != null) {
+ this.note += ".";
+ }
}
}
@Inject
private GAEHelper gaeHelper;
@Inject
private Mailer mailer;
public void onSuccess() {
String subject = "Ping Service Feedback";
mailer.sendMail(
gaeHelper.getUserPrincipal() == null ? Mailer.PING_SERVICE_NOTIFY_GMAIL_COM
: gaeHelper.getUserPrincipal().getName(),
Mailer.DMITRY_GUSEV_GMAIL_COM, subject, message);
thanks = "Thanks for sharing your feedback!";
}
}
| true | true | public void onActivate() {
String subject = request.getParameter("subject");
this.message = Utils.isNullOrEmpty(subject) ? null : subject + "\n\n";
if (!Utils.isNullOrEmpty(subject)) {
this.note = "Please, provide more information so that we can help you";
}
if (gaeHelper.getUserPrincipal() == null) {
String replyToReminder = "specify your email address in the message text in case you want us to contact you.";
if (this.note != null) {
this.note += ", and don't forget to " + replyToReminder;
} else {
this.note = "Please, " + replyToReminder;
}
} else {
this.note += ".";
}
}
| public void onActivate() {
String subject = request.getParameter("subject");
this.message = Utils.isNullOrEmpty(subject) ? null : subject + "\n\n";
if (!Utils.isNullOrEmpty(subject)) {
this.note = "Please, provide more information so that we can help you";
}
if (gaeHelper.getUserPrincipal() == null) {
String replyToReminder = "specify your email address in the message text in case you want us to contact you.";
if (this.note != null) {
this.note += ", and don't forget to " + replyToReminder;
} else {
this.note = "Please, " + replyToReminder;
}
} else {
if (this.note != null) {
this.note += ".";
}
}
}
|
diff --git a/aura-impl/src/test/java/org/auraframework/impl/context/AuraContextImplTest.java b/aura-impl/src/test/java/org/auraframework/impl/context/AuraContextImplTest.java
index 95e6f87932..87d0ba3ef2 100644
--- a/aura-impl/src/test/java/org/auraframework/impl/context/AuraContextImplTest.java
+++ b/aura-impl/src/test/java/org/auraframework/impl/context/AuraContextImplTest.java
@@ -1,256 +1,256 @@
/*
* Copyright (C) 2012 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.context;
import java.util.List;
import java.util.Set;
import org.auraframework.Aura;
import org.auraframework.def.ApplicationDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.EventDef;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.instance.Event;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Access;
import org.auraframework.system.AuraContext.Format;
import org.auraframework.system.AuraContext.Mode;
import org.auraframework.test.annotation.UnAdaptableTest;
import org.auraframework.util.json.Json;
/**
* Unit tests for AuraContextImpl.
*
* @hierarchy Aura.Basic
* @priority high
* @userStory a07B0000000DfxB
*/
public class AuraContextImplTest extends AuraImplTestCase {
public AuraContextImplTest(String name) {
super(name);
}
/**
* Verify the basic configuration in place for preloading namespaces.
* AuraContextImpl keeps track of namespaces whose definitions should be
* preLoaded. This test would act like a gold file for namespaces selected
* to be pre-loaded. Be sure to consider what namespaces you are specifying
* for pre-loading.
*
* @userStory a07B0000000EYU4
*/
public void testPreloadConfigurations() throws Exception {
AuraContext lc = Aura.getContextService().getCurrentContext();
Set<String> preloadNamespace = lc.getPreloads();
// Verify that 'ui' and 'Aura' are always specified as standard preload
// namespaces
// don't verify anything else as more preloads could be injected through
// adapters
assertTrue("UI namespace not specified as standard preload namespace", preloadNamespace.contains("ui"));
assertTrue("aura namespace not specified as standard preload namespace", preloadNamespace.contains("aura"));
}
/**
* Verify methods on AuraContext to alter pre-load configurations.
*
* @userStory a07B0000000EYU4
*/
public void testPreloadConfigurationMethods() throws Exception {
AuraContext lc = Aura.getContextService().getCurrentContext();
lc.clearPreloads();
Set<String> preloadNamespace = lc.getPreloads();
assertTrue("Preload namespace configuration could not be reset", preloadNamespace.size() == 0);
lc.addPreload("auratest");
preloadNamespace = lc.getPreloads();
assertTrue("Preload namespace configuration could not be changed", preloadNamespace.contains("auratest"));
}
/**
* Verify the serialized format of a ComponentDef when it belongs to a
* pre-load namespace. Components which belong to a pre-load namespace will
* only have the descriptor as part of their ComponentDef. This descriptor
* will be used on the client side to obtain the full blown componentDef.
*/
public void testComponentDefSerializedFormat() throws Exception {
ApplicationDef cDef = Aura.getDefinitionService().getDefinition("preloadTest:test_Preload_Cmp_SameNameSpace",
ApplicationDef.class);
// Set<String> preloadNamespace = cDef.getPreloads();
// assertTrue(preloadNamespace.contains("preloadTest"));
AuraContext lc = Aura.getContextService().getCurrentContext();
lc.addPreload("preloadTest");
assertEquals("{\"descriptor\":\"markup://preloadTest:test_Preload_Cmp_SameNameSpace\"}", Json.serialize(cDef));
}
/**
* Verify we are able to check what DefDescriptors have been preloaded.
*/
public void testIsPreloaded() throws Exception {
AuraContext lc = Aura.getContextService().getCurrentContext();
lc.clearPreloads();
lc.addPreload("auratest");
// Check in preloaded namesapce
DefDescriptor<ComponentDef> dd = vendor.makeComponentDefDescriptor("auratest:text");
assertTrue("Descriptor in preloaded namespace not found", lc.isPreloaded(dd));
// Check in namespace that is not preloaded
dd = vendor.makeComponentDefDescriptor("aura:text");
assertTrue("Descriptor in namespace *not* preloaded found", !lc.isPreloaded(dd));
// Check after preloads cleared
lc.clearPreloads();
dd = vendor.makeComponentDefDescriptor("auratest:text");
assertTrue("Descriptor found after preloads cleared", !lc.isPreloaded(dd));
}
/**
* Verify clearing current preloads in AuraContext AuraContext.preloading
* indicates whether components defs are currently being preloaded.
*/
public void testClearPreloads() throws Exception {
AuraContext lc = Aura.getContextService().getCurrentContext();
lc.clearPreloads();
Set<String> preloadNamespace = lc.getPreloads();
assertEquals("Calling clearPreloads() should clear the context of all preload namespaces.", 0,
preloadNamespace.size());
}
/**
* Context app descriptor gets serialized.
*/
@UnAdaptableTest
public void testSerializeWithApp() throws Exception {
DefDescriptor<ApplicationDef> desc = Aura.getDefinitionService().getDefDescriptor("arbitrary:appname",
ApplicationDef.class);
AuraContext ctx = Aura.getContextService().startContext(Mode.PROD, Format.JSON, Access.PUBLIC, desc);
ctx.setSerializeLastMod(false);
String res = Json.serialize(ctx, ctx.getJsonSerializationContext());
goldFileJson(res);
}
/**
* Context app descriptor gets serialized.
*/
@UnAdaptableTest
public void testSerializeWithCmp() throws Exception {
DefDescriptor<ComponentDef> desc = Aura.getDefinitionService().getDefDescriptor("arbitrary:cmpname",
ComponentDef.class);
AuraContext ctx = Aura.getContextService().startContext(Mode.PROD, Format.JSON, Access.PUBLIC, desc);
ctx.setSerializeLastMod(false);
String res = Json.serialize(ctx, ctx.getJsonSerializationContext());
goldFileJson(res);
}
/**
* App not serialized for context without descriptor.
*/
@UnAdaptableTest
public void testSerializeWithoutApp() throws Exception {
AuraContext ctx = Aura.getContextService().startContext(Mode.PROD, Format.JSON, Access.PUBLIC);
ctx.setSerializeLastMod(false);
String res = Json.serialize(ctx, ctx.getJsonSerializationContext());
goldFileJson(res);
}
/**
* Verify setting a Context's DefDescriptor.
*/
@UnAdaptableTest
public void testSetApplicationDescriptor() throws Exception {
DefDescriptor<ApplicationDef> descApp1 = Aura.getDefinitionService().getDefDescriptor("arbitrary:appnameApp1",
ApplicationDef.class);
DefDescriptor<ApplicationDef> descApp2 = Aura.getDefinitionService().getDefDescriptor("arbitrary:appnameApp2",
ApplicationDef.class);
DefDescriptor<ComponentDef> descCmp = Aura.getDefinitionService().getDefDescriptor("arbitrary:cmpname",
ComponentDef.class);
AuraContext ctx = Aura.getContextService().startContext(Mode.PROD, Format.JSON, Access.PUBLIC);
ctx.setSerializeLastMod(false);
ctx.setApplicationDescriptor(descCmp);
assertEquals("ComponentDef should override a Context's null DefDescriptor", descCmp,
ctx.getApplicationDescriptor());
ctx.setApplicationDescriptor(descApp1);
assertEquals("ApplicationDef should override a Context's ComponentDef", descApp1,
ctx.getApplicationDescriptor());
ctx.setApplicationDescriptor(descApp2);
assertEquals("ApplicationDef should override current Context's ApplicationDef", descApp2,
ctx.getApplicationDescriptor());
ctx.setApplicationDescriptor(descCmp);
assertEquals("ComponentDef should not override current Context's ApplicationDef", descApp2,
ctx.getApplicationDescriptor());
}
/**
* Add events to context. Technique used by controllers to add events and
* send them down with action response.
*
* @throws Exception
*/
public void testAttachingEvents() throws Exception {
// Verify that nulls are filtered
AuraContext lc = Aura.getContextService().getCurrentContext();
try {
lc.addClientApplicationEvent(null);
assertEquals("Should not be accepting null objects as events.", 0, lc.getClientEvents().size());
} catch (Exception e) {
fail("Context.addClientApplicationEvent() does not handle nulls.");
}
Aura.getContextService().endContext();
// Adding multiple contexts
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt1 = Aura.getInstanceService().getInstance("markup://aura:applicationEvent", EventDef.class, null);
lc.addClientApplicationEvent(evt1);
- Event evt2 = Aura.getInstanceService().getInstance("markup://aura:noConnection", EventDef.class, null);
+ Event evt2 = Aura.getInstanceService().getInstance("markup://aura:connectionLost", EventDef.class, null);
lc.addClientApplicationEvent(evt2);
List<Event> evnts = lc.getClientEvents();
assertEquals("Found unexpected number of events on context", 2, evnts.size());
assertEquals("markup://aura:applicationEvent", evnts.get(0).getDescriptor().getQualifiedName());
- assertEquals("markup://aura:noConnection", evnts.get(1).getDescriptor().getQualifiedName());
+ assertEquals("markup://aura:connectionLost", evnts.get(1).getDescriptor().getQualifiedName());
Aura.getContextService().endContext();
// Adding same event again should not cause an error, same event can be
// fired with different parameters.
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt3 = Aura.getInstanceService().getInstance("markup://handleEventTest:applicationEvent", EventDef.class,
null);
lc.addClientApplicationEvent(evt3);
Event evt3_dup = Aura.getInstanceService().getInstance("markup://handleEventTest:applicationEvent",
EventDef.class, null);
lc.addClientApplicationEvent(evt3_dup);
assertEquals("Failed to add same event twice.", 2, evnts.size());
Aura.getContextService().endContext();
// Verify component events are not acceptable
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt4 = Aura.getInstanceService().getInstance("markup://handleEventTest:event", EventDef.class, null);
try {
lc.addClientApplicationEvent(evt4);
fail("Component events should not be allowed to be fired from server.");
} catch (Exception e) {
assertEquals("markup://handleEventTest:event is not an Application event. "
+ "Only Application events are allowed to be fired from server.", e.getMessage());
}
}
}
| false | true | public void testAttachingEvents() throws Exception {
// Verify that nulls are filtered
AuraContext lc = Aura.getContextService().getCurrentContext();
try {
lc.addClientApplicationEvent(null);
assertEquals("Should not be accepting null objects as events.", 0, lc.getClientEvents().size());
} catch (Exception e) {
fail("Context.addClientApplicationEvent() does not handle nulls.");
}
Aura.getContextService().endContext();
// Adding multiple contexts
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt1 = Aura.getInstanceService().getInstance("markup://aura:applicationEvent", EventDef.class, null);
lc.addClientApplicationEvent(evt1);
Event evt2 = Aura.getInstanceService().getInstance("markup://aura:noConnection", EventDef.class, null);
lc.addClientApplicationEvent(evt2);
List<Event> evnts = lc.getClientEvents();
assertEquals("Found unexpected number of events on context", 2, evnts.size());
assertEquals("markup://aura:applicationEvent", evnts.get(0).getDescriptor().getQualifiedName());
assertEquals("markup://aura:noConnection", evnts.get(1).getDescriptor().getQualifiedName());
Aura.getContextService().endContext();
// Adding same event again should not cause an error, same event can be
// fired with different parameters.
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt3 = Aura.getInstanceService().getInstance("markup://handleEventTest:applicationEvent", EventDef.class,
null);
lc.addClientApplicationEvent(evt3);
Event evt3_dup = Aura.getInstanceService().getInstance("markup://handleEventTest:applicationEvent",
EventDef.class, null);
lc.addClientApplicationEvent(evt3_dup);
assertEquals("Failed to add same event twice.", 2, evnts.size());
Aura.getContextService().endContext();
// Verify component events are not acceptable
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt4 = Aura.getInstanceService().getInstance("markup://handleEventTest:event", EventDef.class, null);
try {
lc.addClientApplicationEvent(evt4);
fail("Component events should not be allowed to be fired from server.");
} catch (Exception e) {
assertEquals("markup://handleEventTest:event is not an Application event. "
+ "Only Application events are allowed to be fired from server.", e.getMessage());
}
}
| public void testAttachingEvents() throws Exception {
// Verify that nulls are filtered
AuraContext lc = Aura.getContextService().getCurrentContext();
try {
lc.addClientApplicationEvent(null);
assertEquals("Should not be accepting null objects as events.", 0, lc.getClientEvents().size());
} catch (Exception e) {
fail("Context.addClientApplicationEvent() does not handle nulls.");
}
Aura.getContextService().endContext();
// Adding multiple contexts
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt1 = Aura.getInstanceService().getInstance("markup://aura:applicationEvent", EventDef.class, null);
lc.addClientApplicationEvent(evt1);
Event evt2 = Aura.getInstanceService().getInstance("markup://aura:connectionLost", EventDef.class, null);
lc.addClientApplicationEvent(evt2);
List<Event> evnts = lc.getClientEvents();
assertEquals("Found unexpected number of events on context", 2, evnts.size());
assertEquals("markup://aura:applicationEvent", evnts.get(0).getDescriptor().getQualifiedName());
assertEquals("markup://aura:connectionLost", evnts.get(1).getDescriptor().getQualifiedName());
Aura.getContextService().endContext();
// Adding same event again should not cause an error, same event can be
// fired with different parameters.
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt3 = Aura.getInstanceService().getInstance("markup://handleEventTest:applicationEvent", EventDef.class,
null);
lc.addClientApplicationEvent(evt3);
Event evt3_dup = Aura.getInstanceService().getInstance("markup://handleEventTest:applicationEvent",
EventDef.class, null);
lc.addClientApplicationEvent(evt3_dup);
assertEquals("Failed to add same event twice.", 2, evnts.size());
Aura.getContextService().endContext();
// Verify component events are not acceptable
lc = Aura.getContextService().startContext(Mode.UTEST, Format.JSON, Access.AUTHENTICATED);
Event evt4 = Aura.getInstanceService().getInstance("markup://handleEventTest:event", EventDef.class, null);
try {
lc.addClientApplicationEvent(evt4);
fail("Component events should not be allowed to be fired from server.");
} catch (Exception e) {
assertEquals("markup://handleEventTest:event is not an Application event. "
+ "Only Application events are allowed to be fired from server.", e.getMessage());
}
}
|
diff --git a/policy/src/main/java/brooklyn/policy/autoscaling/AutoScalerPolicy.java b/policy/src/main/java/brooklyn/policy/autoscaling/AutoScalerPolicy.java
index 0de3b7c32..06b4bdc3a 100644
--- a/policy/src/main/java/brooklyn/policy/autoscaling/AutoScalerPolicy.java
+++ b/policy/src/main/java/brooklyn/policy/autoscaling/AutoScalerPolicy.java
@@ -1,753 +1,753 @@
package brooklyn.policy.autoscaling;
import static brooklyn.util.GroovyJavaMethods.truth;
import static com.google.common.base.Preconditions.checkNotNull;
import groovy.lang.Closure;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.config.ConfigKey;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.EntityLocal;
import brooklyn.entity.trait.Resizable;
import brooklyn.entity.trait.Startable;
import brooklyn.event.AttributeSensor;
import brooklyn.event.Sensor;
import brooklyn.event.SensorEvent;
import brooklyn.event.SensorEventListener;
import brooklyn.event.basic.BasicConfigKey;
import brooklyn.event.basic.BasicNotificationSensor;
import brooklyn.policy.basic.AbstractPolicy;
import brooklyn.policy.loadbalancing.LoadBalancingPolicy;
import brooklyn.util.MutableMap;
import brooklyn.util.TimeWindowedList;
import brooklyn.util.TimestampedValue;
import brooklyn.util.flags.SetFromFlag;
import brooklyn.util.flags.TypeCoercions;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
/**
* Policy that is attached to a {@link Resizable} entity and dynamically adjusts its size in response to
* emitted {@code POOL_COLD} and {@code POOL_HOT} events. (This policy does not itself determine whether
* the pool is hot or cold, but instead relies on these events being emitted by the monitored entity itself, or
* by another policy that is attached to it; see, for example, {@link LoadBalancingPolicy}.)
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class AutoScalerPolicy extends AbstractPolicy {
private static final Logger LOG = LoggerFactory.getLogger(AutoScalerPolicy.class);
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String id;
private String name;
private AttributeSensor<? extends Number> metric;
private Entity entityWithMetric;
private Number metricUpperBound;
private Number metricLowerBound;
private int minPoolSize = 0;
private int maxPoolSize = Integer.MAX_VALUE;
private long minPeriodBetweenExecs = 100;
private long resizeUpStabilizationDelay;
private long resizeDownStabilizationDelay;
private ResizeOperator resizeOperator;
private Function<Entity,Integer> currentSizeOperator;
private BasicNotificationSensor<?> poolHotSensor;
private BasicNotificationSensor<?> poolColdSensor;
private BasicNotificationSensor<?> poolOkSensor;
public Builder id(String val) {
this.id = val; return this;
}
public Builder name(String val) {
this.name = val; return this;
}
public Builder metric(AttributeSensor<? extends Number> val) {
this.metric = val; return this;
}
public Builder entityWithMetric(Entity val) {
this.entityWithMetric = val; return this;
}
public Builder metricLowerBound(Number val) {
this.metricLowerBound = val; return this;
}
public Builder metricUpperBound(Number val) {
this.metricUpperBound = val; return this;
}
public Builder metricRange(Number min, Number max) {
metricLowerBound = checkNotNull(min);
metricUpperBound = checkNotNull(max);
return this;
}
public Builder minPoolSize(int val) {
this.minPoolSize = val; return this;
}
public Builder maxPoolSize(int val) {
this.maxPoolSize = val; return this;
}
public Builder sizeRange(int min, int max) {
minPoolSize = min;
maxPoolSize = max;
return this;
}
public Builder minPeriodBetweenExecs(long val) {
this.minPeriodBetweenExecs = val; return this;
}
public Builder resizeUpStabilizationDelay(long val) {
this.resizeUpStabilizationDelay = val; return this;
}
public Builder resizeDownStabilizationDelay(long val) {
this.resizeDownStabilizationDelay = val; return this;
}
public Builder resizeOperator(ResizeOperator val) {
this.resizeOperator = val; return this;
}
public Builder currentSizeOperator(Function<Entity, Integer> val) {
this.currentSizeOperator = val; return this;
}
public Builder poolHotSensor(BasicNotificationSensor<?> val) {
this.poolHotSensor = val; return this;
}
public Builder poolColdSensor(BasicNotificationSensor<?> val) {
this.poolColdSensor = val; return this;
}
public Builder poolOkSensor(BasicNotificationSensor<?> val) {
this.poolOkSensor = val; return this;
}
public AutoScalerPolicy build() {
return new AutoScalerPolicy(toFlags());
}
private Map<String,?> toFlags() {
return MutableMap.<String,Object>builder()
.putIfNotNull("id", id)
.putIfNotNull("name", name)
.putIfNotNull("metric", metric)
.putIfNotNull("entityWithMetric", entityWithMetric)
.putIfNotNull("metricUpperBound", metricUpperBound)
.putIfNotNull("metricLowerBound", metricLowerBound)
.putIfNotNull("minPoolSize", minPoolSize)
.putIfNotNull("maxPoolSize", maxPoolSize)
.putIfNotNull("minPeriodBetweenExecs", minPeriodBetweenExecs)
.putIfNotNull("resizeUpStabilizationDelay", resizeUpStabilizationDelay)
.putIfNotNull("resizeDownStabilizationDelay", resizeDownStabilizationDelay)
.putIfNotNull("resizeOperator", resizeOperator)
.putIfNotNull("currentSizeOperator", currentSizeOperator)
.putIfNotNull("poolHotSensor", poolHotSensor)
.putIfNotNull("poolColdSensor", poolColdSensor)
.putIfNotNull("poolOkSensor", poolOkSensor)
.build();
}
}
// TODO Is there a nicer pattern for registering such type-coercions?
// Can't put it in the ResizeOperator interface, nor in core TypeCoercions class because interface is defined in policy/.
static {
TypeCoercions.registerAdapter(Closure.class, ResizeOperator.class, new Function<Closure,ResizeOperator>() {
@Override
public ResizeOperator apply(final Closure closure) {
return new ResizeOperator() {
@Override public Integer resize(Entity entity, Integer input) {
return (Integer) closure.call(entity, input);
}
};
}
});
}
// Pool workrate notifications.
public static BasicNotificationSensor<Map> DEFAULT_POOL_HOT_SENSOR = new BasicNotificationSensor<Map>(
Map.class, "resizablepool.hot", "Pool is over-utilized; it has insufficient resource for current workload");
public static BasicNotificationSensor<Map> DEFAULT_POOL_COLD_SENSOR = new BasicNotificationSensor<Map>(
Map.class, "resizablepool.cold", "Pool is under-utilized; it has too much resource for current workload");
public static BasicNotificationSensor<Map> DEFAULT_POOL_OK_SENSOR = new BasicNotificationSensor<Map>(
Map.class, "resizablepool.cold", "Pool utilization is ok; the available resources are fine for the current workload");
public static final String POOL_CURRENT_SIZE_KEY = "pool.current.size";
public static final String POOL_HIGH_THRESHOLD_KEY = "pool.high.threshold";
public static final String POOL_LOW_THRESHOLD_KEY = "pool.low.threshold";
public static final String POOL_CURRENT_WORKRATE_KEY = "pool.current.workrate";
@SetFromFlag("metric")
public static final ConfigKey<AttributeSensor<? extends Number>> METRIC = BasicConfigKey.builder(new TypeToken<AttributeSensor<? extends Number>>() {})
.name("autoscaler.metric")
.build();
@SetFromFlag("entityWithMetric")
public static final ConfigKey<Entity> ENTITY_WITH_METRIC = BasicConfigKey.builder(Entity.class)
.name("autoscaler.entityWithMetric")
.build();
@SetFromFlag("metricLowerBound")
public static final ConfigKey<Number> METRIC_LOWER_BOUND = BasicConfigKey.builder(Number.class)
.name("autoscaler.metricLowerBound")
.build();
@SetFromFlag("metricUpperBound")
public static final ConfigKey<Number> METRIC_UPPER_BOUND = BasicConfigKey.builder(Number.class)
.name("autoscaler.metricUpperBound")
.build();
@SetFromFlag("minPeriodBetweenExecs")
public static final ConfigKey<Long> MIN_PERIOD_BETWEEN_EXECS = BasicConfigKey.builder(Long.class)
.name("autoscaler.minPeriodBetweenExecs")
.defaultValue(100L)
.build();
@SetFromFlag("resizeUpStabilizationDelay")
public static final ConfigKey<Long> RESIZE_UP_STABILIZATION_DELAY = BasicConfigKey.builder(Long.class)
.name("autoscaler.resizeUpStabilizationDelay")
.defaultValue(0l)
.build();
@SetFromFlag("resizeDownStabilizationDelay")
public static final ConfigKey<Long> RESIZE_DOWN_STABILIZATION_DELAY = BasicConfigKey.builder(Long.class)
.name("autoscaler.resizeDownStabilizationDelay")
.defaultValue(0l)
.build();
@SetFromFlag("minPoolSize")
public static final ConfigKey<Integer> MIN_POOL_SIZE = BasicConfigKey.builder(Integer.class)
.name("autoscaler.minPoolSize")
.defaultValue(0)
.build();
@SetFromFlag("maxPoolSize")
public static final ConfigKey<Integer> MAX_POOL_SIZE = BasicConfigKey.builder(Integer.class)
.name("autoscaler.maxPoolSize")
.defaultValue(Integer.MAX_VALUE)
.build();
@SetFromFlag("resizeOperator")
public static final ConfigKey<ResizeOperator> RESIZE_OPERATOR = BasicConfigKey.builder(ResizeOperator.class)
.name("autoscaler.resizeOperator")
.defaultValue(new ResizeOperator() {
public Integer resize(Entity entity, Integer desiredSize) {
return ((Resizable)entity).resize(desiredSize);
}})
.build();
@SetFromFlag("currentSizeOperator")
public static final ConfigKey<Function<Entity,Integer>> CURRENT_SIZE_OPERATOR = BasicConfigKey.builder(new TypeToken<Function<Entity,Integer>>() {})
.name("autoscaler.currentSizeOperator")
.defaultValue(new Function<Entity,Integer>() {
public Integer apply(Entity entity) {
return ((Resizable)entity).getCurrentSize();
}})
.build();
@SetFromFlag("poolHotSensor")
public static final ConfigKey<BasicNotificationSensor<? extends Map>> POOL_HOT_SENSOR = BasicConfigKey.builder(new TypeToken<BasicNotificationSensor<? extends Map>>() {})
.name("autoscaler.poolHotSensor")
.defaultValue(DEFAULT_POOL_HOT_SENSOR)
.build();
@SetFromFlag("poolColdSensor")
public static final ConfigKey<BasicNotificationSensor<? extends Map>> POOL_COLD_SENSOR = BasicConfigKey.builder(new TypeToken<BasicNotificationSensor<? extends Map>>() {})
.name("autoscaler.poolColdSensor")
.defaultValue(DEFAULT_POOL_COLD_SENSOR)
.build();
@SetFromFlag("poolOkSensor")
public static final ConfigKey<BasicNotificationSensor<? extends Map>> POOL_OK_SENSOR = BasicConfigKey.builder(new TypeToken<BasicNotificationSensor<? extends Map>>() {})
.name("autoscaler.poolOkSensor")
.defaultValue(DEFAULT_POOL_OK_SENSOR)
.build();
private Entity poolEntity;
private final AtomicBoolean executorQueued = new AtomicBoolean(false);
private volatile long executorTime = 0;
private volatile ScheduledExecutorService executor;
private final TimeWindowedList<Number> recentDesiredResizes;
private final SensorEventListener<Map> utilizationEventHandler = new SensorEventListener<Map>() {
public void onEvent(SensorEvent<Map> event) {
Map<String, ?> properties = (Map<String, ?>) event.getValue();
Sensor<?> sensor = event.getSensor();
if (sensor.equals(getPoolColdSensor())) {
onPoolCold(properties);
} else if (sensor.equals(getPoolHotSensor())) {
onPoolHot(properties);
} else if (sensor.equals(getPoolOkSensor())) {
onPoolOk(properties);
} else {
throw new IllegalStateException("Unexpected sensor type: "+sensor+"; event="+event);
}
}
};
private final SensorEventListener<Number> metricEventHandler = new SensorEventListener<Number>() {
public void onEvent(SensorEvent<Number> event) {
assert event.getSensor().equals(getMetric());
onMetricChanged(event.getValue());
}
};
public AutoScalerPolicy() {
this(MutableMap.<String,Object>of());
}
public AutoScalerPolicy(Map<String,?> props) {
super(props);
long maxResizeStabilizationDelay = Math.max(getResizeUpStabilizationDelay(), getResizeDownStabilizationDelay());
recentDesiredResizes = new TimeWindowedList<Number>(MutableMap.of("timePeriod", maxResizeStabilizationDelay, "minExpiredVals", 1));
// TODO Should re-use the execution manager's thread pool, somehow
executor = Executors.newSingleThreadScheduledExecutor(newThreadFactory());
}
public void setMetricLowerBound(Number val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing metricLowerBound from {} to {}", new Object[] {this, getMetricLowerBound(), val});
setConfig(METRIC_LOWER_BOUND, checkNotNull(val));
}
public void setMetricUpperBound(Number val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing metricUpperBound from {} to {}", new Object[] {this, getMetricUpperBound(), val});
setConfig(METRIC_UPPER_BOUND, checkNotNull(val));
}
public void setMinPeriodBetweenExecs(long val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing minPeriodBetweenExecs from {} to {}", new Object[] {this, getMinPeriodBetweenExecs(), val});
setConfig(MIN_PERIOD_BETWEEN_EXECS, val);
}
public void setResizeUpStabilizationDelay(long val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing resizeUpStabilizationDelay from {} to {}", new Object[] {this, getResizeUpStabilizationDelay(), val});
setConfig(RESIZE_UP_STABILIZATION_DELAY, val);
}
public void setResizeDownStabilizationDelay(long val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing resizeDownStabilizationDelay from {} to {}", new Object[] {this, getResizeDownStabilizationDelay(), val});
setConfig(RESIZE_DOWN_STABILIZATION_DELAY, val);
}
public void setMinPoolSize(int val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing minPoolSize from {} to {}", new Object[] {this, getMinPoolSize(), val});
setConfig(MIN_POOL_SIZE, val);
}
public void setMaxPoolSize(int val) {
if (LOG.isInfoEnabled()) LOG.info("{} changing maxPoolSize from {} to {}", new Object[] {this, getMaxPoolSize(), val});
setConfig(MAX_POOL_SIZE, val);
}
private AttributeSensor<? extends Number> getMetric() {
return getConfig(METRIC);
}
private Entity getEntityWithMetric() {
return getConfig(ENTITY_WITH_METRIC);
}
private Number getMetricLowerBound() {
return getConfig(METRIC_LOWER_BOUND);
}
private Number getMetricUpperBound() {
return getConfig(METRIC_UPPER_BOUND);
}
private long getMinPeriodBetweenExecs() {
return getConfig(MIN_PERIOD_BETWEEN_EXECS);
}
private long getResizeUpStabilizationDelay() {
return getConfig(RESIZE_UP_STABILIZATION_DELAY);
}
private long getResizeDownStabilizationDelay() {
return getConfig(RESIZE_DOWN_STABILIZATION_DELAY);
}
private int getMinPoolSize() {
return getConfig(MIN_POOL_SIZE);
}
private int getMaxPoolSize() {
return getConfig(MAX_POOL_SIZE);
}
private ResizeOperator getResizeOperator() {
return getConfig(RESIZE_OPERATOR);
}
private Function<Entity,Integer> getCurrentSizeOperator() {
return getConfig(CURRENT_SIZE_OPERATOR);
}
private BasicNotificationSensor<? extends Map> getPoolHotSensor() {
return getConfig(POOL_HOT_SENSOR);
}
private BasicNotificationSensor<? extends Map> getPoolColdSensor() {
return getConfig(POOL_COLD_SENSOR);
}
private BasicNotificationSensor<? extends Map> getPoolOkSensor() {
return getConfig(POOL_OK_SENSOR);
}
@Override
public void suspend() {
super.suspend();
// TODO unsubscribe from everything? And resubscribe on resume?
if (executor != null) executor.shutdownNow();
}
@Override
public void resume() {
super.resume();
executor = Executors.newSingleThreadScheduledExecutor(newThreadFactory());
}
@Override
public void setEntity(EntityLocal entity) {
if (configsInternal.getRawConfig(RESIZE_OPERATOR) == null) {
Preconditions.checkArgument(entity instanceof Resizable, "Provided entity must be an instance of Resizable, because no custom-resizer operator supplied");
}
super.setEntity(entity);
this.poolEntity = entity;
if (getMetric() != null) {
Entity entityToSubscribeTo = (getEntityWithMetric() != null) ? getEntityWithMetric() : entity;
subscribe(entityToSubscribeTo, getMetric(), metricEventHandler);
}
subscribe(poolEntity, getPoolColdSensor(), utilizationEventHandler);
subscribe(poolEntity, getPoolHotSensor(), utilizationEventHandler);
subscribe(poolEntity, getPoolOkSensor(), utilizationEventHandler);
}
private ThreadFactory newThreadFactory() {
return new ThreadFactoryBuilder()
.setNameFormat("brooklyn-autoscalerpolicy-%d")
.build();
}
private void onMetricChanged(Number val) {
if (LOG.isTraceEnabled()) LOG.trace("{} recording pool-metric for {}: {}", new Object[] {this, poolEntity, val});
double currentMetricD = val.doubleValue();
double metricUpperBoundD = getMetricUpperBound().doubleValue();
double metricLowerBoundD = getMetricLowerBound().doubleValue();
int currentSize = getCurrentSizeOperator().apply(entity);
double currentTotalActivity = currentSize * currentMetricD;
int desiredSize;
/* We always scale out (modulo stabilization delay) if:
* currentTotalActivity > currentSize*metricUpperBound
* With newDesiredSize the smallest n such that n*metricUpperBound >= currentTotalActivity
* ie n >= currentTotalActiviy/metricUpperBound, thus n := Math.ceil(currentTotalActivity/metricUpperBound)
*
* Else consider scale back if:
* currentTotalActivity < currentSize*metricLowerBound
* With newDesiredSize normally the largest n such that:
* n*metricLowerBound <= currentTotalActivity
* BUT with an absolute requirement which trumps the above computation
* that the newDesiredSize doesn't cause immediate scale out:
* n*metricUpperBound >= currentTotalActivity
* thus n := Math.max ( floor(currentTotalActiviy/metricLowerBound), ceil(currentTotal/metricUpperBound) )
*/
if (currentMetricD > metricUpperBoundD) {
// scale out
desiredSize = (int)Math.ceil(currentTotalActivity/metricUpperBoundD);
desiredSize = toBoundedDesiredPoolSize(desiredSize);
if (desiredSize > currentSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} resizing out pool {} from {} to {} ({} > {})", new Object[] {this, poolEntity, currentSize, desiredSize, currentMetricD, metricUpperBoundD});
scheduleResize(desiredSize);
} else {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} ({} > {} > {}, but scale-out blocked eg by bounds/check)", new Object[] {this, poolEntity, currentSize, currentMetricD, metricUpperBoundD, metricLowerBoundD});
}
} else if (currentMetricD < metricLowerBoundD) {
// scale back
desiredSize = (int)Math.floor(currentTotalActivity/metricLowerBoundD);
desiredSize = toBoundedDesiredPoolSize(desiredSize);
if (desiredSize < currentTotalActivity/metricUpperBoundD) {
// this desired size would cause scale-out on next run, ie thrashing, so tweak
if (LOG.isTraceEnabled()) LOG.trace("{} resizing back pool {} from {}, tweaking from {} to prevent thrashing", new Object[] {this, poolEntity, currentSize, desiredSize });
desiredSize = (int)Math.ceil(currentTotalActivity/metricUpperBoundD);
desiredSize = toBoundedDesiredPoolSize(desiredSize);
}
if (desiredSize < currentSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} resizing back pool {} from {} to {} ({} < {})", new Object[] {this, poolEntity, currentSize, desiredSize, currentMetricD, metricLowerBoundD});
scheduleResize(desiredSize);
} else {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} ({} < {} < {}, but scale-back blocked eg by bounds/check)", new Object[] {this, poolEntity, currentSize, currentMetricD, metricLowerBoundD, metricUpperBoundD});
}
} else {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} ({} within range {}..{})", new Object[] {this, poolEntity, currentSize, currentMetricD, metricLowerBoundD, metricUpperBoundD});
abortResize(currentSize);
return; // within a health range; no-op
}
}
private void onPoolCold(Map<String, ?> properties) {
if (LOG.isTraceEnabled()) LOG.trace("{} recording pool-cold for {}: {}", new Object[] {this, poolEntity, properties});
int poolCurrentSize = (Integer) properties.get(POOL_CURRENT_SIZE_KEY);
double poolCurrentWorkrate = (Double) properties.get(POOL_CURRENT_WORKRATE_KEY);
double poolLowThreshold = (Double) properties.get(POOL_LOW_THRESHOLD_KEY);
// Shrink the pool to force its low threshold to fall below the current workrate.
// NOTE: assumes the pool is homogeneous for now.
int desiredPoolSize = (int) Math.ceil(poolCurrentWorkrate / (poolLowThreshold/poolCurrentSize));
desiredPoolSize = toBoundedDesiredPoolSize(desiredPoolSize);
if (desiredPoolSize < poolCurrentSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} resizing cold pool {} from {} to {}", new Object[] {this, poolEntity, poolCurrentSize, desiredPoolSize});
scheduleResize(desiredPoolSize);
} else {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing cold pool {} from {} to {}", new Object[] {this, poolEntity, poolCurrentSize, desiredPoolSize});
abortResize(poolCurrentSize);
}
}
private void onPoolHot(Map<String, ?> properties) {
if (LOG.isTraceEnabled()) LOG.trace("{} recording pool-hot for {}: {}", new Object[] {this, poolEntity, properties});
int poolCurrentSize = (Integer) properties.get(POOL_CURRENT_SIZE_KEY);
double poolCurrentWorkrate = (Double) properties.get(POOL_CURRENT_WORKRATE_KEY);
double poolHighThreshold = (Double) properties.get(POOL_HIGH_THRESHOLD_KEY);
// Grow the pool to force its high threshold to rise above the current workrate.
// FIXME: assumes the pool is homogeneous for now.
int desiredPoolSize = (int) Math.ceil(poolCurrentWorkrate / (poolHighThreshold/poolCurrentSize));
desiredPoolSize = toBoundedDesiredPoolSize(desiredPoolSize);
if (desiredPoolSize > poolCurrentSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} resizing hot pool {} from {} to {}", new Object[] {this, poolEntity, poolCurrentSize, desiredPoolSize});
scheduleResize(desiredPoolSize);
} else {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing hot pool {} from {} to {}", new Object[] {this, poolEntity, poolCurrentSize, desiredPoolSize});
abortResize(poolCurrentSize);
}
}
private void onPoolOk(Map<String, ?> properties) {
if (LOG.isTraceEnabled()) LOG.trace("{} recording pool-ok for {}: {}", new Object[] {this, poolEntity, properties});
int poolCurrentSize = (Integer) properties.get(POOL_CURRENT_SIZE_KEY);
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing ok pool {} from {}", new Object[] {this, poolEntity, poolCurrentSize});
abortResize(poolCurrentSize);
}
private int toBoundedDesiredPoolSize(int size) {
int result = Math.max(getMinPoolSize(), size);
result = Math.min(getMaxPoolSize(), result);
return result;
}
/**
* Schedules a resize, if there is not already a resize operation queued up. When that resize
* executes, it will resize to whatever the latest value is to be (rather than what it was told
* to do at the point the job was queued).
*/
private void scheduleResize(final int newSize) {
recentDesiredResizes.add(newSize);
scheduleResize();
}
private void abortResize(final int currentSize) {
recentDesiredResizes.add(currentSize);
}
private boolean isEntityUp() {
if (entity == null) {
return false;
} else if (entity.getEntityType().getSensors().contains(Startable.SERVICE_UP)) {
return Boolean.TRUE.equals(entity.getAttribute(Startable.SERVICE_UP));
} else {
return true;
}
}
private void scheduleResize() {
// TODO perhaps make concurrent calls, rather than waiting for first resize to entirely
// finish? On ec2 for example, this can cause us to grow very slowly if first request is for
// just one new VM to be provisioned.
// Alex comments: yes, for scale out
- if (isRunning() && executorQueued.compareAndSet(false, true) && isEntityUp()) {
+ if (isRunning() && isEntityUp() && executorQueued.compareAndSet(false, true)) {
long now = System.currentTimeMillis();
long delay = Math.max(0, (executorTime + getMinPeriodBetweenExecs()) - now);
if (LOG.isTraceEnabled()) LOG.trace("{} scheduling resize in {}ms", this, delay);
executor.schedule(new Runnable() {
@Override public void run() {
try {
executorTime = System.currentTimeMillis();
executorQueued.set(false);
long currentPoolSize = getCurrentSizeOperator().apply(poolEntity);
CalculatedDesiredPoolSize calculatedDesiredPoolSize = calculateDesiredPoolSize(currentPoolSize);
long desiredPoolSize = calculatedDesiredPoolSize.size;
boolean stable = calculatedDesiredPoolSize.stable;
// TODO Alex says: I think we should change even if not stable ... worst case we'll shrink later
// otherwise if we're at 100 nodes and the num required keeps shifting from 10 to 11 to 8 to 13
// we'll always have 100 ... or worse if we have 10 and num required keeps shifting 100 to 101 to 98...
if (!stable) {
// the desired size fluctuations are not stable; ensure we check again later (due to time-window)
// even if no additional events have been received
if (LOG.isTraceEnabled()) LOG.trace("{} re-scheduling resize check, as desired size not stable; continuing with resize...",
new Object[] {this, poolEntity, currentPoolSize, desiredPoolSize});
scheduleResize();
}
if (currentPoolSize == desiredPoolSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} to {}",
new Object[] {this, poolEntity, currentPoolSize, desiredPoolSize});
return;
}
if (LOG.isDebugEnabled()) LOG.debug("{} requesting resize to {}; current {}, min {}, max {}",
new Object[] {this, desiredPoolSize, currentPoolSize, getMinPoolSize(), getMaxPoolSize()});
// TODO Should we use int throughout, rather than casting here?
getResizeOperator().resize(poolEntity, (int) desiredPoolSize);
} catch (Exception e) {
if (isRunning()) {
LOG.error("Error resizing: "+e, e);
} else {
if (LOG.isDebugEnabled()) LOG.debug("Error resizing, but no longer running: "+e, e);
}
} catch (Throwable t) {
LOG.error("Error resizing: "+t, t);
throw Throwables.propagate(t);
}
}},
delay,
TimeUnit.MILLISECONDS);
}
}
/**
* Complicated logic for stabilization-delay...
* Only grow if we have consistently been asked to grow for the resizeUpStabilizationDelay period;
* Only shrink if we have consistently been asked to shrink for the resizeDownStabilizationDelay period.
*
* @return tuple of desired pool size, and whether this is "stable" (i.e. if we receive no more events
* will this continue to be the desired pool size)
*/
private CalculatedDesiredPoolSize calculateDesiredPoolSize(long currentPoolSize) {
long now = System.currentTimeMillis();
List<TimestampedValue<Number>> downsizeWindowVals = recentDesiredResizes.getValuesInWindow(now, getResizeDownStabilizationDelay());
List<TimestampedValue<Number>> upsizeWindowVals = recentDesiredResizes.getValuesInWindow(now, getResizeUpStabilizationDelay());
// this is the largest size that has been requested in the "stable-for-shrinking" period:
long minDesiredPoolSize = maxInWindow(downsizeWindowVals, getResizeDownStabilizationDelay()).longValue();
// this is the smallest size that has been requested in the "stable-for-growing" period:
long maxDesiredPoolSize = minInWindow(upsizeWindowVals, getResizeUpStabilizationDelay()).longValue();
// (it is a logical consequence of the above that minDesired >= maxDesired -- this is correct, if confusing:
// think of minDesired as the minimum size we are allowed to resize to, and similarly for maxDesired;
// if min > max we can scale to max if current < max, or scale to min if current > min)
long desiredPoolSize;
boolean stableForShrinking = (minInWindow(downsizeWindowVals, getResizeDownStabilizationDelay()).equals(maxInWindow(downsizeWindowVals, getResizeDownStabilizationDelay())));
boolean stableForGrowing = (minInWindow(upsizeWindowVals, getResizeUpStabilizationDelay()).equals(maxInWindow(upsizeWindowVals, getResizeUpStabilizationDelay())));
boolean stable;
if (currentPoolSize < maxDesiredPoolSize) {
// we have valid request to grow
// (we'll never have a valid request to grow and a valid to shrink simultaneously, btw)
desiredPoolSize = maxDesiredPoolSize;
stable = stableForGrowing;
} else if (currentPoolSize > minDesiredPoolSize) {
// we have valid request to shrink
desiredPoolSize = minDesiredPoolSize;
stable = stableForShrinking;
} else {
desiredPoolSize = currentPoolSize;
stable = stableForGrowing && stableForShrinking;
}
if (LOG.isTraceEnabled()) LOG.trace("{} calculated desired pool size: from {} to {}; minDesired {}, maxDesired {}; " +
"stable {}; now {}; downsizeHistory {}; upsizeHistory {}",
new Object[] {this, currentPoolSize, desiredPoolSize, minDesiredPoolSize, maxDesiredPoolSize, stable, now, downsizeWindowVals, upsizeWindowVals});
return new CalculatedDesiredPoolSize(desiredPoolSize, stable);
}
private static class CalculatedDesiredPoolSize {
final long size;
final boolean stable;
CalculatedDesiredPoolSize(long size, boolean stable) {
this.size = size;
this.stable = stable;
}
}
/**
* If the entire time-window is not covered by the given values, then returns Integer.MAX_VALUE.
*/
private <T extends Number> T maxInWindow(List<TimestampedValue<T>> vals, long timewindow) {
// TODO bad casting from Integer default result to T
long now = System.currentTimeMillis();
long epoch = now-timewindow;
T result = null;
double resultAsDouble = Integer.MAX_VALUE;
for (TimestampedValue<T> val : vals) {
T valAsNum = val.getValue();
double valAsDouble = (valAsNum != null) ? valAsNum.doubleValue() : 0;
if (result == null && val.getTimestamp() > epoch) {
result = (T) Integer.valueOf(Integer.MAX_VALUE);
resultAsDouble = result.doubleValue();
}
if (result == null || (valAsNum != null && valAsDouble > resultAsDouble)) {
result = valAsNum;
resultAsDouble = valAsDouble;
}
}
return (T) (result != null ? result : Integer.MAX_VALUE);
}
/**
* If the entire time-window is not covered by the given values, then returns Integer.MIN_VALUE
*/
private <T extends Number> T minInWindow(List<TimestampedValue<T>> vals, long timewindow) {
long now = System.currentTimeMillis();
long epoch = now-timewindow;
T result = null;
double resultAsDouble = Integer.MIN_VALUE;
for (TimestampedValue<T> val : vals) {
T valAsNum = val.getValue();
double valAsDouble = (valAsNum != null) ? valAsNum.doubleValue() : 0;
if (result == null && val.getTimestamp() > epoch) {
result = (T) Integer.valueOf(Integer.MIN_VALUE);
resultAsDouble = result.doubleValue();
}
if (result == null || (val.getValue() != null && valAsDouble < resultAsDouble)) {
result = valAsNum;
resultAsDouble = valAsDouble;
}
}
return (T) (result != null ? result : Integer.MIN_VALUE);
}
@Override
public String toString() {
return getClass().getSimpleName() + (truth(name) ? "("+name+")" : "");
}
}
| true | true | private void scheduleResize() {
// TODO perhaps make concurrent calls, rather than waiting for first resize to entirely
// finish? On ec2 for example, this can cause us to grow very slowly if first request is for
// just one new VM to be provisioned.
// Alex comments: yes, for scale out
if (isRunning() && executorQueued.compareAndSet(false, true) && isEntityUp()) {
long now = System.currentTimeMillis();
long delay = Math.max(0, (executorTime + getMinPeriodBetweenExecs()) - now);
if (LOG.isTraceEnabled()) LOG.trace("{} scheduling resize in {}ms", this, delay);
executor.schedule(new Runnable() {
@Override public void run() {
try {
executorTime = System.currentTimeMillis();
executorQueued.set(false);
long currentPoolSize = getCurrentSizeOperator().apply(poolEntity);
CalculatedDesiredPoolSize calculatedDesiredPoolSize = calculateDesiredPoolSize(currentPoolSize);
long desiredPoolSize = calculatedDesiredPoolSize.size;
boolean stable = calculatedDesiredPoolSize.stable;
// TODO Alex says: I think we should change even if not stable ... worst case we'll shrink later
// otherwise if we're at 100 nodes and the num required keeps shifting from 10 to 11 to 8 to 13
// we'll always have 100 ... or worse if we have 10 and num required keeps shifting 100 to 101 to 98...
if (!stable) {
// the desired size fluctuations are not stable; ensure we check again later (due to time-window)
// even if no additional events have been received
if (LOG.isTraceEnabled()) LOG.trace("{} re-scheduling resize check, as desired size not stable; continuing with resize...",
new Object[] {this, poolEntity, currentPoolSize, desiredPoolSize});
scheduleResize();
}
if (currentPoolSize == desiredPoolSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} to {}",
new Object[] {this, poolEntity, currentPoolSize, desiredPoolSize});
return;
}
if (LOG.isDebugEnabled()) LOG.debug("{} requesting resize to {}; current {}, min {}, max {}",
new Object[] {this, desiredPoolSize, currentPoolSize, getMinPoolSize(), getMaxPoolSize()});
// TODO Should we use int throughout, rather than casting here?
getResizeOperator().resize(poolEntity, (int) desiredPoolSize);
} catch (Exception e) {
if (isRunning()) {
LOG.error("Error resizing: "+e, e);
} else {
if (LOG.isDebugEnabled()) LOG.debug("Error resizing, but no longer running: "+e, e);
}
} catch (Throwable t) {
LOG.error("Error resizing: "+t, t);
throw Throwables.propagate(t);
}
}},
delay,
TimeUnit.MILLISECONDS);
}
}
| private void scheduleResize() {
// TODO perhaps make concurrent calls, rather than waiting for first resize to entirely
// finish? On ec2 for example, this can cause us to grow very slowly if first request is for
// just one new VM to be provisioned.
// Alex comments: yes, for scale out
if (isRunning() && isEntityUp() && executorQueued.compareAndSet(false, true)) {
long now = System.currentTimeMillis();
long delay = Math.max(0, (executorTime + getMinPeriodBetweenExecs()) - now);
if (LOG.isTraceEnabled()) LOG.trace("{} scheduling resize in {}ms", this, delay);
executor.schedule(new Runnable() {
@Override public void run() {
try {
executorTime = System.currentTimeMillis();
executorQueued.set(false);
long currentPoolSize = getCurrentSizeOperator().apply(poolEntity);
CalculatedDesiredPoolSize calculatedDesiredPoolSize = calculateDesiredPoolSize(currentPoolSize);
long desiredPoolSize = calculatedDesiredPoolSize.size;
boolean stable = calculatedDesiredPoolSize.stable;
// TODO Alex says: I think we should change even if not stable ... worst case we'll shrink later
// otherwise if we're at 100 nodes and the num required keeps shifting from 10 to 11 to 8 to 13
// we'll always have 100 ... or worse if we have 10 and num required keeps shifting 100 to 101 to 98...
if (!stable) {
// the desired size fluctuations are not stable; ensure we check again later (due to time-window)
// even if no additional events have been received
if (LOG.isTraceEnabled()) LOG.trace("{} re-scheduling resize check, as desired size not stable; continuing with resize...",
new Object[] {this, poolEntity, currentPoolSize, desiredPoolSize});
scheduleResize();
}
if (currentPoolSize == desiredPoolSize) {
if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} to {}",
new Object[] {this, poolEntity, currentPoolSize, desiredPoolSize});
return;
}
if (LOG.isDebugEnabled()) LOG.debug("{} requesting resize to {}; current {}, min {}, max {}",
new Object[] {this, desiredPoolSize, currentPoolSize, getMinPoolSize(), getMaxPoolSize()});
// TODO Should we use int throughout, rather than casting here?
getResizeOperator().resize(poolEntity, (int) desiredPoolSize);
} catch (Exception e) {
if (isRunning()) {
LOG.error("Error resizing: "+e, e);
} else {
if (LOG.isDebugEnabled()) LOG.debug("Error resizing, but no longer running: "+e, e);
}
} catch (Throwable t) {
LOG.error("Error resizing: "+t, t);
throw Throwables.propagate(t);
}
}},
delay,
TimeUnit.MILLISECONDS);
}
}
|
diff --git a/extensions/robospice-ormlite-content-provider-parent/robospice-ormlite-content-provider/src/main/java/com/octo/android/robospice/persistence/ormlite/RoboSpiceContentProvider.java b/extensions/robospice-ormlite-content-provider-parent/robospice-ormlite-content-provider/src/main/java/com/octo/android/robospice/persistence/ormlite/RoboSpiceContentProvider.java
index 65fbf3e5c..dc3411c45 100644
--- a/extensions/robospice-ormlite-content-provider-parent/robospice-ormlite-content-provider/src/main/java/com/octo/android/robospice/persistence/ormlite/RoboSpiceContentProvider.java
+++ b/extensions/robospice-ormlite-content-provider-parent/robospice-ormlite-content-provider/src/main/java/com/octo/android/robospice/persistence/ormlite/RoboSpiceContentProvider.java
@@ -1,51 +1,51 @@
package com.octo.android.robospice.persistence.ormlite;
import java.util.List;
import roboguice.util.temp.Ln;
import android.app.Application;
import com.tojc.ormlite.android.OrmLiteSimpleContentProvider;
import com.tojc.ormlite.android.annotation.AdditionalAnnotation.Contract;
import com.tojc.ormlite.android.framework.MatcherController;
import com.tojc.ormlite.android.framework.MimeTypeVnd.SubType;
public abstract class RoboSpiceContentProvider extends OrmLiteSimpleContentProvider<RoboSpiceDatabaseHelper> {
@Override
protected Class<RoboSpiceDatabaseHelper> getHelperClass() {
return RoboSpiceDatabaseHelper.class;
}
@Override
public RoboSpiceDatabaseHelper getHelper() {
return new RoboSpiceDatabaseHelper((Application) getContext().getApplicationContext(), getDatabaseName(), getDatabaseVersion());
}
@Override
public boolean onCreate() {
MatcherController controller = new MatcherController();
for (Class<?> clazz : getExposedClasses()) {
try {
if (!clazz.isAnnotationPresent(Contract.class)) {
throw new Exception("Class " + clazz + " is not annotated with the @Contract annotation.");
}
Class<?> contractClazz = ContractHelper.getContractClassForClass(clazz);
int contentUriPatternMany = ContractHelper.getContentUriPatternMany(contractClazz);
int contentUriPatternOne = ContractHelper.getContentUriPatternOne(contractClazz);
controller.add(clazz, SubType.DIRECTORY, "", contentUriPatternMany);
- controller.add(clazz, SubType.DIRECTORY, "#", contentUriPatternOne);
+ controller.add(clazz, SubType.ITEM, "#", contentUriPatternOne);
} catch (Exception e) {
Ln.e(e);
}
}
setMatcherController(controller);
return true;
}
public abstract List<Class<?>> getExposedClasses();
public abstract String getDatabaseName();
public abstract int getDatabaseVersion();
}
| true | true | public boolean onCreate() {
MatcherController controller = new MatcherController();
for (Class<?> clazz : getExposedClasses()) {
try {
if (!clazz.isAnnotationPresent(Contract.class)) {
throw new Exception("Class " + clazz + " is not annotated with the @Contract annotation.");
}
Class<?> contractClazz = ContractHelper.getContractClassForClass(clazz);
int contentUriPatternMany = ContractHelper.getContentUriPatternMany(contractClazz);
int contentUriPatternOne = ContractHelper.getContentUriPatternOne(contractClazz);
controller.add(clazz, SubType.DIRECTORY, "", contentUriPatternMany);
controller.add(clazz, SubType.DIRECTORY, "#", contentUriPatternOne);
} catch (Exception e) {
Ln.e(e);
}
}
setMatcherController(controller);
return true;
}
| public boolean onCreate() {
MatcherController controller = new MatcherController();
for (Class<?> clazz : getExposedClasses()) {
try {
if (!clazz.isAnnotationPresent(Contract.class)) {
throw new Exception("Class " + clazz + " is not annotated with the @Contract annotation.");
}
Class<?> contractClazz = ContractHelper.getContractClassForClass(clazz);
int contentUriPatternMany = ContractHelper.getContentUriPatternMany(contractClazz);
int contentUriPatternOne = ContractHelper.getContentUriPatternOne(contractClazz);
controller.add(clazz, SubType.DIRECTORY, "", contentUriPatternMany);
controller.add(clazz, SubType.ITEM, "#", contentUriPatternOne);
} catch (Exception e) {
Ln.e(e);
}
}
setMatcherController(controller);
return true;
}
|
diff --git a/src/main/java/org/codehaus/larex/io/CachedByteBuffers.java b/src/main/java/org/codehaus/larex/io/CachedByteBuffers.java
index 61ad3fb..436d052 100644
--- a/src/main/java/org/codehaus/larex/io/CachedByteBuffers.java
+++ b/src/main/java/org/codehaus/larex/io/CachedByteBuffers.java
@@ -1,89 +1,91 @@
/*
* Copyright (c) 2010-2010 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.larex.io;
import java.nio.ByteBuffer;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
/**
* <p>Implementation of {@link ByteBuffers} that caches and reuses buffers.</p>
* <p>Buffers will be created in capacity steps controlled by a factor, to avoid
* that a new buffer is created for each different capacity.<br />
* Therefore, if the factor is 1024 (the default) and a request for size 2500 arrives,
* then a buffer of capacity 3072 (1024 * 3) is created and returned.
* If, later on, a request for size 3000 arrives, the same buffer is returned.</p>
*
* @version $Revision$ $Date$
*/
public class CachedByteBuffers implements ByteBuffers
{
private final ConcurrentMap<Integer, Queue<ByteBuffer>> directBuffers = new ConcurrentHashMap<Integer, Queue<ByteBuffer>>();
private final ConcurrentMap<Integer, Queue<ByteBuffer>> heapBuffers = new ConcurrentHashMap<Integer, Queue<ByteBuffer>>();
private final int factor;
public CachedByteBuffers()
{
this(1024);
}
public CachedByteBuffers(int factor)
{
this.factor = factor;
}
public ByteBuffer acquire(int size, boolean direct)
{
int bucket = size / factor;
+ if (size % factor > 0)
+ ++bucket;
ConcurrentMap<Integer, Queue<ByteBuffer>> buffers = direct ? directBuffers : heapBuffers;
// Avoid to create a new queue every time, just to be discarded immediately
Queue<ByteBuffer> byteBuffers = buffers.get(bucket);
if (byteBuffers == null)
{
byteBuffers = new ConcurrentLinkedQueue<ByteBuffer>();
Queue<ByteBuffer> existing = buffers.putIfAbsent(bucket, byteBuffers);
if (existing != null)
byteBuffers = existing;
}
ByteBuffer result = byteBuffers.poll();
while (result == null)
{
int capacity = (bucket + 1) * factor;
result = direct ? ByteBuffer.allocateDirect(capacity) : ByteBuffer.allocate(capacity);
byteBuffers.offer(result);
result = byteBuffers.poll();
}
result.clear();
result.limit(size);
return result;
}
public void release(ByteBuffer buffer)
{
int bucket = buffer.capacity() / factor;
ConcurrentMap<Integer, Queue<ByteBuffer>> buffers = buffer.isDirect() ? directBuffers : heapBuffers;
Queue<ByteBuffer> byteBuffers = buffers.get(bucket);
if (byteBuffers != null)
byteBuffers.offer(buffer);
}
}
| true | true | public ByteBuffer acquire(int size, boolean direct)
{
int bucket = size / factor;
ConcurrentMap<Integer, Queue<ByteBuffer>> buffers = direct ? directBuffers : heapBuffers;
// Avoid to create a new queue every time, just to be discarded immediately
Queue<ByteBuffer> byteBuffers = buffers.get(bucket);
if (byteBuffers == null)
{
byteBuffers = new ConcurrentLinkedQueue<ByteBuffer>();
Queue<ByteBuffer> existing = buffers.putIfAbsent(bucket, byteBuffers);
if (existing != null)
byteBuffers = existing;
}
ByteBuffer result = byteBuffers.poll();
while (result == null)
{
int capacity = (bucket + 1) * factor;
result = direct ? ByteBuffer.allocateDirect(capacity) : ByteBuffer.allocate(capacity);
byteBuffers.offer(result);
result = byteBuffers.poll();
}
result.clear();
result.limit(size);
return result;
}
| public ByteBuffer acquire(int size, boolean direct)
{
int bucket = size / factor;
if (size % factor > 0)
++bucket;
ConcurrentMap<Integer, Queue<ByteBuffer>> buffers = direct ? directBuffers : heapBuffers;
// Avoid to create a new queue every time, just to be discarded immediately
Queue<ByteBuffer> byteBuffers = buffers.get(bucket);
if (byteBuffers == null)
{
byteBuffers = new ConcurrentLinkedQueue<ByteBuffer>();
Queue<ByteBuffer> existing = buffers.putIfAbsent(bucket, byteBuffers);
if (existing != null)
byteBuffers = existing;
}
ByteBuffer result = byteBuffers.poll();
while (result == null)
{
int capacity = (bucket + 1) * factor;
result = direct ? ByteBuffer.allocateDirect(capacity) : ByteBuffer.allocate(capacity);
byteBuffers.offer(result);
result = byteBuffers.poll();
}
result.clear();
result.limit(size);
return result;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.