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/Experimental/src/package_APLessons_TrialOne/ReadWriteTwo.java b/Experimental/src/package_APLessons_TrialOne/ReadWriteTwo.java
index 1dd4f8f..720c71e 100644
--- a/Experimental/src/package_APLessons_TrialOne/ReadWriteTwo.java
+++ b/Experimental/src/package_APLessons_TrialOne/ReadWriteTwo.java
@@ -1,166 +1,168 @@
/*
* Uses:
* Method Call
* Returns
*/
package package_APLessons_TrialOne;
import java.util.Scanner;
public class ReadWriteTwo {
public static void main(String[] args) {
//initialization
System.out.println("This program was written by James Daniel");
System.out.println();
String varOne;
System.out.print("Enter your name: ");
Scanner readStuff = new Scanner(System.in);
varOne = readStuff.nextLine();
System.out.println();
for (int foo = 0; foo < 4; ++foo) //ints
{
//section 1 of loop
int firstNum, secondNum, sum, differ, mult, qot, remain;
System.out.println();
System.out.println("Trial " + (foo+1) + " integers: ");
System.out.print("Please enter your first number: ");
firstNum = readStuff.nextInt();
System.out.print("Please enter your second number: ");
secondNum = readStuff.nextInt();
sum = summation(firstNum, secondNum);
differ = difference(firstNum, secondNum);
mult = multiplex(firstNum, secondNum);
System.out.println("The sum of " + firstNum + " and " + secondNum + " is " + sum);
System.out.println("The difference of " + firstNum + " and " + secondNum + " is " + differ);
System.out.println("The product of " + firstNum + " and " + secondNum + " is " + mult);
@SuppressWarnings("unused")
boolean dba = divisible(secondNum);
if (dba = false)
System.out.println("The quotient of " + firstNum + " and " + secondNum + " cannot be resolved. | (ERR: DIV/0)");
else
{
qot = division(firstNum, secondNum);
remain = modulus(firstNum, secondNum);
System.out.println("The quotient of " + firstNum + " and " + secondNum + " is " + qot + "r" + remain);
}
System.out.println();
//section 2 of loop
double firstNumd, secondNumd, sumd, differd, multd, qotd; //doubles
System.out.println();
System.out.println("Trial " + (foo+1) + " doubles: ");
System.out.print("Please enter your first number: ");
firstNumd = readStuff.nextDouble();
System.out.print("Please enter your second number: ");
secondNumd = readStuff.nextDouble();
sumd = summationDb(firstNumd, secondNumd);
differd = differenceDb(firstNumd, secondNumd);
multd = multiplexDb(firstNumd, secondNumd);
System.out.println("The sum of " + firstNumd + " and " + secondNumd + " is " + sumd);
System.out.println("The difference of " + firstNumd + " and " + secondNumd + " is " + differd);
System.out.println("The product of " + firstNumd + " and " + secondNumd + " is " + multd);
- if (secondNum == 0)
+ @SuppressWarnings("unused")
+ boolean dbaDb = divisibleDb(secondNumd);
+ if (dbaDb = false)
System.out.println("The quotient of " + firstNumd + " and " + secondNumd + " cannot be resolved. | (ERR: DIV/0)");
else
{
qotd = divisionDb(firstNumd, secondNumd);
System.out.println("The quotient of " + firstNumd + " and " + secondNumd + " is " + qotd);
}
System.out.println();
}
System.out.println("# # # # # # # # # # # # # # # # # # # #");
System.out.println("This program was run by " + varOne);
System.out.println("# # # # # # # # # # # # # # # # # # # #");
readStuff.close();
}
///////////////////////////////////////////// subroutines start here
public static int summation (int a, int b) {
int foo = a + b;
return foo;
}
public static int difference (int a, int b) {
int foo = a - b;
return foo;
}
public static int multiplex (int a, int b) {
int foo = a * b;
return foo;
}
public static boolean divisible (int a) {
if (a == 0)
return false;
else return true;
}
public static int division (int a, int b) {
int foo = a / b;
return foo;
}
public static int modulus (int a, int b) {
int foo = a % b;
return foo;
}
//////////////////////////////////////////////////
public static double summationDb (double a, double b) {
double foo = a + b;
return foo;
}
public static double differenceDb (double a, double b) {
double foo = a - b;
return foo;
}
public static double multiplexDb (double a, double b) {
double foo = a * b;
return foo;
}
public static boolean divisibleDb (double a) {
if (a == 0.0)
return false;
else return true;
}
public static double divisionDb (double a, double b) {
double foo = a / b;
return foo;
}
}
| true | true | public static void main(String[] args) {
//initialization
System.out.println("This program was written by James Daniel");
System.out.println();
String varOne;
System.out.print("Enter your name: ");
Scanner readStuff = new Scanner(System.in);
varOne = readStuff.nextLine();
System.out.println();
for (int foo = 0; foo < 4; ++foo) //ints
{
//section 1 of loop
int firstNum, secondNum, sum, differ, mult, qot, remain;
System.out.println();
System.out.println("Trial " + (foo+1) + " integers: ");
System.out.print("Please enter your first number: ");
firstNum = readStuff.nextInt();
System.out.print("Please enter your second number: ");
secondNum = readStuff.nextInt();
sum = summation(firstNum, secondNum);
differ = difference(firstNum, secondNum);
mult = multiplex(firstNum, secondNum);
System.out.println("The sum of " + firstNum + " and " + secondNum + " is " + sum);
System.out.println("The difference of " + firstNum + " and " + secondNum + " is " + differ);
System.out.println("The product of " + firstNum + " and " + secondNum + " is " + mult);
@SuppressWarnings("unused")
boolean dba = divisible(secondNum);
if (dba = false)
System.out.println("The quotient of " + firstNum + " and " + secondNum + " cannot be resolved. | (ERR: DIV/0)");
else
{
qot = division(firstNum, secondNum);
remain = modulus(firstNum, secondNum);
System.out.println("The quotient of " + firstNum + " and " + secondNum + " is " + qot + "r" + remain);
}
System.out.println();
//section 2 of loop
double firstNumd, secondNumd, sumd, differd, multd, qotd; //doubles
System.out.println();
System.out.println("Trial " + (foo+1) + " doubles: ");
System.out.print("Please enter your first number: ");
firstNumd = readStuff.nextDouble();
System.out.print("Please enter your second number: ");
secondNumd = readStuff.nextDouble();
sumd = summationDb(firstNumd, secondNumd);
differd = differenceDb(firstNumd, secondNumd);
multd = multiplexDb(firstNumd, secondNumd);
System.out.println("The sum of " + firstNumd + " and " + secondNumd + " is " + sumd);
System.out.println("The difference of " + firstNumd + " and " + secondNumd + " is " + differd);
System.out.println("The product of " + firstNumd + " and " + secondNumd + " is " + multd);
if (secondNum == 0)
System.out.println("The quotient of " + firstNumd + " and " + secondNumd + " cannot be resolved. | (ERR: DIV/0)");
else
{
qotd = divisionDb(firstNumd, secondNumd);
System.out.println("The quotient of " + firstNumd + " and " + secondNumd + " is " + qotd);
}
System.out.println();
}
System.out.println("# # # # # # # # # # # # # # # # # # # #");
System.out.println("This program was run by " + varOne);
System.out.println("# # # # # # # # # # # # # # # # # # # #");
readStuff.close();
}
| public static void main(String[] args) {
//initialization
System.out.println("This program was written by James Daniel");
System.out.println();
String varOne;
System.out.print("Enter your name: ");
Scanner readStuff = new Scanner(System.in);
varOne = readStuff.nextLine();
System.out.println();
for (int foo = 0; foo < 4; ++foo) //ints
{
//section 1 of loop
int firstNum, secondNum, sum, differ, mult, qot, remain;
System.out.println();
System.out.println("Trial " + (foo+1) + " integers: ");
System.out.print("Please enter your first number: ");
firstNum = readStuff.nextInt();
System.out.print("Please enter your second number: ");
secondNum = readStuff.nextInt();
sum = summation(firstNum, secondNum);
differ = difference(firstNum, secondNum);
mult = multiplex(firstNum, secondNum);
System.out.println("The sum of " + firstNum + " and " + secondNum + " is " + sum);
System.out.println("The difference of " + firstNum + " and " + secondNum + " is " + differ);
System.out.println("The product of " + firstNum + " and " + secondNum + " is " + mult);
@SuppressWarnings("unused")
boolean dba = divisible(secondNum);
if (dba = false)
System.out.println("The quotient of " + firstNum + " and " + secondNum + " cannot be resolved. | (ERR: DIV/0)");
else
{
qot = division(firstNum, secondNum);
remain = modulus(firstNum, secondNum);
System.out.println("The quotient of " + firstNum + " and " + secondNum + " is " + qot + "r" + remain);
}
System.out.println();
//section 2 of loop
double firstNumd, secondNumd, sumd, differd, multd, qotd; //doubles
System.out.println();
System.out.println("Trial " + (foo+1) + " doubles: ");
System.out.print("Please enter your first number: ");
firstNumd = readStuff.nextDouble();
System.out.print("Please enter your second number: ");
secondNumd = readStuff.nextDouble();
sumd = summationDb(firstNumd, secondNumd);
differd = differenceDb(firstNumd, secondNumd);
multd = multiplexDb(firstNumd, secondNumd);
System.out.println("The sum of " + firstNumd + " and " + secondNumd + " is " + sumd);
System.out.println("The difference of " + firstNumd + " and " + secondNumd + " is " + differd);
System.out.println("The product of " + firstNumd + " and " + secondNumd + " is " + multd);
@SuppressWarnings("unused")
boolean dbaDb = divisibleDb(secondNumd);
if (dbaDb = false)
System.out.println("The quotient of " + firstNumd + " and " + secondNumd + " cannot be resolved. | (ERR: DIV/0)");
else
{
qotd = divisionDb(firstNumd, secondNumd);
System.out.println("The quotient of " + firstNumd + " and " + secondNumd + " is " + qotd);
}
System.out.println();
}
System.out.println("# # # # # # # # # # # # # # # # # # # #");
System.out.println("This program was run by " + varOne);
System.out.println("# # # # # # # # # # # # # # # # # # # #");
readStuff.close();
}
|
diff --git a/direWolfInABottle/client/ItemRenderDWIAB.java b/direWolfInABottle/client/ItemRenderDWIAB.java
index 535bd5e..26f7966 100644
--- a/direWolfInABottle/client/ItemRenderDWIAB.java
+++ b/direWolfInABottle/client/ItemRenderDWIAB.java
@@ -1,70 +1,70 @@
package jcj94.direWolfInABottle.client;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.Sphere;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.*;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.IItemRenderer;
public class ItemRenderDWIAB implements IItemRenderer
{
public ItemRenderDWIAB()
{
}
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type)
{
switch(type)
{
case EQUIPPED: return true;
default: return false;
}
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper)
{
return false;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
switch(type)
{
case EQUIPPED:
{
- Minecraft.getMinecraft().renderEngine.bindTexture("/dwiab/DWIAB.png");
+ Minecraft.getMinecraft().renderEngine.bindTexture("/jcj94/direWolfInABottle/model/DWIAB.png");
if(!((EntityPlayer)data[1] == Minecraft.getMinecraft().renderViewEntity && Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 && !((Minecraft.getMinecraft().currentScreen instanceof GuiInventory || Minecraft.getMinecraft().currentScreen instanceof GuiContainerCreative) && RenderManager.instance.playerViewY == 180.0F)))
{
GL11.glPushMatrix();
GL11.glRotatef(90, 1.00F, 0.00F, 0.00F);
GL11.glRotatef(130, 0.00F, 1.00F, 0.00F);
GL11.glRotatef(90, 0.00F, 0.00F, 1.00F);
- float scale = 0.50F;
+ float scale = 1.00F;
GL11.glScalef(scale, scale, scale);
GL11.glTranslatef(-0.025F, 0.05F, 0.70F);
GL11.glPopMatrix();
}
}
default:
break;
}
}
}
| false | true | public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
switch(type)
{
case EQUIPPED:
{
Minecraft.getMinecraft().renderEngine.bindTexture("/dwiab/DWIAB.png");
if(!((EntityPlayer)data[1] == Minecraft.getMinecraft().renderViewEntity && Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 && !((Minecraft.getMinecraft().currentScreen instanceof GuiInventory || Minecraft.getMinecraft().currentScreen instanceof GuiContainerCreative) && RenderManager.instance.playerViewY == 180.0F)))
{
GL11.glPushMatrix();
GL11.glRotatef(90, 1.00F, 0.00F, 0.00F);
GL11.glRotatef(130, 0.00F, 1.00F, 0.00F);
GL11.glRotatef(90, 0.00F, 0.00F, 1.00F);
float scale = 0.50F;
GL11.glScalef(scale, scale, scale);
GL11.glTranslatef(-0.025F, 0.05F, 0.70F);
GL11.glPopMatrix();
}
}
default:
break;
}
}
| public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
switch(type)
{
case EQUIPPED:
{
Minecraft.getMinecraft().renderEngine.bindTexture("/jcj94/direWolfInABottle/model/DWIAB.png");
if(!((EntityPlayer)data[1] == Minecraft.getMinecraft().renderViewEntity && Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 && !((Minecraft.getMinecraft().currentScreen instanceof GuiInventory || Minecraft.getMinecraft().currentScreen instanceof GuiContainerCreative) && RenderManager.instance.playerViewY == 180.0F)))
{
GL11.glPushMatrix();
GL11.glRotatef(90, 1.00F, 0.00F, 0.00F);
GL11.glRotatef(130, 0.00F, 1.00F, 0.00F);
GL11.glRotatef(90, 0.00F, 0.00F, 1.00F);
float scale = 1.00F;
GL11.glScalef(scale, scale, scale);
GL11.glTranslatef(-0.025F, 0.05F, 0.70F);
GL11.glPopMatrix();
}
}
default:
break;
}
}
|
diff --git a/test/com/google/inject/internal/LineNumbersTest.java b/test/com/google/inject/internal/LineNumbersTest.java
index f35d46e3..dfed5394 100644
--- a/test/com/google/inject/internal/LineNumbersTest.java
+++ b/test/com/google/inject/internal/LineNumbersTest.java
@@ -1,62 +1,62 @@
/**
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import com.google.inject.AbstractModule;
import static com.google.inject.Asserts.assertContains;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.matcher.Matchers;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* @author [email protected] (Jesse Wilson)
*/
public class LineNumbersTest extends TestCase {
public void testCanHandleLineNumbersForGuiceGeneratedClasses() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {
bindInterceptor(Matchers.only(A.class), Matchers.any(),
new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) {
return null;
}
});
bind(A.class);
}
});
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(),
- "Error at " + A.class.getName() + "<init>(LineNumbersTest:",
+ "Error at " + A.class.getName() + ".<init>(LineNumbersTest.java",
"No implementation for " + B.class.getName() + " was bound.");
}
}
static class A {
@Inject A(B b) {}
}
interface B {}
}
| true | true | public void testCanHandleLineNumbersForGuiceGeneratedClasses() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {
bindInterceptor(Matchers.only(A.class), Matchers.any(),
new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) {
return null;
}
});
bind(A.class);
}
});
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(),
"Error at " + A.class.getName() + "<init>(LineNumbersTest:",
"No implementation for " + B.class.getName() + " was bound.");
}
}
| public void testCanHandleLineNumbersForGuiceGeneratedClasses() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {
bindInterceptor(Matchers.only(A.class), Matchers.any(),
new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) {
return null;
}
});
bind(A.class);
}
});
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(),
"Error at " + A.class.getName() + ".<init>(LineNumbersTest.java",
"No implementation for " + B.class.getName() + " was bound.");
}
}
|
diff --git a/src/com/anysoftkeyboard/ui/settings/AddOnListPreference.java b/src/com/anysoftkeyboard/ui/settings/AddOnListPreference.java
index 52b940f7..72aafeae 100644
--- a/src/com/anysoftkeyboard/ui/settings/AddOnListPreference.java
+++ b/src/com/anysoftkeyboard/ui/settings/AddOnListPreference.java
@@ -1,264 +1,263 @@
/*
* Copyright (c) 2013 Menny Even-Danan
*
* 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.anysoftkeyboard.ui.settings;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import com.anysoftkeyboard.addons.AddOn;
import com.anysoftkeyboard.addons.AddOnsFactory;
import com.anysoftkeyboard.addons.IconHolder;
import com.anysoftkeyboard.addons.ScreenshotHolder;
import com.menny.android.anysoftkeyboard.R;
public class AddOnListPreference extends ListPreferenceEx {
private AddOn[] mAddOns;
private AddOn mSelectedAddOn;
public AddOnListPreference(Context context) {
super(context);
}
public AddOnListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
if (mAddOns != null) {
// mAddOns is null happens when activity gets recreated, e.g. on
// rotating the device.
ListAdapter listAdapter = new AddOnArrayAdapter(getContext().getApplicationContext(),
R.layout.addon_list_item_pref, mAddOns);
builder.setAdapter(listAdapter, this);
}
super.onPrepareDialogBuilder(builder);
}
public void setAddOnsList(AddOn[] addOns) {
mAddOns = addOns;
String[] ids = new String[mAddOns.length];
String[] names = new String[mAddOns.length];
int entryPos = 0;
for (AddOn addOn : mAddOns) {
ids[entryPos] = addOn.getId();
names[entryPos] = addOn.getName();
entryPos++;
}
setEntries(names);
setEntryValues(ids);
}
private class AddOnArrayAdapter extends ArrayAdapter<AddOn> implements
OnClickListener {
public AddOnArrayAdapter(Context context, int textViewResourceId,
AddOn[] objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final AddOn addOn = getItem(position);
// inflate layout
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View row = inflator.inflate(R.layout.addon_list_item_pref, parent,
false);
row.setTag(addOn);
// set on click listener for row
row.setOnClickListener(this);
// set addon details
TextView title = (TextView) row.findViewById(R.id.addon_title);
title.setText(addOn.getName());
TextView description = (TextView) row
.findViewById(R.id.addon_description);
description.setText(addOn.getDescription());
Drawable icon = null;
if (addOn instanceof IconHolder) {
IconHolder iconHolder = (IconHolder) addOn;
icon = iconHolder.getIcon();
}
if (icon == null) {
try {
PackageManager packageManager = getContext()
.getPackageManager();
- PackageInfo packageInfo = packageManager.getPackageInfo(
- addOn.getPackageContext().getPackageName(), 0);
+ PackageInfo packageInfo = packageManager.getPackageInfo(addOn.getPackageName(), 0);
icon = packageInfo.applicationInfo.loadIcon(packageManager);
} catch (PackageManager.NameNotFoundException e) {
icon = null;
}
}
ImageView addOnIcon = (ImageView) row
.findViewById(R.id.addon_image);
addOnIcon.setImageDrawable(icon);
if (addOn instanceof ScreenshotHolder) {
if (((ScreenshotHolder) addOn).hasScreenshot()) {
addOnIcon.setOnClickListener(this);
addOnIcon.setTag(addOn);
row.findViewById(R.id.addon_image_more_overlay)
.setVisibility(View.VISIBLE);
}
}
// set checkbox
RadioButton tb = (RadioButton) row
.findViewById(R.id.addon_checkbox);
tb.setClickable(false);
tb.setChecked(addOn.getId() == mSelectedAddOn.getId());
return row;
}
public void onClick(View v) {
if (v.getId() == R.id.addon_list_item_layout) {
setSelectedAddOn((AddOn) v.getTag());
AddOnListPreference.this.setValue(mSelectedAddOn.getId());
Dialog dialog = getDialog();
if (dialog != null)
dialog.dismiss();// it is null if the dialog is not shown.
} else if (v.getId() == R.id.addon_image) {
// showing a screenshot (if available)
AddOn addOn = (AddOn) v.getTag();
Drawable screenshot = null;
if (addOn instanceof ScreenshotHolder) {
ScreenshotHolder holder = (ScreenshotHolder) addOn;
screenshot = holder.getScreenshot();
}
if (screenshot == null) {
screenshot = ((ImageView) v).getDrawable();
}
//
if (screenshot == null)
return;
// inflating the screenshot view
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
ViewGroup layout = (ViewGroup) inflator.inflate(
R.layout.addon_screenshot, null);
final PopupWindow popup = new PopupWindow(getContext());
popup.setContentView(layout);
DisplayMetrics dm = getContext().getResources()
.getDisplayMetrics();
popup.setWidth(dm.widthPixels);
popup.setHeight(dm.heightPixels);
popup.setAnimationStyle(R.style.ScreenshotAnimation);
layout.findViewById(R.id.addon_screenshot_close)
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
popup.dismiss();
}
});
((ImageView) layout.findViewById(R.id.addon_screenshot))
.setImageDrawable(screenshot);
popup.showAtLocation(v, Gravity.CENTER, 0, 0);
}
}
}
public void setSelectedAddOn(AddOn currentSelectedAddOn) {
mSelectedAddOn = currentSelectedAddOn;
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superP = super.onSaveInstanceState();
AddOnsListSavedState myState = new AddOnsListSavedState(superP);
myState.selectedAddOnId = mSelectedAddOn.getId();
String[] addOns = new String[mAddOns.length];
for (int i = 0; i < addOns.length; i++)
addOns[i] = mAddOns[i].getId();
myState.addOnIds = addOns;
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !(state instanceof AddOnsListSavedState)) {
// although, this should not happen
super.onRestoreInstanceState(state);
} else {
AddOnsListSavedState myState = (AddOnsListSavedState) state;
String selectedAddOnId = myState.selectedAddOnId;
String[] addOnIds = myState.addOnIds;
AddOn[] addOns = new AddOn[addOnIds.length];
for (int i = 0; i < addOns.length; i++)
addOns[i] = AddOnsFactory
.locateAddOn(addOnIds[i], getContext().getApplicationContext());
setAddOnsList(addOns);
setSelectedAddOn(AddOnsFactory.locateAddOn(selectedAddOnId,
getContext().getApplicationContext()));
super.onRestoreInstanceState(myState.getSuperState());
}
}
private static class AddOnsListSavedState extends AbsSavedState {
String selectedAddOnId;
String[] addOnIds;
public AddOnsListSavedState(Parcel source) {
super(source);
selectedAddOnId = source.readString();
int addOnCount = source.readInt();
addOnIds = new String[addOnCount];
source.readStringArray(addOnIds);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(selectedAddOnId);
dest.writeInt(addOnIds.length);
dest.writeStringArray(addOnIds);
}
public AddOnsListSavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<AddOnsListSavedState> CREATOR = new Parcelable.Creator<AddOnsListSavedState>() {
public AddOnsListSavedState createFromParcel(Parcel in) {
return new AddOnsListSavedState(in);
}
public AddOnsListSavedState[] newArray(int size) {
return new AddOnsListSavedState[size];
}
};
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
final AddOn addOn = getItem(position);
// inflate layout
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View row = inflator.inflate(R.layout.addon_list_item_pref, parent,
false);
row.setTag(addOn);
// set on click listener for row
row.setOnClickListener(this);
// set addon details
TextView title = (TextView) row.findViewById(R.id.addon_title);
title.setText(addOn.getName());
TextView description = (TextView) row
.findViewById(R.id.addon_description);
description.setText(addOn.getDescription());
Drawable icon = null;
if (addOn instanceof IconHolder) {
IconHolder iconHolder = (IconHolder) addOn;
icon = iconHolder.getIcon();
}
if (icon == null) {
try {
PackageManager packageManager = getContext()
.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
addOn.getPackageContext().getPackageName(), 0);
icon = packageInfo.applicationInfo.loadIcon(packageManager);
} catch (PackageManager.NameNotFoundException e) {
icon = null;
}
}
ImageView addOnIcon = (ImageView) row
.findViewById(R.id.addon_image);
addOnIcon.setImageDrawable(icon);
if (addOn instanceof ScreenshotHolder) {
if (((ScreenshotHolder) addOn).hasScreenshot()) {
addOnIcon.setOnClickListener(this);
addOnIcon.setTag(addOn);
row.findViewById(R.id.addon_image_more_overlay)
.setVisibility(View.VISIBLE);
}
}
// set checkbox
RadioButton tb = (RadioButton) row
.findViewById(R.id.addon_checkbox);
tb.setClickable(false);
tb.setChecked(addOn.getId() == mSelectedAddOn.getId());
return row;
}
| public View getView(int position, View convertView, ViewGroup parent) {
final AddOn addOn = getItem(position);
// inflate layout
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View row = inflator.inflate(R.layout.addon_list_item_pref, parent,
false);
row.setTag(addOn);
// set on click listener for row
row.setOnClickListener(this);
// set addon details
TextView title = (TextView) row.findViewById(R.id.addon_title);
title.setText(addOn.getName());
TextView description = (TextView) row
.findViewById(R.id.addon_description);
description.setText(addOn.getDescription());
Drawable icon = null;
if (addOn instanceof IconHolder) {
IconHolder iconHolder = (IconHolder) addOn;
icon = iconHolder.getIcon();
}
if (icon == null) {
try {
PackageManager packageManager = getContext()
.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(addOn.getPackageName(), 0);
icon = packageInfo.applicationInfo.loadIcon(packageManager);
} catch (PackageManager.NameNotFoundException e) {
icon = null;
}
}
ImageView addOnIcon = (ImageView) row
.findViewById(R.id.addon_image);
addOnIcon.setImageDrawable(icon);
if (addOn instanceof ScreenshotHolder) {
if (((ScreenshotHolder) addOn).hasScreenshot()) {
addOnIcon.setOnClickListener(this);
addOnIcon.setTag(addOn);
row.findViewById(R.id.addon_image_more_overlay)
.setVisibility(View.VISIBLE);
}
}
// set checkbox
RadioButton tb = (RadioButton) row
.findViewById(R.id.addon_checkbox);
tb.setClickable(false);
tb.setChecked(addOn.getId() == mSelectedAddOn.getId());
return row;
}
|
diff --git a/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/masking/MaskingTool.java b/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/masking/MaskingTool.java
index b5d64eba1..041bbc2ff 100644
--- a/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/masking/MaskingTool.java
+++ b/org.dawnsci.plotting.tools/src/org/dawnsci/plotting/tools/masking/MaskingTool.java
@@ -1,1560 +1,1560 @@
package org.dawnsci.plotting.tools.masking;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.dawb.common.ui.image.CursorUtils;
import org.dawb.common.ui.image.IconUtils;
import org.dawb.common.ui.image.ShapeType;
import org.dawb.common.ui.menu.CheckableActionGroup;
import org.dawb.common.ui.menu.MenuAction;
import org.dawb.common.ui.util.EclipseUtils;
import org.dawb.common.ui.util.GridUtils;
import org.dawb.common.ui.wizard.persistence.PersistenceExportWizard;
import org.dawb.common.ui.wizard.persistence.PersistenceImportWizard;
import org.dawnsci.common.widgets.spinner.FloatSpinner;
import org.dawnsci.plotting.AbstractPlottingSystem;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.dawnsci.plotting.api.histogram.HistogramBound;
import org.dawnsci.plotting.api.preferences.BasePlottingConstants;
import org.dawnsci.plotting.api.preferences.PlottingConstants;
import org.dawnsci.plotting.api.region.IROIListener;
import org.dawnsci.plotting.api.region.IRegion;
import org.dawnsci.plotting.api.region.IRegion.RegionType;
import org.dawnsci.plotting.api.region.IRegionAction;
import org.dawnsci.plotting.api.region.IRegionListener;
import org.dawnsci.plotting.api.region.ROIEvent;
import org.dawnsci.plotting.api.region.RegionEvent;
import org.dawnsci.plotting.api.region.RegionUtils;
import org.dawnsci.plotting.api.tool.AbstractToolPage;
import org.dawnsci.plotting.api.tool.IToolPage;
import org.dawnsci.plotting.api.trace.IImageTrace;
import org.dawnsci.plotting.api.trace.IPaletteListener;
import org.dawnsci.plotting.api.trace.ITraceListener;
import org.dawnsci.plotting.api.trace.PaletteEvent;
import org.dawnsci.plotting.api.trace.TraceEvent;
import org.dawnsci.plotting.tools.Activator;
import org.dawnsci.plotting.util.ColorUtility;
import org.eclipse.core.commands.operations.IOperationHistoryListener;
import org.eclipse.core.commands.operations.OperationHistoryEvent;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.draw2d.geometry.PrecisionPoint;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.ColorSelector;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
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.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IActionBars;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
import uk.ac.diamond.scisoft.analysis.dataset.BooleanDataset;
public class MaskingTool extends AbstractToolPage implements MouseListener{
private static final Logger logger = LoggerFactory.getLogger(MaskingTool.class);
private ScrolledComposite scrollComp;
private FloatSpinner minimum, maximum;
private Button autoApply;
private MaskObject maskObject;
private MaskJob maskJob;
private TableViewer regionTable;
private ToolBarManager directToolbar;
private Button apply;
private IPaletteListener paletteListener;
private ITraceListener traceListener;
private IRegionListener regionListener;
private IROIListener regionBoundsListener;
private MaskMouseListener clickListener;
private ColorSelector colorSelector;
public MaskingTool() {
this.traceListener = new ITraceListener.Stub() {
@Override
public void traceAdded(TraceEvent evt) {
try {
if (evt.getSource() instanceof IImageTrace) {
((IImageTrace)evt.getSource()).setMask(maskObject.getMaskDataset());
((IImageTrace)evt.getSource()).addPaletteListener(paletteListener);
int[] ia = ((IImageTrace)evt.getSource()).getImageServiceBean().getNanBound().getColor();
updateIcons(ia);
colorSelector.setColorValue(ColorUtility.getRGB(ia));
if (autoApplySavedMask && savedMask!=null) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
try {
mergeSavedMask();
} catch (Throwable ne) {
logger.error("Problem loading saved mask!", ne);
}
}
});
}
} else {
saveMaskBuffer();
}
} catch (Exception ne) {
logger.error("Cannot update trace!", ne);
}
}
@Override
public void traceRemoved(TraceEvent evt) {
if (evt.getSource() instanceof IImageTrace) {
((IImageTrace)evt.getSource()).removePaletteListener(paletteListener);
}
}
};
this.paletteListener = new IPaletteListener.Stub() {
@Override
public void nanBoundsChanged(PaletteEvent evt) {
updateIcons(evt.getTrace().getNanBound().getColor());
}
};
this.clickListener = new MaskMouseListener();
this.regionListener = new IRegionListener.Stub() {
@Override
public void regionCreated(RegionEvent evt) {
// Those created while the tool is active are mask regions
evt.getRegion().setMaskRegion(true);
if (MaskMarker.MASK_REGION == evt.getRegion().getUserObject()) {
int wid = Activator.getPlottingPreferenceStore().getInt(PlottingConstants.FREE_DRAW_WIDTH);
evt.getRegion().setLineWidth(wid);
evt.getRegion().setUserObject(MaskObject.MaskRegionType.REGION_FROM_MASKING);
}
}
@Override
public void regionAdded(final RegionEvent evt) {
if (MaskMarker.MASK_REGION == evt.getRegion().getUserObject()) {
int wid = Activator.getPlottingPreferenceStore().getInt(PlottingConstants.FREE_DRAW_WIDTH);
evt.getRegion().setLineWidth(wid);
evt.getRegion().setUserObject(MaskObject.MaskRegionType.REGION_FROM_MASKING);
}
setLastActionRange(false);
evt.getRegion().addROIListener(regionBoundsListener);
processMask(evt.getRegion());
regionTable.refresh();
if (Activator.getPlottingPreferenceStore().getBoolean(PlottingConstants.MASK_DRAW_MULTIPLE)) {
Display.getDefault().asyncExec(new Runnable(){
public void run() {
try {
getPlottingSystem().createRegion(RegionUtils.getUniqueName(evt.getRegion().getRegionType().getName(), getPlottingSystem()),
evt.getRegion().getRegionType());
} catch (Exception e) {
logger.error("Cannot add multple regions.", e);
}
}
});
}
}
@Override
public void regionRemoved(RegionEvent evt) {
evt.getRegion().removeROIListener(regionBoundsListener);
processMask(true, false, null);
regionTable.refresh();
}
@Override
public void regionsRemoved(RegionEvent evt) {
processMask(true, false, null);
regionTable.refresh();
}
};
this.regionBoundsListener = new IROIListener.Stub() {
@Override
public void roiChanged(ROIEvent evt) {
processMask((IRegion)evt.getSource());
}
};
this.maskJob = new MaskJob();
maskJob.setPriority(Job.INTERACTIVE);
maskJob.setUser(false);
}
protected final class MaskMouseListener extends MouseMotionListener.Stub implements org.eclipse.draw2d.MouseListener {
@Override
public void mousePressed(org.eclipse.draw2d.MouseEvent me) {
if (me.button!=1) return;
if (((AbstractPlottingSystem)getPlottingSystem()).getSelectedCursor()==null) {
ActionContributionItem item = (ActionContributionItem)directToolbar.find(ShapeType.NONE.getId());
if (item!=null) item.getAction().setChecked(true);
return;
}
setLastActionRange(false);
maskJob.schedule(false, null, me.getLocation());
}
@Override
public void mouseDragged(org.eclipse.draw2d.MouseEvent me) {
if (me.button!=0) return;
if (((AbstractPlottingSystem)getPlottingSystem()).getSelectedCursor()==null) {
ActionContributionItem item = (ActionContributionItem)directToolbar.find(ShapeType.NONE.getId());
if (item!=null) item.getAction().setChecked(true);
return;
}
setLastActionRange(false);
maskJob.schedule(false, null, me.getLocation());
}
@Override
public void mouseReleased(org.eclipse.draw2d.MouseEvent me) {
// record shift point
((AbstractPlottingSystem)getPlottingSystem()).setShiftPoint(me.getLocation());
}
@Override
public void mouseDoubleClicked(org.eclipse.draw2d.MouseEvent me) { }
}
public void setPlottingSystem(IPlottingSystem system) {
super.setPlottingSystem(system);
this.maskObject = new MaskObject(); //TODO maybe make maskCreator by only processing visible regions.
}
@Override
public ToolPageRole getToolPageRole() {
return ToolPageRole.ROLE_2D;
}
@Override
public void createControl(Composite parent) {
scrollComp = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
final Group composite = new Group(scrollComp, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
final IImageTrace image = getImageTrace();
if (image!=null) {
composite.setText("Masking '"+image.getName()+"'");
} else {
composite.setText("Masking ");
}
final Composite minMaxComp = new Composite(composite, SWT.NONE);
minMaxComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
minMaxComp.setLayout(new GridLayout(2, false));
Label label = new Label(minMaxComp, SWT.WRAP);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2,1));
label.setText("Create a mask, the mask can be saved and available in other tools.");
final CLabel warningMessage = new CLabel(minMaxComp, SWT.WRAP);
- warningMessage.setText("Changing lower / upper can reset the mask as is not undoable.");
+ warningMessage.setText("Changing lower / upper can reset the mask and is not undoable.");
warningMessage.setToolTipText("The reset can occur because the algorithm which processes intensity values,\ndoes not know if the mask pixel should be unmasked or not.\nIt can only take into account intensity.\nTherefore it is best to define intensity masks first,\nbefore the custom masks using pen or region tools." );
warningMessage.setImage(Activator.getImage("icons/error.png"));
warningMessage.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2,1));
GridUtils.setVisible(warningMessage, false);
// Max and min
final Button minEnabled = new Button(minMaxComp, SWT.CHECK);
minEnabled.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
minEnabled.setText("Enable lower mask ");
minEnabled.setToolTipText("Enable the lower bound mask, removing pixels with lower intensity.");
this.minimum = new FloatSpinner(minMaxComp, SWT.NONE);
minimum.setIncrement(1d);
minimum.setEnabled(false);
minimum.setMinimum(Integer.MIN_VALUE);
minimum.setMaximum(Integer.MAX_VALUE);
minimum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) minimum.setDouble(getValue(image.getMin(), image.getMinCut(), 0));
minimum.setToolTipText("Press enter to apply a full update of the mask.");
minimum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(true, false, null);
setLastActionRange(true);
}
});
minimum.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
processMask(isLastActionRange(), true, null);
}
}
});
final Button maxEnabled = new Button(minMaxComp, SWT.CHECK);
maxEnabled.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
maxEnabled.setText("Enable upper mask ");
maxEnabled.setToolTipText("Enable the upper bound mask, removing pixels with higher intensity.");
minEnabled.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
minimum.setEnabled(minEnabled.getSelection());
GridUtils.setVisible(warningMessage, minEnabled.getSelection()||maxEnabled.getSelection());
warningMessage.getParent().getParent().layout();
if (!minEnabled.getSelection()) {
warningMessage.getParent().getParent().layout();
} else {
processMask(false, true, null);
}
}
});
maxEnabled.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maximum.setEnabled(maxEnabled.getSelection());
GridUtils.setVisible(warningMessage, minEnabled.getSelection()||maxEnabled.getSelection());
warningMessage.getParent().getParent().layout();
if (!maxEnabled.getSelection()) {
processMask(true, true, null);
} else {
processMask(false, true, null);
}
}
});
this.maximum = new FloatSpinner(minMaxComp, SWT.NONE);
maximum.setIncrement(1d);
maximum.setEnabled(false);
maximum.setMinimum(Integer.MIN_VALUE);
maximum.setMaximum(Integer.MAX_VALUE);
maximum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) maximum.setDouble(getValue(image.getMax(), image.getMaxCut(), Integer.MAX_VALUE));
maximum.setToolTipText("Press enter to apply a full update of the mask.");
maximum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(true, false, null);
setLastActionRange(true);
}
});
maximum.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
processMask(isLastActionRange(), true, null);
}
}
});
final Button ignoreAlreadyMasked = new Button(minMaxComp, SWT.CHECK);
ignoreAlreadyMasked.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2,1));
ignoreAlreadyMasked.setText("Keep pixels aleady masked");
ignoreAlreadyMasked.setToolTipText("When using bounds, pixels already masked can be ignored and not checked for range.\nThis setting is ignored when removing the bounds mask.");
ignoreAlreadyMasked.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setIgnoreAlreadyMasked(ignoreAlreadyMasked.getSelection());
}
});
label = new Label(minMaxComp, SWT.NONE);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2,1));
label = new Label(minMaxComp, SWT.NONE);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1,1));
label.setText("Mask Color");
this.colorSelector = new ColorSelector(minMaxComp);
colorSelector.getButton().setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
if (image!=null) colorSelector.setColorValue(ColorUtility.getRGB(image.getNanBound().getColor()));
colorSelector.addListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
getImageTrace().setNanBound(new HistogramBound(Double.NaN, ColorUtility.getIntArray(colorSelector.getColorValue())));
getImageTrace().rehistogram();
}
});
final Group drawGroup = new Group(composite, SWT.SHADOW_NONE);
drawGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
drawGroup.setLayout(new GridLayout(3, false));
label = new Label(drawGroup, SWT.NONE);
GridData data = new GridData(SWT.LEFT, SWT.FILL, false, false);
label.setLayoutData(data);
label.setText("Mask using: ");
final Button directDraw = new Button(drawGroup, SWT.RADIO);
directDraw.setText("Direct draw");
directDraw.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
final Button regionDraw = new Button(drawGroup, SWT.RADIO);
regionDraw.setText("Regions");
regionDraw.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, false));
label = new Label(drawGroup, SWT.HORIZONTAL|SWT.SEPARATOR);
GridData gdata = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
gdata.verticalIndent=5;
label.setLayoutData(gdata);
final Composite drawContent = new Composite(drawGroup, SWT.NONE);
drawContent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
drawContent.setLayout(new StackLayout());
final Composite directComp = new Composite(drawContent, SWT.NONE);
directComp.setLayout(new GridLayout(1, false));
GridUtils.removeMargins(directComp);
this.directToolbar = new ToolBarManager(SWT.FLAT|SWT.RIGHT|SWT.WRAP);
createDirectToolbarActions(directToolbar);
Control tb = directToolbar.createControl(directComp);
tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
new Label(directComp, SWT.NONE);
final Label shiftLabel = new Label(directComp, SWT.WRAP);
shiftLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, true, false));
shiftLabel.setText("(Hold down the 'shift' key to draw lines.)");
new Label(directComp, SWT.NONE);
new Label(directComp, SWT.NONE);
final Button useThresh = new Button(directComp, SWT.CHECK);
useThresh.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
useThresh.setText("Use threshold on brush.");
final Composite threshComp = new Composite(directComp, SWT.NONE);
threshComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
threshComp.setLayout(new GridLayout(2, false));
final Label minThreshLabel = new Label(threshComp, SWT.NONE);
threshComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
minThreshLabel.setText("Minimum Threshold");
final FloatSpinner minThresh = new FloatSpinner(threshComp, SWT.NONE);
minThresh.setIncrement(1d);
minThresh.setMinimum(Integer.MIN_VALUE);
minThresh.setMaximum(Integer.MAX_VALUE);
minThresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) minThresh.setDouble(getValue(image.getMin(), image.getMinCut(), 0));
minThresh.setToolTipText("Press enter to set minimum threshold for brush.");
final Label maxThreshLabel = new Label(threshComp, SWT.NONE);
maxThreshLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
maxThreshLabel.setText("Maximum Threshold");
final FloatSpinner maxThresh = new FloatSpinner(threshComp, SWT.NONE);
maxThresh.setIncrement(1d);
maxThresh.setMinimum(Integer.MIN_VALUE);
maxThresh.setMaximum(Integer.MAX_VALUE);
maxThresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) maxThresh.setDouble(getValue(image.getMax(), image.getMaxCut(), Integer.MAX_VALUE));
maxThresh.setToolTipText("Press enter to set maximum threshold for brush.");
minThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
});
minThresh.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
}
});
maxThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
});
maxThresh.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
}
});
useThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
GridUtils.setVisible(threshComp, useThresh.getSelection());
PrecisionPoint thresh = useThresh.getSelection()
? new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble())
: null;
maskObject.setBrushThreshold(thresh);
threshComp.getParent().layout();
}
});
GridUtils.setVisible(threshComp, false);
// Regions
final Composite regionComp = new Composite(drawContent, SWT.NONE);
regionComp.setLayout(new GridLayout(1, false));
GridUtils.removeMargins(regionComp);
final ToolBarManager regionToolbar = new ToolBarManager(SWT.FLAT|SWT.RIGHT);
createMaskingRegionActions(regionToolbar);
tb = regionToolbar.createControl(regionComp);
tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
this.regionTable = new TableViewer(regionComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
regionTable.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
createColumns(regionTable);
regionTable.getTable().setLinesVisible(true);
regionTable.getTable().setHeaderVisible(true);
regionTable.getTable().addMouseListener(this);
getSite().setSelectionProvider(regionTable);
regionTable.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
final Collection<IRegion> regions = getPlottingSystem().getRegions();
if (regions==null || regions.isEmpty()) return new Object[]{"-"};
final List<IRegion> supported = new ArrayList<IRegion>(regions.size());
for (IRegion iRegion : regions) if (maskObject.isSupportedRegion(iRegion) &&
iRegion.isUserRegion()) {
supported.add(iRegion);
}
return supported.toArray(new IRegion[supported.size()]);
}
});
regionTable.setInput(new Object());
final Composite buttons = new Composite(drawGroup, SWT.BORDER);
buttons.setLayout(new GridLayout(2, false));
buttons.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 3, 1));
this.autoApply = new Button(buttons, SWT.CHECK);
autoApply.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 2, 1));
autoApply.setText("Automatically apply mask when something changes.");
autoApply.setSelection(Activator.getPlottingPreferenceStore().getBoolean(PlottingConstants.MASK_AUTO_APPLY));
this.apply = new Button(buttons, SWT.PUSH);
apply.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
apply.setImage(Activator.getImage("icons/apply.gif"));
apply.setText("Apply");
apply.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(isLastActionRange(), true, null);
}
});
apply.setEnabled(true);
autoApply.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_AUTO_APPLY, autoApply.getSelection());
apply.setEnabled(!autoApply.getSelection());
processMask();
}
});
final Button reset = new Button(buttons, SWT.PUSH);
reset.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
reset.setImage(Activator.getImage("icons/reset.gif"));
reset.setText("Reset");
reset.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resetMask();
}
});
createActions(getSite().getActionBars());
final StackLayout layout = (StackLayout)drawContent.getLayout();
layout.topControl = directComp;
directDraw.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_TYPE, "direct");
layout.topControl = directComp;
drawContent.layout();
ShapeType penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
ActionContributionItem item= ((ActionContributionItem)directToolbar.find(penShape.getId()));
if (item!=null) item.getAction().run();
setRegionsVisible(false);
}
});
regionDraw.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_TYPE, "region");
layout.topControl = regionComp;
drawContent.layout();
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(null);
setRegionsVisible(true);
}
});
String drawType = Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_DRAW_TYPE);
if (drawType!=null && !"".equals(drawType)) {
if ("direct".equals(drawType)) {
directDraw.setSelection(true);
layout.topControl = directComp;
ShapeType penShape = ShapeType.NONE;
if (Activator.getPlottingPreferenceStore().contains(PlottingConstants.MASK_PEN_SHAPE)) {
penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
}
ActionContributionItem item= ((ActionContributionItem)directToolbar.find(penShape.getId()));
if (item!=null) item.getAction().run();
} else if ("region".equals(drawType)) {
regionDraw.setSelection(true);
layout.topControl = regionComp;
}
}
scrollComp.setContent(composite);
scrollComp.setExpandVertical(true);
scrollComp.setExpandHorizontal(true);
scrollComp.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
Rectangle r = scrollComp.getClientArea();
scrollComp.setMinHeight(composite.computeSize(r.width, SWT.DEFAULT).y);
scrollComp.setMinWidth(composite.computeSize(SWT.DEFAULT, r.height).x);
}
});
}
private boolean lastActionRange = false;
protected void setLastActionRange(boolean isRange) {
lastActionRange = isRange;
}
protected boolean isLastActionRange() {
return lastActionRange;
}
protected void setRegionsVisible(boolean isVis) {
if (getPlottingSystem()==null) return;
final Collection<IRegion> regions = getPlottingSystem().getRegions();
for (IRegion iRegion : regions) {
if (iRegion.isMaskRegion()) iRegion.setVisible(isVis);
}
}
/**
* Actions for
* @param freeToolbar2
*/
private void createDirectToolbarActions(ToolBarManager man) {
final MenuAction penSize = new MenuAction("Pen Size");
penSize.setToolTipText("Pen size");
man.add(penSize);
CheckableActionGroup group = new CheckableActionGroup();
final int[] pensizes = new int[]{1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,24,32,64};
Action currentSize=null;
for (final int pensize : pensizes) {
final Action action = new Action("Pen size of "+String.valueOf(pensize), IAction.AS_CHECK_BOX) {
public void run() {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_SIZE, pensize);
penSize.setSelectedAction(this);
penSize.setToolTipText(getToolTipText());
ShapeType penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
if (penShape!=null) {
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(CursorUtils.getPenCursor(pensize, penShape));
}
}
};
action.setImageDescriptor(IconUtils.createPenDescriptor(pensize));
penSize.add(action);
group.add(action);
if (Activator.getPlottingPreferenceStore().getInt(PlottingConstants.MASK_PEN_SIZE)==pensize) {
currentSize = action;
}
action.setToolTipText("Set pen size to "+pensize);
}
if (currentSize!=null) {
currentSize.setChecked(true);
penSize.setSelectedAction(currentSize);
penSize.setToolTipText(currentSize.getToolTipText());
}
man.add(new Separator());
group = new CheckableActionGroup();
Action action = new Action("Square brush", IAction.AS_CHECK_BOX) {
public void run() {
int pensize = Activator.getPlottingPreferenceStore().getInt(PlottingConstants.MASK_PEN_SIZE);
ShapeType penShape = ShapeType.SQUARE;
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(CursorUtils.getPenCursor(pensize, penShape));
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_SHAPE, penShape.name());
}
};
action.setId(ShapeType.SQUARE.getId());
group.add(action);
man.add(action);
action = new Action("Triangle brush", IAction.AS_CHECK_BOX) {
public void run() {
int pensize = Activator.getPlottingPreferenceStore().getInt(PlottingConstants.MASK_PEN_SIZE);
ShapeType penShape = ShapeType.TRIANGLE;
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(CursorUtils.getPenCursor(pensize, penShape));
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_SHAPE, penShape.name());
}
};
action.setId(ShapeType.TRIANGLE.getId());
group.add(action);
man.add(action);
action = new Action("Circular brush", IAction.AS_CHECK_BOX) {
public void run() {
int pensize = Activator.getPlottingPreferenceStore().getInt(PlottingConstants.MASK_PEN_SIZE);
ShapeType penShape = ShapeType.CIRCLE;
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(CursorUtils.getPenCursor(pensize, penShape));
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_SHAPE, penShape.name());
}
};
action.setId(ShapeType.CIRCLE.getId());
group.add(action);
man.add(action);
action = new Action("None", IAction.AS_CHECK_BOX) {
public void run() {
ShapeType penShape = ShapeType.NONE;
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_SHAPE, penShape.name());
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(null);
}
};
action.setId(ShapeType.NONE.getId());
action.setImageDescriptor(Activator.getImageDescriptor("icons/MouseArrow.png"));
group.add(action);
man.add(action);
man.add(new Separator());
group = new CheckableActionGroup();
final Action mask = new Action("Mask", IAction.AS_CHECK_BOX) {
public void run() {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_MASKOUT, true);
updateIcons(getImageTrace().getNanBound().getColor());
}
};
mask.setImageDescriptor(Activator.getImageDescriptor("icons/mask-add.png"));
group.add(mask);
man.add(mask);
final Action unmask = new Action("Unmask", IAction.AS_CHECK_BOX) {
public void run() {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_PEN_MASKOUT, false);
updateIcons(null);
}
};
unmask.setImageDescriptor(Activator.getImageDescriptor("icons/mask-remove.png"));
group.add(unmask);
man.add(unmask);
man.add(new Separator());
boolean maskout = Activator.getPlottingPreferenceStore().getBoolean(PlottingConstants.MASK_PEN_MASKOUT);
if (maskout) {
if (getImageTrace()!=null) {
updateIcons(getImageTrace().getNanBound().getColor());
} else {
updateIcons(new int[]{0,255,0});
}
mask.setChecked(true);
} else {
updateIcons(null);
unmask.setChecked(true);
}
Display.getDefault().asyncExec(new Runnable() {
public void run() {
String savedShape = Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE);
if (savedShape!=null && !"".equals(savedShape)) {
ShapeType type = ShapeType.valueOf(savedShape);
((ActionContributionItem)directToolbar.find(type.getId())).getAction().setChecked(true);
}
}
});
}
private void updateIcons(int[] ia) {
RGB maskColor = ColorUtility.getRGB(ia);
((ActionContributionItem)directToolbar.find(ShapeType.SQUARE.getId())).getAction().setImageDescriptor(IconUtils.getBrushIcon( 12, ShapeType.SQUARE, maskColor));
((ActionContributionItem)directToolbar.find(ShapeType.TRIANGLE.getId())).getAction().setImageDescriptor(IconUtils.getBrushIcon(12, ShapeType.TRIANGLE, maskColor));
((ActionContributionItem)directToolbar.find(ShapeType.CIRCLE.getId())).getAction().setImageDescriptor(IconUtils.getBrushIcon( 12, ShapeType.CIRCLE, maskColor));
}
private static BooleanDataset savedMask=null;
private static boolean autoApplySavedMask=false;
private static MaskingTool currentMaskingTool=null;
private static final String AUTO_SAVE_PROP="org.dawb.workbench.plotting.tools.auto.save.mask";
private IAction loadMask;
private static IAction autoApplyMask, alwaysSave;
/**
* You can programmatically set the last saved mask by calling this method.
*
* NOTE: In future a mask saving and retrieving methodology will exist.
* This method is used for an NCD workaround and is not intended
* as a long term solution for mask saving/loading
*
* @param sm - static dataset to use as the mask
* @param autoApply - if true the mask will be applied when the tool is activated
*/
public static void setSavedMask(final BooleanDataset sm, final boolean autoApply) {
savedMask = sm;
autoApplySavedMask = autoApply;
if (autoApplyMask!=null) {
autoApplyMask.setChecked(autoApply);
}
}
public static BooleanDataset getSavedMask() {
return savedMask;
}
private void createActions(IActionBars actionBars) {
final Action exportMask = new Action("Export mask to file", Activator.getImageDescriptor("icons/mask-export-wiz.png")) {
public void run() {
try {
IWizard wiz = EclipseUtils.openWizard(PersistenceExportWizard.ID, false);
WizardDialog wd = new WizardDialog(Display.getCurrent().getActiveShell(), wiz);
wd.setTitle(wiz.getWindowTitle());
wd.open();
} catch (Exception e) {
logger.error("Problem opening import!", e);
}
}
};
actionBars.getToolBarManager().add(exportMask);
final Action importMask = new Action("Import mask from file", Activator.getImageDescriptor("icons/mask-import-wiz.png")) {
public void run() {
try {
autoApply.setSelection(false);
apply.setEnabled(true);
IWizard wiz = EclipseUtils.openWizard(PersistenceImportWizard.ID, false);
WizardDialog wd = new WizardDialog(Display.getCurrent().getActiveShell(), wiz);
wd.setTitle(wiz.getWindowTitle());
wd.open();
} catch (Exception e) {
logger.error("Problem opening import!", e);
}
}
};
actionBars.getToolBarManager().add(importMask);
actionBars.getToolBarManager().add(new Separator());
final Action invertMask = new Action("Invert mask", Activator.getImageDescriptor("icons/mask-invert.png")) {
public void run() {
try {
maskObject.invert();
final IImageTrace image = getImageTrace();
image.setMask(maskObject.getMaskDataset());
} catch (Exception e) {
logger.error("Problem opening import!", e);
}
}
};
actionBars.getToolBarManager().add(invertMask);
actionBars.getToolBarManager().add(new Separator());
final Action undo = new Action("Undo mask operation", Activator.getImageDescriptor("icons/mask-undo.png")) {
public void run() {
maskObject.undo();
getImageTrace().setMask(maskObject.getMaskDataset());
}
};
actionBars.getToolBarManager().add(undo);
undo.setEnabled(false);
final Action redo = new Action("Redo mask operation", Activator.getImageDescriptor("icons/mask-redo.png")) {
public void run() {
maskObject.redo();
getImageTrace().setMask(maskObject.getMaskDataset());
}
};
actionBars.getToolBarManager().add(redo);
redo.setEnabled(false);
actionBars.getToolBarManager().add(new Separator());
maskObject.getOperationManager().addOperationHistoryListener(new IOperationHistoryListener() {
@Override
public void historyNotification(OperationHistoryEvent event) {
undo.setEnabled(maskObject.getOperationManager().canUndo(MaskOperation.MASK_CONTEXT));
redo.setEnabled(maskObject.getOperationManager().canRedo(MaskOperation.MASK_CONTEXT));
}
});
final Action reset = new Action("Reset Mask", Activator.getImageDescriptor("icons/reset.gif")) {
public void run() {
resetMask();
}
};
actionBars.getToolBarManager().add(reset);
actionBars.getToolBarManager().add(new Separator());
final Action saveMask = new Action("Export the mask into a temporary buffer", Activator.getImageDescriptor("icons/export_wiz.gif")) {
public void run() {
saveMaskBuffer();
}
};
actionBars.getToolBarManager().add(saveMask);
loadMask = new Action("Import the mask from temporary buffer", Activator.getImageDescriptor("icons/import_wiz.gif")) {
public void run() {
mergeSavedMask();
}
};
loadMask.setEnabled(savedMask!=null);
actionBars.getToolBarManager().add(loadMask);
if (autoApplyMask==null) {
autoApplyMask = new Action("Automatically apply the mask buffer to any image plotted.", IAction.AS_CHECK_BOX) {
public void run() {
autoApplySavedMask = isChecked();
if (autoApplySavedMask&¤tMaskingTool!=null) {
if (savedMask==null) currentMaskingTool.saveMaskBuffer();
currentMaskingTool.mergeSavedMask();
if (!currentMaskingTool.isDedicatedView()) {
try {
currentMaskingTool.createToolInDedicatedView();
} catch (Exception e) {
logger.error("Internal error!", e);
}
}
}
}
};
autoApplyMask.setChecked(autoApplySavedMask);
autoApplyMask.setImageDescriptor(Activator.getImageDescriptor("icons/mask-autoapply.png"));
};
actionBars.getToolBarManager().add(autoApplyMask);
actionBars.getToolBarManager().add(new Separator());
if (alwaysSave==null) { // Needs to be static else you have to go back to all editors and
// uncheck each one.
alwaysSave = new Action("Auto-save the mask to the buffer when it changes", IAction.AS_CHECK_BOX) {
public void run() {
Activator.getPlottingPreferenceStore().setValue(AUTO_SAVE_PROP, isChecked());
}
};
alwaysSave.setImageDescriptor(Activator.getImageDescriptor("icons/plot-tool-masking-autosave.png"));
if (Activator.getPlottingPreferenceStore().contains(AUTO_SAVE_PROP)) {
alwaysSave.setChecked(Activator.getPlottingPreferenceStore().getBoolean(AUTO_SAVE_PROP));
} else {
Activator.getPlottingPreferenceStore().setValue(AUTO_SAVE_PROP, true);
alwaysSave.setChecked(true);
}
};
actionBars.getToolBarManager().add(alwaysSave);
final IPlottingSystem system = getPlottingSystem();
system.getPlotActionSystem().fillTraceActions(actionBars.getToolBarManager(), getImageTrace(), system);
}
protected void saveMaskBuffer() {
savedMask = maskObject.getMaskDataset();
loadMask.setEnabled(savedMask!=null);
}
protected void mergeSavedMask() {
if (getImageTrace()!=null) {
if (savedMask==null) return;
if (maskObject.getImageDataset()==null){
maskObject.setImageDataset((AbstractDataset)getImageTrace().getData());
}
maskObject.process(savedMask);
getImageTrace().setMask(maskObject.getMaskDataset());
}
}
private void createColumns(TableViewer viewer) {
ColumnViewerToolTipSupport.enableFor(viewer,ToolTip.NO_RECREATE);
viewer.setColumnProperties(new String[] { "Mask", "Name", "Type" });
TableViewerColumn var = new TableViewerColumn(viewer, SWT.LEFT, 0);
var.getColumn().setText("Mask");
var.getColumn().setWidth(50);
var.setLabelProvider(new MaskingLabelProvider());
var = new TableViewerColumn(viewer, SWT.CENTER, 1);
var.getColumn().setText("Name");
var.getColumn().setWidth(200);
var.setLabelProvider(new MaskingLabelProvider());
var.setEditingSupport(new NameEditingSupport(viewer));
var = new TableViewerColumn(viewer, SWT.CENTER, 2);
var.getColumn().setText("Type");
var.getColumn().setWidth(120);
var.setLabelProvider(new MaskingLabelProvider());
}
private boolean isInDoubleClick = false;
private class NameEditingSupport extends EditingSupport {
public NameEditingSupport(ColumnViewer viewer) {
super(viewer);
}
@Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor((Composite)getViewer().getControl());
}
@Override
protected boolean canEdit(Object element) {
return isInDoubleClick;
}
@Override
protected Object getValue(Object element) {
return ((IRegion)element).getName();
}
@Override
protected void setValue(Object element, Object value) {
IRegion region = (IRegion)element;
try {
String name = (String)value;
if (name!=null) {
name = name.trim();
if (name.equals(region.getName())) return;
}
if (getPlottingSystem().getRegion(name)!=null || name==null || "".equals(name)) {
throw new Exception("The region name '"+name+"' is not allowed.");
}
getPlottingSystem().renameRegion(region, name);
} catch (Exception e) {
final String message = "The name '"+value+"' is not valid.";
final Status status = new Status(Status.WARNING, "org.dawnsci.plotting", message, e);
ErrorDialog.openError(Display.getDefault().getActiveShell(), "Cannot rename region", message, status);
return;
}
getViewer().refresh(element);
}
}
private class MaskingLabelProvider extends ColumnLabelProvider {
private Image checkedIcon;
private Image uncheckedIcon;
public MaskingLabelProvider() {
ImageDescriptor id = Activator.getImageDescriptor("icons/ticked.png");
checkedIcon = id.createImage();
id = Activator.getImageDescriptor("icons/unticked.gif");
uncheckedIcon = id.createImage();
}
private int columnIndex;
public void update(ViewerCell cell) {
columnIndex = cell.getColumnIndex();
super.update(cell);
}
public Image getImage(Object element) {
if (columnIndex!=0) return null;
if (!(element instanceof IRegion)) return null;
final IRegion region = (IRegion)element;
return region.isMaskRegion() && regionTable.getTable().isEnabled() ? checkedIcon : uncheckedIcon;
}
public String getText(Object element) {
if (element instanceof String) return "";
final IRegion region = (IRegion)element;
switch(columnIndex) {
case 1:
return region.getName();
case 2:
return region.getRegionType().getName();
}
return "";
}
public void dispose() {
super.dispose();
checkedIcon.dispose();
uncheckedIcon.dispose();
}
}
private static final Collection<RegionType> maskingTypes;
static {
maskingTypes = new ArrayList<RegionType>(6);
//maskingTypes.add(RegionType.FREE_DRAW);
maskingTypes.add(RegionType.RING);
maskingTypes.add(RegionType.BOX);
maskingTypes.add(RegionType.LINE);
//maskingTypes.add(RegionType.POLYLINE);
maskingTypes.add(RegionType.POLYGON);
maskingTypes.add(RegionType.SECTOR);
}
private void createMaskingRegionActions(IToolBarManager man) {
final Action multipleRegion = new Action("Continuously add the same region", IAction.AS_CHECK_BOX) {
public void run() {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_MULTIPLE, isChecked());
}
};
multipleRegion.setImageDescriptor(Activator.getImageDescriptor("icons/RegionMultiple.png"));
multipleRegion.setChecked(Activator.getPlottingPreferenceStore().getBoolean(PlottingConstants.MASK_DRAW_MULTIPLE));
man.add(multipleRegion);
man.add(new Separator());
final MenuAction widthChoice = new MenuAction("Line Width");
widthChoice.setToolTipText("Line width for free draw and line regions");
man.add(widthChoice);
// Region actions supported
ActionContributionItem menu = (ActionContributionItem)getPlottingSystem().getActionBars().getMenuManager().find(BasePlottingConstants.ADD_REGION);
MenuAction menuAction = (MenuAction)menu.getAction();
IAction ld = null;
for (RegionType type : maskingTypes) {
final IAction action = menuAction.findAction(type.getId());
if (action==null) continue;
man.add(action);
if (type==RegionType.LINE) {
ld = action;
man.add(new Separator());
}
if (action instanceof IRegionAction) {
((IRegionAction)action).setUserObject(MaskMarker.MASK_REGION);
}
}
CheckableActionGroup group = new CheckableActionGroup();
final IAction lineDraw = ld;
final int maxWidth = 10;
for (int iwidth = 1; iwidth <= maxWidth; iwidth++) {
final int width = iwidth;
final Action action = new Action("Draw width of "+String.valueOf(width), IAction.AS_CHECK_BOX) {
public void run() {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.FREE_DRAW_WIDTH, width);
widthChoice.setSelectedAction(this);
lineDraw.run();
}
};
action.setImageDescriptor(IconUtils.createIconDescriptor(String.valueOf(iwidth)));
widthChoice.add(action);
group.add(action);
action.setChecked(false);
action.setToolTipText("Set line width to "+iwidth);
}
int wid = Activator.getPlottingPreferenceStore().getInt(PlottingConstants.FREE_DRAW_WIDTH);
widthChoice.setSelectedAction(wid-1);
widthChoice.setCheckedAction(wid-1, true);
man.add(new Separator());
menu = (ActionContributionItem)getPlottingSystem().getActionBars().getToolBarManager().find(BasePlottingConstants.REMOVE_REGION);
if (menu!=null) {
menuAction = (MenuAction)menu.getAction();
man.add(menuAction);
}
}
private int getValue(Number bound, HistogramBound hb, int defaultInt) {
if (bound!=null) return bound.intValue();
if (hb!=null && hb.getBound()!=null) {
if (!Double.isInfinite(hb.getBound().doubleValue())) {
return hb.getBound().intValue();
}
}
return defaultInt;
}
private void processMask() {
processMask(false, false, null);
}
private void processMask(final IRegion region) {
processMask(false, false, region);
}
/**
* Either adds a new region directly or
* @param forceProcess
* @param roi
* @return true if did some masking
*/
private void processMask(final boolean resetMask, boolean ignoreAuto, final IRegion region) {
if (!ignoreAuto && (autoApply!=null && !autoApply.getSelection())) return;
final IImageTrace image = getImageTrace();
if (image == null) return;
maskJob.schedule(resetMask, region, null);
}
protected void resetMask() { // Reread the file from disk or cached one if this is a view
final IImageTrace image = getImageTrace();
if (image==null) return;
maskObject.reset();
image.setMask(null);
if (autoApplySavedMask) { // If it is auto-apply then it needs to be reset when you reset.
final boolean ok = MessageDialog.openQuestion(Display.getDefault().getActiveShell(), "Confirm Removal of Saved Mask",
"You have a saved mask which can be cleared as well.\n\nWould you like to remove the saved mask?");
if (ok) {
savedMask = null;
autoApplySavedMask = false;
}
loadMask.setEnabled(savedMask!=null);
}
}
@Override
public Control getControl() {
return scrollComp;
}
@Override
public void setFocus() {
if (scrollComp!=null) scrollComp.setFocus();
}
@Override
public void activate() {
super.activate();
currentMaskingTool = this;
if (getPlottingSystem()!=null) {
getPlottingSystem().addTraceListener(traceListener); // If it changes get reference to image.
getPlottingSystem().addRegionListener(regionListener); // Listen to new regions
// For all supported regions, add listener for rois
final Collection<IRegion> regions = getPlottingSystem().getRegions();
if (regions!=null) for (IRegion region : regions) {
if (!maskObject.isSupportedRegion(region)) continue;
region.addROIListener(this.regionBoundsListener);
}
if (getImageTrace()!=null) {
getImageTrace().addPaletteListener(paletteListener);
}
((AbstractPlottingSystem)getPlottingSystem()).addMouseClickListener(clickListener);
((AbstractPlottingSystem)getPlottingSystem()).addMouseMotionListener(clickListener);
}
if (this.regionTable!=null && !regionTable.getControl().isDisposed()) {
regionTable.refresh();
}
if (loadMask!=null) loadMask.setEnabled(savedMask!=null);
}
@Override
public void deactivate() {
super.deactivate();
if (savedMask==null) saveMaskBuffer();
currentMaskingTool = null;
if (getPlottingSystem()!=null) {
getPlottingSystem().removeTraceListener(traceListener);
getPlottingSystem().removeRegionListener(regionListener);// Stop listen to new regions
// For all supported regions, add listener
final Collection<IRegion> regions = getPlottingSystem().getRegions();
if (regions!=null) for (IRegion region : regions) region.removeROIListener(this.regionBoundsListener);
if (getImageTrace()!=null) {
getImageTrace().removePaletteListener(paletteListener);
}
((AbstractPlottingSystem)getPlottingSystem()).removeMouseClickListener(clickListener);
((AbstractPlottingSystem)getPlottingSystem()).removeMouseMotionListener(clickListener);
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(null);
((AbstractPlottingSystem)getPlottingSystem()).setShiftPoint(null);
}
}
@Override
public void dispose() {
super.dispose();
if (scrollComp!=null) scrollComp.dispose();
if (maskObject!=null) maskObject.dispose();
scrollComp = null;
traceListener = null;
regionListener = null;
regionBoundsListener = null;
if (this.regionTable!=null && !regionTable.getControl().isDisposed()) {
regionTable.getTable().removeMouseListener(this);
}
}
@Override
public void sync(IToolPage with) {
if (with instanceof MaskingTool) {
MaskingTool sync = (MaskingTool)with;
maskObject.sync(sync.maskObject);
}
}
public class MaskJob extends Job {
public MaskJob() {
super("Masking image");
}
private boolean resetMask = false;
private boolean isRegionsEnabled = false;
private IRegion region = null;
private Double min=null, max=null;
private org.eclipse.draw2d.geometry.Point location;
@Override
protected IStatus run(final IProgressMonitor monitor) {
try {
if (isDisposed() || !isActive()) {
return Status.CANCEL_STATUS;
}
monitor.beginTask("Mask Process", 100);
final IImageTrace image = getImageTrace();
if (image == null) return Status.CANCEL_STATUS;
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
if (region!=null && !isRegionsEnabled) return Status.CANCEL_STATUS;
if (resetMask && !maskObject.isIgnoreAlreadyMasked()) {
maskObject.setMaskDataset(null, false);
}
if (maskObject.getMaskDataset()==null) {
// The mask must be maintained as a BooleanDataset so that there is the option
// of applying the same mask to many images.
final AbstractDataset unmasked = (AbstractDataset)image.getData();
maskObject.setMaskDataset(new BooleanDataset(unmasked.getShape()), true);
maskObject.setImageDataset(unmasked);
}
if (maskObject.getImageDataset()==null) {
final AbstractDataset unmasked = (AbstractDataset)image.getData();
maskObject.setImageDataset(unmasked);
}
// Keep the saved mask
if (autoApplySavedMask && savedMask!=null) maskObject.process(savedMask);
monitor.worked(1);
// Just process a changing region
if (location!=null) {
maskObject.process(location, getPlottingSystem(), monitor);
} else if (region!=null) {
if (!maskObject.isSupportedRegion(region)) return Status.CANCEL_STATUS;
maskObject.process(region, monitor);
} else { // process everything
maskObject.process(min, max, isRegionsEnabled?getPlottingSystem().getRegions():null, monitor);
}
if (Activator.getPlottingPreferenceStore().getBoolean(AUTO_SAVE_PROP)) {
saveMaskBuffer();
}
Display.getDefault().syncExec(new Runnable() {
public void run() {
// NOTE the mask will have a reference kept and
// will downsample with the data.
image.setMask(maskObject.getMaskDataset());
}
});
return Status.OK_STATUS;
} catch (Throwable ne) {
logger.error("Cannot mask properly at the edges as yet!", ne);
return Status.CANCEL_STATUS;
} finally {
monitor.done();
}
}
/**
* Uses job thread
* @param resetMask
* @param region
* @param loc
*/
public void schedule(boolean resetMask, IRegion region, org.eclipse.draw2d.geometry.Point loc) {
assign(resetMask, region, loc);
schedule();
}
private void assign(boolean resetMask, IRegion region, org.eclipse.draw2d.geometry.Point loc) {
if (isDisposed()) {
return;
}
this.isRegionsEnabled = regionTable!=null ? regionTable.getTable().isEnabled() : false;
this.resetMask = resetMask;
this.region = region;
this.location = loc;
min = (minimum!=null && minimum.isEnabled()) ? minimum.getDouble() : null;
max = (maximum!=null && maximum.isEnabled()) ? maximum.getDouble() : null;
}
/**
* Done in calling thread.
* @param resetMask
* @param region
* @param loc
*/
public void run(boolean resetMask, IRegion region, org.eclipse.draw2d.geometry.Point loc) {
assign(resetMask, region, loc);
try {
run(new NullProgressMonitor());
} catch (Throwable ne) {
logger.error("Cannot run masking job!", ne);
}
}
}
@Override
public void mouseDoubleClick(MouseEvent e) {
final TableItem item = this.regionTable.getTable().getItem(new Point(e.x, e.y));
if (e.button==1 && item!=null) {
Rectangle rect = item.getBounds(1); // Name
if (!rect.contains(e.x,e.y)) return;
try {
IRegion region = (IRegion)item.getData();
isInDoubleClick = true;
regionTable.editElement(region, 1);
} finally {
isInDoubleClick = false;
}
}
}
@Override
public void mouseDown(MouseEvent e) {
final TableItem item = this.regionTable.getTable().getItem(new Point(e.x, e.y));
if (item!=null) {
Rectangle rect = item.getBounds(0); // Tick
if (!rect.contains(e.x,e.y)) return;
IRegion region = (IRegion)item.getData();
region.setMaskRegion(!region.isMaskRegion());
region.setUserObject(MaskObject.MaskRegionType.REGION_FROM_MASKING);
regionTable.refresh(region);
processMask(true, false, null);
}
}
@Override
public void mouseUp(MouseEvent e) {
}
private enum MaskMarker {
MASK_REGION;
}
}
| true | true | public void createControl(Composite parent) {
scrollComp = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
final Group composite = new Group(scrollComp, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
final IImageTrace image = getImageTrace();
if (image!=null) {
composite.setText("Masking '"+image.getName()+"'");
} else {
composite.setText("Masking ");
}
final Composite minMaxComp = new Composite(composite, SWT.NONE);
minMaxComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
minMaxComp.setLayout(new GridLayout(2, false));
Label label = new Label(minMaxComp, SWT.WRAP);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2,1));
label.setText("Create a mask, the mask can be saved and available in other tools.");
final CLabel warningMessage = new CLabel(minMaxComp, SWT.WRAP);
warningMessage.setText("Changing lower / upper can reset the mask as is not undoable.");
warningMessage.setToolTipText("The reset can occur because the algorithm which processes intensity values,\ndoes not know if the mask pixel should be unmasked or not.\nIt can only take into account intensity.\nTherefore it is best to define intensity masks first,\nbefore the custom masks using pen or region tools." );
warningMessage.setImage(Activator.getImage("icons/error.png"));
warningMessage.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2,1));
GridUtils.setVisible(warningMessage, false);
// Max and min
final Button minEnabled = new Button(minMaxComp, SWT.CHECK);
minEnabled.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
minEnabled.setText("Enable lower mask ");
minEnabled.setToolTipText("Enable the lower bound mask, removing pixels with lower intensity.");
this.minimum = new FloatSpinner(minMaxComp, SWT.NONE);
minimum.setIncrement(1d);
minimum.setEnabled(false);
minimum.setMinimum(Integer.MIN_VALUE);
minimum.setMaximum(Integer.MAX_VALUE);
minimum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) minimum.setDouble(getValue(image.getMin(), image.getMinCut(), 0));
minimum.setToolTipText("Press enter to apply a full update of the mask.");
minimum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(true, false, null);
setLastActionRange(true);
}
});
minimum.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
processMask(isLastActionRange(), true, null);
}
}
});
final Button maxEnabled = new Button(minMaxComp, SWT.CHECK);
maxEnabled.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
maxEnabled.setText("Enable upper mask ");
maxEnabled.setToolTipText("Enable the upper bound mask, removing pixels with higher intensity.");
minEnabled.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
minimum.setEnabled(minEnabled.getSelection());
GridUtils.setVisible(warningMessage, minEnabled.getSelection()||maxEnabled.getSelection());
warningMessage.getParent().getParent().layout();
if (!minEnabled.getSelection()) {
warningMessage.getParent().getParent().layout();
} else {
processMask(false, true, null);
}
}
});
maxEnabled.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maximum.setEnabled(maxEnabled.getSelection());
GridUtils.setVisible(warningMessage, minEnabled.getSelection()||maxEnabled.getSelection());
warningMessage.getParent().getParent().layout();
if (!maxEnabled.getSelection()) {
processMask(true, true, null);
} else {
processMask(false, true, null);
}
}
});
this.maximum = new FloatSpinner(minMaxComp, SWT.NONE);
maximum.setIncrement(1d);
maximum.setEnabled(false);
maximum.setMinimum(Integer.MIN_VALUE);
maximum.setMaximum(Integer.MAX_VALUE);
maximum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) maximum.setDouble(getValue(image.getMax(), image.getMaxCut(), Integer.MAX_VALUE));
maximum.setToolTipText("Press enter to apply a full update of the mask.");
maximum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(true, false, null);
setLastActionRange(true);
}
});
maximum.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
processMask(isLastActionRange(), true, null);
}
}
});
final Button ignoreAlreadyMasked = new Button(minMaxComp, SWT.CHECK);
ignoreAlreadyMasked.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2,1));
ignoreAlreadyMasked.setText("Keep pixels aleady masked");
ignoreAlreadyMasked.setToolTipText("When using bounds, pixels already masked can be ignored and not checked for range.\nThis setting is ignored when removing the bounds mask.");
ignoreAlreadyMasked.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setIgnoreAlreadyMasked(ignoreAlreadyMasked.getSelection());
}
});
label = new Label(minMaxComp, SWT.NONE);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2,1));
label = new Label(minMaxComp, SWT.NONE);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1,1));
label.setText("Mask Color");
this.colorSelector = new ColorSelector(minMaxComp);
colorSelector.getButton().setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
if (image!=null) colorSelector.setColorValue(ColorUtility.getRGB(image.getNanBound().getColor()));
colorSelector.addListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
getImageTrace().setNanBound(new HistogramBound(Double.NaN, ColorUtility.getIntArray(colorSelector.getColorValue())));
getImageTrace().rehistogram();
}
});
final Group drawGroup = new Group(composite, SWT.SHADOW_NONE);
drawGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
drawGroup.setLayout(new GridLayout(3, false));
label = new Label(drawGroup, SWT.NONE);
GridData data = new GridData(SWT.LEFT, SWT.FILL, false, false);
label.setLayoutData(data);
label.setText("Mask using: ");
final Button directDraw = new Button(drawGroup, SWT.RADIO);
directDraw.setText("Direct draw");
directDraw.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
final Button regionDraw = new Button(drawGroup, SWT.RADIO);
regionDraw.setText("Regions");
regionDraw.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, false));
label = new Label(drawGroup, SWT.HORIZONTAL|SWT.SEPARATOR);
GridData gdata = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
gdata.verticalIndent=5;
label.setLayoutData(gdata);
final Composite drawContent = new Composite(drawGroup, SWT.NONE);
drawContent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
drawContent.setLayout(new StackLayout());
final Composite directComp = new Composite(drawContent, SWT.NONE);
directComp.setLayout(new GridLayout(1, false));
GridUtils.removeMargins(directComp);
this.directToolbar = new ToolBarManager(SWT.FLAT|SWT.RIGHT|SWT.WRAP);
createDirectToolbarActions(directToolbar);
Control tb = directToolbar.createControl(directComp);
tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
new Label(directComp, SWT.NONE);
final Label shiftLabel = new Label(directComp, SWT.WRAP);
shiftLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, true, false));
shiftLabel.setText("(Hold down the 'shift' key to draw lines.)");
new Label(directComp, SWT.NONE);
new Label(directComp, SWT.NONE);
final Button useThresh = new Button(directComp, SWT.CHECK);
useThresh.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
useThresh.setText("Use threshold on brush.");
final Composite threshComp = new Composite(directComp, SWT.NONE);
threshComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
threshComp.setLayout(new GridLayout(2, false));
final Label minThreshLabel = new Label(threshComp, SWT.NONE);
threshComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
minThreshLabel.setText("Minimum Threshold");
final FloatSpinner minThresh = new FloatSpinner(threshComp, SWT.NONE);
minThresh.setIncrement(1d);
minThresh.setMinimum(Integer.MIN_VALUE);
minThresh.setMaximum(Integer.MAX_VALUE);
minThresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) minThresh.setDouble(getValue(image.getMin(), image.getMinCut(), 0));
minThresh.setToolTipText("Press enter to set minimum threshold for brush.");
final Label maxThreshLabel = new Label(threshComp, SWT.NONE);
maxThreshLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
maxThreshLabel.setText("Maximum Threshold");
final FloatSpinner maxThresh = new FloatSpinner(threshComp, SWT.NONE);
maxThresh.setIncrement(1d);
maxThresh.setMinimum(Integer.MIN_VALUE);
maxThresh.setMaximum(Integer.MAX_VALUE);
maxThresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) maxThresh.setDouble(getValue(image.getMax(), image.getMaxCut(), Integer.MAX_VALUE));
maxThresh.setToolTipText("Press enter to set maximum threshold for brush.");
minThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
});
minThresh.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
}
});
maxThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
});
maxThresh.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
}
});
useThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
GridUtils.setVisible(threshComp, useThresh.getSelection());
PrecisionPoint thresh = useThresh.getSelection()
? new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble())
: null;
maskObject.setBrushThreshold(thresh);
threshComp.getParent().layout();
}
});
GridUtils.setVisible(threshComp, false);
// Regions
final Composite regionComp = new Composite(drawContent, SWT.NONE);
regionComp.setLayout(new GridLayout(1, false));
GridUtils.removeMargins(regionComp);
final ToolBarManager regionToolbar = new ToolBarManager(SWT.FLAT|SWT.RIGHT);
createMaskingRegionActions(regionToolbar);
tb = regionToolbar.createControl(regionComp);
tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
this.regionTable = new TableViewer(regionComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
regionTable.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
createColumns(regionTable);
regionTable.getTable().setLinesVisible(true);
regionTable.getTable().setHeaderVisible(true);
regionTable.getTable().addMouseListener(this);
getSite().setSelectionProvider(regionTable);
regionTable.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
final Collection<IRegion> regions = getPlottingSystem().getRegions();
if (regions==null || regions.isEmpty()) return new Object[]{"-"};
final List<IRegion> supported = new ArrayList<IRegion>(regions.size());
for (IRegion iRegion : regions) if (maskObject.isSupportedRegion(iRegion) &&
iRegion.isUserRegion()) {
supported.add(iRegion);
}
return supported.toArray(new IRegion[supported.size()]);
}
});
regionTable.setInput(new Object());
final Composite buttons = new Composite(drawGroup, SWT.BORDER);
buttons.setLayout(new GridLayout(2, false));
buttons.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 3, 1));
this.autoApply = new Button(buttons, SWT.CHECK);
autoApply.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 2, 1));
autoApply.setText("Automatically apply mask when something changes.");
autoApply.setSelection(Activator.getPlottingPreferenceStore().getBoolean(PlottingConstants.MASK_AUTO_APPLY));
this.apply = new Button(buttons, SWT.PUSH);
apply.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
apply.setImage(Activator.getImage("icons/apply.gif"));
apply.setText("Apply");
apply.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(isLastActionRange(), true, null);
}
});
apply.setEnabled(true);
autoApply.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_AUTO_APPLY, autoApply.getSelection());
apply.setEnabled(!autoApply.getSelection());
processMask();
}
});
final Button reset = new Button(buttons, SWT.PUSH);
reset.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
reset.setImage(Activator.getImage("icons/reset.gif"));
reset.setText("Reset");
reset.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resetMask();
}
});
createActions(getSite().getActionBars());
final StackLayout layout = (StackLayout)drawContent.getLayout();
layout.topControl = directComp;
directDraw.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_TYPE, "direct");
layout.topControl = directComp;
drawContent.layout();
ShapeType penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
ActionContributionItem item= ((ActionContributionItem)directToolbar.find(penShape.getId()));
if (item!=null) item.getAction().run();
setRegionsVisible(false);
}
});
regionDraw.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_TYPE, "region");
layout.topControl = regionComp;
drawContent.layout();
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(null);
setRegionsVisible(true);
}
});
String drawType = Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_DRAW_TYPE);
if (drawType!=null && !"".equals(drawType)) {
if ("direct".equals(drawType)) {
directDraw.setSelection(true);
layout.topControl = directComp;
ShapeType penShape = ShapeType.NONE;
if (Activator.getPlottingPreferenceStore().contains(PlottingConstants.MASK_PEN_SHAPE)) {
penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
}
ActionContributionItem item= ((ActionContributionItem)directToolbar.find(penShape.getId()));
if (item!=null) item.getAction().run();
} else if ("region".equals(drawType)) {
regionDraw.setSelection(true);
layout.topControl = regionComp;
}
}
scrollComp.setContent(composite);
scrollComp.setExpandVertical(true);
scrollComp.setExpandHorizontal(true);
scrollComp.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
Rectangle r = scrollComp.getClientArea();
scrollComp.setMinHeight(composite.computeSize(r.width, SWT.DEFAULT).y);
scrollComp.setMinWidth(composite.computeSize(SWT.DEFAULT, r.height).x);
}
});
}
| public void createControl(Composite parent) {
scrollComp = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
final Group composite = new Group(scrollComp, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
final IImageTrace image = getImageTrace();
if (image!=null) {
composite.setText("Masking '"+image.getName()+"'");
} else {
composite.setText("Masking ");
}
final Composite minMaxComp = new Composite(composite, SWT.NONE);
minMaxComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
minMaxComp.setLayout(new GridLayout(2, false));
Label label = new Label(minMaxComp, SWT.WRAP);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2,1));
label.setText("Create a mask, the mask can be saved and available in other tools.");
final CLabel warningMessage = new CLabel(minMaxComp, SWT.WRAP);
warningMessage.setText("Changing lower / upper can reset the mask and is not undoable.");
warningMessage.setToolTipText("The reset can occur because the algorithm which processes intensity values,\ndoes not know if the mask pixel should be unmasked or not.\nIt can only take into account intensity.\nTherefore it is best to define intensity masks first,\nbefore the custom masks using pen or region tools." );
warningMessage.setImage(Activator.getImage("icons/error.png"));
warningMessage.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2,1));
GridUtils.setVisible(warningMessage, false);
// Max and min
final Button minEnabled = new Button(minMaxComp, SWT.CHECK);
minEnabled.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
minEnabled.setText("Enable lower mask ");
minEnabled.setToolTipText("Enable the lower bound mask, removing pixels with lower intensity.");
this.minimum = new FloatSpinner(minMaxComp, SWT.NONE);
minimum.setIncrement(1d);
minimum.setEnabled(false);
minimum.setMinimum(Integer.MIN_VALUE);
minimum.setMaximum(Integer.MAX_VALUE);
minimum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) minimum.setDouble(getValue(image.getMin(), image.getMinCut(), 0));
minimum.setToolTipText("Press enter to apply a full update of the mask.");
minimum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(true, false, null);
setLastActionRange(true);
}
});
minimum.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
processMask(isLastActionRange(), true, null);
}
}
});
final Button maxEnabled = new Button(minMaxComp, SWT.CHECK);
maxEnabled.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
maxEnabled.setText("Enable upper mask ");
maxEnabled.setToolTipText("Enable the upper bound mask, removing pixels with higher intensity.");
minEnabled.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
minimum.setEnabled(minEnabled.getSelection());
GridUtils.setVisible(warningMessage, minEnabled.getSelection()||maxEnabled.getSelection());
warningMessage.getParent().getParent().layout();
if (!minEnabled.getSelection()) {
warningMessage.getParent().getParent().layout();
} else {
processMask(false, true, null);
}
}
});
maxEnabled.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maximum.setEnabled(maxEnabled.getSelection());
GridUtils.setVisible(warningMessage, minEnabled.getSelection()||maxEnabled.getSelection());
warningMessage.getParent().getParent().layout();
if (!maxEnabled.getSelection()) {
processMask(true, true, null);
} else {
processMask(false, true, null);
}
}
});
this.maximum = new FloatSpinner(minMaxComp, SWT.NONE);
maximum.setIncrement(1d);
maximum.setEnabled(false);
maximum.setMinimum(Integer.MIN_VALUE);
maximum.setMaximum(Integer.MAX_VALUE);
maximum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) maximum.setDouble(getValue(image.getMax(), image.getMaxCut(), Integer.MAX_VALUE));
maximum.setToolTipText("Press enter to apply a full update of the mask.");
maximum.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(true, false, null);
setLastActionRange(true);
}
});
maximum.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
processMask(isLastActionRange(), true, null);
}
}
});
final Button ignoreAlreadyMasked = new Button(minMaxComp, SWT.CHECK);
ignoreAlreadyMasked.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2,1));
ignoreAlreadyMasked.setText("Keep pixels aleady masked");
ignoreAlreadyMasked.setToolTipText("When using bounds, pixels already masked can be ignored and not checked for range.\nThis setting is ignored when removing the bounds mask.");
ignoreAlreadyMasked.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setIgnoreAlreadyMasked(ignoreAlreadyMasked.getSelection());
}
});
label = new Label(minMaxComp, SWT.NONE);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2,1));
label = new Label(minMaxComp, SWT.NONE);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1,1));
label.setText("Mask Color");
this.colorSelector = new ColorSelector(minMaxComp);
colorSelector.getButton().setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1,1));
if (image!=null) colorSelector.setColorValue(ColorUtility.getRGB(image.getNanBound().getColor()));
colorSelector.addListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
getImageTrace().setNanBound(new HistogramBound(Double.NaN, ColorUtility.getIntArray(colorSelector.getColorValue())));
getImageTrace().rehistogram();
}
});
final Group drawGroup = new Group(composite, SWT.SHADOW_NONE);
drawGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
drawGroup.setLayout(new GridLayout(3, false));
label = new Label(drawGroup, SWT.NONE);
GridData data = new GridData(SWT.LEFT, SWT.FILL, false, false);
label.setLayoutData(data);
label.setText("Mask using: ");
final Button directDraw = new Button(drawGroup, SWT.RADIO);
directDraw.setText("Direct draw");
directDraw.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false));
final Button regionDraw = new Button(drawGroup, SWT.RADIO);
regionDraw.setText("Regions");
regionDraw.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, false));
label = new Label(drawGroup, SWT.HORIZONTAL|SWT.SEPARATOR);
GridData gdata = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
gdata.verticalIndent=5;
label.setLayoutData(gdata);
final Composite drawContent = new Composite(drawGroup, SWT.NONE);
drawContent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
drawContent.setLayout(new StackLayout());
final Composite directComp = new Composite(drawContent, SWT.NONE);
directComp.setLayout(new GridLayout(1, false));
GridUtils.removeMargins(directComp);
this.directToolbar = new ToolBarManager(SWT.FLAT|SWT.RIGHT|SWT.WRAP);
createDirectToolbarActions(directToolbar);
Control tb = directToolbar.createControl(directComp);
tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
new Label(directComp, SWT.NONE);
final Label shiftLabel = new Label(directComp, SWT.WRAP);
shiftLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, true, false));
shiftLabel.setText("(Hold down the 'shift' key to draw lines.)");
new Label(directComp, SWT.NONE);
new Label(directComp, SWT.NONE);
final Button useThresh = new Button(directComp, SWT.CHECK);
useThresh.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
useThresh.setText("Use threshold on brush.");
final Composite threshComp = new Composite(directComp, SWT.NONE);
threshComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
threshComp.setLayout(new GridLayout(2, false));
final Label minThreshLabel = new Label(threshComp, SWT.NONE);
threshComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
minThreshLabel.setText("Minimum Threshold");
final FloatSpinner minThresh = new FloatSpinner(threshComp, SWT.NONE);
minThresh.setIncrement(1d);
minThresh.setMinimum(Integer.MIN_VALUE);
minThresh.setMaximum(Integer.MAX_VALUE);
minThresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) minThresh.setDouble(getValue(image.getMin(), image.getMinCut(), 0));
minThresh.setToolTipText("Press enter to set minimum threshold for brush.");
final Label maxThreshLabel = new Label(threshComp, SWT.NONE);
maxThreshLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
maxThreshLabel.setText("Maximum Threshold");
final FloatSpinner maxThresh = new FloatSpinner(threshComp, SWT.NONE);
maxThresh.setIncrement(1d);
maxThresh.setMinimum(Integer.MIN_VALUE);
maxThresh.setMaximum(Integer.MAX_VALUE);
maxThresh.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
if (image!=null) maxThresh.setDouble(getValue(image.getMax(), image.getMaxCut(), Integer.MAX_VALUE));
maxThresh.setToolTipText("Press enter to set maximum threshold for brush.");
minThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
});
minThresh.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
}
});
maxThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
});
maxThresh.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.character=='\n' || e.character=='\r') {
maskObject.setBrushThreshold(new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble()));
}
}
});
useThresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
GridUtils.setVisible(threshComp, useThresh.getSelection());
PrecisionPoint thresh = useThresh.getSelection()
? new PrecisionPoint(minThresh.getDouble(), maxThresh.getDouble())
: null;
maskObject.setBrushThreshold(thresh);
threshComp.getParent().layout();
}
});
GridUtils.setVisible(threshComp, false);
// Regions
final Composite regionComp = new Composite(drawContent, SWT.NONE);
regionComp.setLayout(new GridLayout(1, false));
GridUtils.removeMargins(regionComp);
final ToolBarManager regionToolbar = new ToolBarManager(SWT.FLAT|SWT.RIGHT);
createMaskingRegionActions(regionToolbar);
tb = regionToolbar.createControl(regionComp);
tb.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
this.regionTable = new TableViewer(regionComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
regionTable.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
createColumns(regionTable);
regionTable.getTable().setLinesVisible(true);
regionTable.getTable().setHeaderVisible(true);
regionTable.getTable().addMouseListener(this);
getSite().setSelectionProvider(regionTable);
regionTable.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
final Collection<IRegion> regions = getPlottingSystem().getRegions();
if (regions==null || regions.isEmpty()) return new Object[]{"-"};
final List<IRegion> supported = new ArrayList<IRegion>(regions.size());
for (IRegion iRegion : regions) if (maskObject.isSupportedRegion(iRegion) &&
iRegion.isUserRegion()) {
supported.add(iRegion);
}
return supported.toArray(new IRegion[supported.size()]);
}
});
regionTable.setInput(new Object());
final Composite buttons = new Composite(drawGroup, SWT.BORDER);
buttons.setLayout(new GridLayout(2, false));
buttons.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 3, 1));
this.autoApply = new Button(buttons, SWT.CHECK);
autoApply.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 2, 1));
autoApply.setText("Automatically apply mask when something changes.");
autoApply.setSelection(Activator.getPlottingPreferenceStore().getBoolean(PlottingConstants.MASK_AUTO_APPLY));
this.apply = new Button(buttons, SWT.PUSH);
apply.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
apply.setImage(Activator.getImage("icons/apply.gif"));
apply.setText("Apply");
apply.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
processMask(isLastActionRange(), true, null);
}
});
apply.setEnabled(true);
autoApply.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_AUTO_APPLY, autoApply.getSelection());
apply.setEnabled(!autoApply.getSelection());
processMask();
}
});
final Button reset = new Button(buttons, SWT.PUSH);
reset.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
reset.setImage(Activator.getImage("icons/reset.gif"));
reset.setText("Reset");
reset.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resetMask();
}
});
createActions(getSite().getActionBars());
final StackLayout layout = (StackLayout)drawContent.getLayout();
layout.topControl = directComp;
directDraw.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_TYPE, "direct");
layout.topControl = directComp;
drawContent.layout();
ShapeType penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
ActionContributionItem item= ((ActionContributionItem)directToolbar.find(penShape.getId()));
if (item!=null) item.getAction().run();
setRegionsVisible(false);
}
});
regionDraw.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Activator.getPlottingPreferenceStore().setValue(PlottingConstants.MASK_DRAW_TYPE, "region");
layout.topControl = regionComp;
drawContent.layout();
((AbstractPlottingSystem)getPlottingSystem()).setSelectedCursor(null);
setRegionsVisible(true);
}
});
String drawType = Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_DRAW_TYPE);
if (drawType!=null && !"".equals(drawType)) {
if ("direct".equals(drawType)) {
directDraw.setSelection(true);
layout.topControl = directComp;
ShapeType penShape = ShapeType.NONE;
if (Activator.getPlottingPreferenceStore().contains(PlottingConstants.MASK_PEN_SHAPE)) {
penShape = ShapeType.valueOf(Activator.getPlottingPreferenceStore().getString(PlottingConstants.MASK_PEN_SHAPE));
}
ActionContributionItem item= ((ActionContributionItem)directToolbar.find(penShape.getId()));
if (item!=null) item.getAction().run();
} else if ("region".equals(drawType)) {
regionDraw.setSelection(true);
layout.topControl = regionComp;
}
}
scrollComp.setContent(composite);
scrollComp.setExpandVertical(true);
scrollComp.setExpandHorizontal(true);
scrollComp.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
Rectangle r = scrollComp.getClientArea();
scrollComp.setMinHeight(composite.computeSize(r.width, SWT.DEFAULT).y);
scrollComp.setMinWidth(composite.computeSize(SWT.DEFAULT, r.height).x);
}
});
}
|
diff --git a/sitebricks/src/main/java/com/google/sitebricks/compiler/HtmlParser.java b/sitebricks/src/main/java/com/google/sitebricks/compiler/HtmlParser.java
index e2c7c2a..1ede460 100644
--- a/sitebricks/src/main/java/com/google/sitebricks/compiler/HtmlParser.java
+++ b/sitebricks/src/main/java/com/google/sitebricks/compiler/HtmlParser.java
@@ -1,450 +1,450 @@
package com.google.sitebricks.compiler;
import com.google.common.collect.ImmutableSet;
import com.google.sitebricks.rendering.Strings;
import org.apache.commons.lang.Validate;
import org.jsoup.nodes.*;
import org.jsoup.parser.Tag;
import org.jsoup.parser.TokenQueue;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
/**
Parses HTML into a List<{@link org.jsoup.nodes.Node}>
this is a relaxed version of Jonathan Hedley's {@link org.jsoup.parser.Parser}
*/
public class HtmlParser {
private static final ImmutableSet<String> closingOptional = ImmutableSet
.of("a", "form", "label", "dt", "dd", "li",
"thead", "tfoot", "tbody", "colgroup", "tr", "th", "td");
private static final ImmutableSet<String> headTags = ImmutableSet
.of ("base", "script","noscript", "link", "meta", "title", "style", "object");
private static final String SQ = "'";
private static final String DQ = "\"";
private static final Tag htmlTag = Tag.valueOf("html");
private static final Tag headTag = Tag.valueOf("head");
private static final Tag bodyTag = Tag.valueOf("body");
private static final Tag titleTag = Tag.valueOf("title");
private static final Tag textareaTag = Tag.valueOf("textarea");
// private final ArrayList<Node> soup = new ArrayList<Node>();
// private final LinkedList<Node> soup = new LinkedList<Node>();
private final LinkedList<Node> stack = new LinkedList<Node>();
// TODO - LineCountingTokenQueue
static final Pattern LINE_SEPARATOR = Pattern.compile("(\\r\\n|\\n|\\r|\\u0085|\\u2028|\\u2029)");
static final String LINE_NUMBER_ATTRIBUTE = "_linecount";
private final TokenQueue tq;
private String baseUri = "";
private Element _html=null;
private Element _head=null;
private Element _body=null;
private AnnotationNode pendingAnnotation=null;
private int linecount = 0;
static final ImmutableSet<String> SKIP_ATTR = ImmutableSet.of(LINE_NUMBER_ATTRIBUTE,
AnnotationNode.ANNOTATION, AnnotationNode.ANNOTATION_KEY, AnnotationNode.ANNOTATION_CONTENT);
private HtmlParser(String html) {
Validate.notNull(html);
tq = new TokenQueue(html);
}
/**
Parse HTML into List<Node>
@param html HTML to parse
*/
public static List<Node> parse(String html) {
HtmlParser parser = new HtmlParser(html);
return parser.parse();
}
/* Parse a fragment of HTML into the {@code body} of a Document.
@param bodyHtml fragment of HTML
@param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs.
@return Document, with empty head, and HTML parsed into body
*/
// public static Document parseBodyFragment(String bodyHtml, String baseUri) {
// HtmlParser parser = new HtmlParser(bodyHtml, true);
// return parser.parse();
// }
private List<Node> parse() {
while (!tq.isEmpty()) {
if (tq.matches("<!--")) {
parseComment();
} else if (tq.matches("<![CDATA[")) {
parseCdata();
} else if (tq.matches("<?") || tq.matches("<!")) {
parseXmlDecl();
} else if (tq.matches("</")) {
parseEndTag();
} else if (tq.matches("<")) {
parseStartTag();
} else {
parseTextNode();
}
}
return stack;
}
private void parseComment() {
tq.consume("<!--");
String data = tq.chompTo("->");
if (data.endsWith("-")) // i.e. was -->
data = data.substring(0, data.length()-1);
Comment comment = new Comment(data, baseUri);
annotate(comment); // TODO - should annotations even apply to comments?
lines(comment, data);
add(comment);
}
private void parseXmlDecl() {
tq.consume("<");
Character firstChar = tq.consume(); // <? or <!, from initial match.
boolean procInstr = firstChar.toString().equals("!");
String data = tq.chompTo(">");
XmlDeclaration decl = new XmlDeclaration(data, baseUri, procInstr);
annotate(decl); // TODO - should annotations even apply to declarations?
lines(decl, data);
add(decl);
}
private void parseEndTag() {
tq.consume("</");
String tagName = tq.consumeWord();
tq.chompTo(">");
if (!Strings.empty(tagName)) {
Tag tag = Tag.valueOf(tagName);
popStackToClose(tag);
}
}
private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
- if (!Strings.empty(tagName)) { // doesn't look like a start tag after all; put < back on stack and handle as text
+ if (Strings.empty(tagName)) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
// TODO - option to create elements without indent
Element child = new Element(tag, baseUri, attributes);
annotate(child);
lines(child, "");
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
Node dataNode;
// want to show as text, but not contain inside tags (so not a data tag?)
if (tag.equals(titleTag) || tag.equals(textareaTag))
dataNode = TextNode.createFromEncoded(data, baseUri);
else // data not encoded but raw (for " in script)
dataNode = new DataNode(data, baseUri);
if (pendingAnnotation != null)
pendingAnnotation.apply(dataNode);
lines(dataNode, data);
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (!Strings.empty(href)) { // ignore <base target> etc
baseUri = href;
// TODO - consider updating baseUri for relevant elements in the stack, eg rebase(stack, uri)
// doc.get().setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
addChildToParent(child, isEmptyElement);
}
private Attribute parseAttribute() {
whitespace();
String key = tq.consumeAttributeKey();
String value = "";
whitespace();
if (tq.matchChomp("=")) {
whitespace();
if (tq.matchChomp(SQ)) {
value = tq.chompTo(SQ);
} else if (tq.matchChomp(DQ)) {
value = tq.chompTo(DQ);
} else {
StringBuilder valueAccum = new StringBuilder();
// no ' or " to look for, so scan to end tag or space (or end of stream)
while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) {
valueAccum.append(tq.consume());
}
value = valueAccum.toString();
}
whitespace();
}
if (!Strings.empty(key))
return Attribute.createFromEncoded(key, value);
else {
tq.consume(); // unknown char, keep popping so not get stuck
return null;
}
}
private void parseTextNode() {
String text = tq.consumeTo("<");
String annotationText = AnnotationParser.readAnnotation(text);
text = AnnotationParser.stripAnnotation(text);
if (text.length()>0) {
TextNode textNode = TextNode.createFromEncoded(text, baseUri);
// if (pendingAnnotation != null) { pendingAnnotation.apply(textNode); }
lines(textNode, text);
add(textNode);
}
if (null != annotationText) {
AnnotationNode annotation = new AnnotationNode(annotationText);
lines(annotation, annotationText);
add(annotation);
}
}
private void parseCdata() {
tq.consume("<![CDATA[");
String rawText = tq.chompTo("]]>");
TextNode textNode = new TextNode(rawText, baseUri); // constructor does not escape
if (pendingAnnotation != null)
pendingAnnotation.apply(textNode);
lines(textNode, rawText);
add(textNode);
}
private Element addChildToParent(Element child, boolean isEmptyElement) {
Element parent = popStackToSuitableContainer(child.tag());
if (parent != null)
parent.appendChild(child);
if (!isEmptyElement && !child.tag().isData())
stack.addLast(child);
return parent;
}
private boolean stackHasValidParent(Tag childTag) {
if (stack.size() == 1 && childTag.equals(htmlTag))
return true; // root is valid for html node
for (int i = stack.size() -1; i >= 0; i--) {
Node n = stack.get(i);
if (n instanceof Element)
return true;
}
return false;
}
private Element popStackToSuitableContainer(Tag tag) {
while (!stack.isEmpty() && !(stack.getLast() instanceof XmlDeclaration)) {
Node lastNode = stack.getLast();
if (lastNode instanceof Element) {
Element last = (Element) lastNode;
if (canContain(last.tag(), tag))
return last;
else
stack.removeLast();
}
}
return null;
}
private Element popStackToClose(Tag tag) {
// first check to see if stack contains this tag; if so pop to there, otherwise ignore
int counter = 0;
Element elToClose = null;
for (int i = stack.size() -1; i > 0; i--) {
counter++;
Node n = stack.get(i);
if (n instanceof Element) {
Element el = (Element) n;
Tag elTag = el.tag();
if (elTag.equals(bodyTag) || elTag.equals(headTag) || elTag.equals(htmlTag)) { // once in body, don't close past body
break;
} else if (elTag.equals(tag)) {
elToClose = el;
break;
}
}
}
if (elToClose != null) {
for (int i = 0; i < counter; i++) {
stack.removeLast();
}
}
return elToClose;
}
private <N extends Node> void add(N n) {
Node last = null;
if (stack.size()==0) {
if (n instanceof XmlDeclaration) {
// only add the first/outermost doctype
stack.add(n);
return;
}
} else {
last = stack.getLast();
}
// TODO - optionally put the AnnotationNode on the stack
if (n instanceof AnnotationNode) {
pendingAnnotation=(AnnotationNode) n;
return;
}
// else if (null != pendingAnnotation) {
// pendingAnnotation.apply(n);
// }
if (n instanceof Element) {
Element en = (Element) n;
if (en.tag().equals(htmlTag) && (null == _html))
_html = en;
else if (en.tag().equals(htmlTag) && (null != _html))
for (Node cat: en.childNodes()) _html.appendChild(cat);
else if (en.tag().equals(headTag) && (null == _head))
_head = en;
else if (en.tag().equals(headTag) && (null != _head))
for (Node cat: en.childNodes()) _head.appendChild(cat);
else if (en.tag().equals(bodyTag) && (null == _body))
_body = en;
else if (en.tag().equals(bodyTag) && (null != _body))
for (Node cat: en.childNodes()) _body.appendChild(cat);
}
if (last == null)
stack.add(n);
else if (last instanceof Element) {
((Element)last).appendChild(n);
}
}
// from jsoup.parser.Tag
/**
Test if this tag, the prospective parent, can accept the proposed child.
@param child potential child tag.
@return true if this can contain child.
*/
boolean canContain(Tag parent, Tag child) {
Validate.notNull(child);
if (child.isBlock() && !parent.canContainBlock())
return false;
if (!child.isBlock() && parent.isData())
return false;
if (closingOptional.contains(parent.getName()) && parent.getName().equals(child.getName()))
return false;
if (parent.isEmpty() || parent.isData())
return false;
// head can only contain a few. if more than head in here, modify to have a list of valids
// TODO: (could solve this with walk for ancestor)
if (parent.getName().equals("head")) {
if (headTags.contains(child.getName()))
return true;
else
return false;
}
// dt and dd (in dl)
if (parent.getName().equals("dt") && child.getName().equals("dd"))
return false;
if (parent.getName().equals("dd") && child.getName().equals("dt"))
return false;
return true;
}
// TODO - LineCountingTokenQueue
// these line numbers are an inaccurate estimate
private void lines (Node node, String data) {
linecount += (LINE_SEPARATOR.split(data).length);
node.attr(LINE_NUMBER_ATTRIBUTE, String.valueOf(linecount));
}
private void whitespace() {
if (tq.peek().equals(Character.LINE_SEPARATOR)) linecount++;
tq.consumeWhitespace();
}
private void annotate(Node n) {
if (null != pendingAnnotation) {
pendingAnnotation.apply(n);
pendingAnnotation = null;
}
}
}
| true | true | private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
if (!Strings.empty(tagName)) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
// TODO - option to create elements without indent
Element child = new Element(tag, baseUri, attributes);
annotate(child);
lines(child, "");
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
Node dataNode;
// want to show as text, but not contain inside tags (so not a data tag?)
if (tag.equals(titleTag) || tag.equals(textareaTag))
dataNode = TextNode.createFromEncoded(data, baseUri);
else // data not encoded but raw (for " in script)
dataNode = new DataNode(data, baseUri);
if (pendingAnnotation != null)
pendingAnnotation.apply(dataNode);
lines(dataNode, data);
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (!Strings.empty(href)) { // ignore <base target> etc
baseUri = href;
// TODO - consider updating baseUri for relevant elements in the stack, eg rebase(stack, uri)
// doc.get().setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
addChildToParent(child, isEmptyElement);
}
| private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
if (Strings.empty(tagName)) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
// TODO - option to create elements without indent
Element child = new Element(tag, baseUri, attributes);
annotate(child);
lines(child, "");
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
Node dataNode;
// want to show as text, but not contain inside tags (so not a data tag?)
if (tag.equals(titleTag) || tag.equals(textareaTag))
dataNode = TextNode.createFromEncoded(data, baseUri);
else // data not encoded but raw (for " in script)
dataNode = new DataNode(data, baseUri);
if (pendingAnnotation != null)
pendingAnnotation.apply(dataNode);
lines(dataNode, data);
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (!Strings.empty(href)) { // ignore <base target> etc
baseUri = href;
// TODO - consider updating baseUri for relevant elements in the stack, eg rebase(stack, uri)
// doc.get().setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
addChildToParent(child, isEmptyElement);
}
|
diff --git a/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java b/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java
index 53a3115e8..910c2b156 100644
--- a/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java
+++ b/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java
@@ -1,282 +1,285 @@
/*
* ScriptLauncher.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2009, Duraspace. 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 Duraspace 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
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.launcher;
import org.dspace.core.ConfigurationManager;
import org.dspace.servicemanager.DSpaceKernelImpl;
import org.dspace.servicemanager.DSpaceKernelInit;
import org.dspace.services.RequestService;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import java.util.List;
import java.lang.reflect.Method;
/**
* A DSpace script launcher.
*
* @author Stuart Lewis
* @author Mark Diggory
*/
public class ScriptLauncher
{
/** The service manager kernel */
private static transient DSpaceKernelImpl kernelImpl;
/**
* Execute the DSpace script launcher
*
* @param args Any parameters required to be passed to the scripts it executes
* @throws Exception
*/
public static void main(String[] args)
{
// Check that there is at least one argument
if (args.length < 1)
{
System.err.println("You must provide at least one command argument");
display();
System.exit(1);
}
// Initalise the service manager kernel
try {
kernelImpl = DSpaceKernelInit.getKernel(null);
if (!kernelImpl.isRunning())
{
kernelImpl.start(ConfigurationManager.getProperty("dspace.dir"));
}
} catch (Exception e)
{
// Failed to start so destroy it and log and throw an exception
try
{
kernelImpl.destroy();
}
catch (Exception e1)
{
// Nothing to do
}
String message = "Failure during filter init: " + e.getMessage();
System.err.println(message + ":" + e);
throw new RuntimeException(message, e);
}
// Parse the configuration file looking for the command entered
Document doc = getConfig();
String request = args[0];
Element root = doc.getRootElement();
List<Element> commands = root.getChildren("command");
for (Element command : commands)
{
if (request.equalsIgnoreCase(command.getChild("name").getValue()))
{
// Run each step
List<Element> steps = command.getChildren("step");
for (Element step : steps)
{
// Instantiate the class
Class target = null;
String className = step.getChild("class").getValue();
try
{
target = Class.forName(className,
true,
Thread.currentThread().getContextClassLoader());
}
catch (ClassNotFoundException e)
{
System.err.println("Error in launcher.xml: Invalid class name: " + className);
System.exit(1);
}
// Strip the leading argument from the args, and add the arguments
// Set <passargs>false</passargs> if the arguments should not be passed on
String[] useargs = args.clone();
Class[] argTypes = {useargs.getClass()};
boolean passargs = true;
if ((step.getAttribute("passuserargs") != null) &&
("false".equalsIgnoreCase(step.getAttribute("passuserargs").getValue())))
{
passargs = false;
}
if ((args.length == 1) || (!passargs))
{
useargs = new String[0];
}
else
{
String[] argsnew = new String[useargs.length - 1];
for (int i = 1; i < useargs.length; i++)
{
argsnew[i - 1] = useargs[i];
}
useargs = argsnew;
}
// Add any extra properties
List<Element> bits = step.getChildren("argument");
if (step.getChild("argument") != null)
{
String[] argsnew = new String[useargs.length + bits.size()];
int i = 0;
for (Element arg : bits)
{
argsnew[i++] = arg.getValue();
}
for (; i < bits.size() + useargs.length; i++)
{
argsnew[i] = useargs[i - bits.size()];
}
useargs = argsnew;
}
// Establish the request service startup
RequestService requestService = kernelImpl.getServiceManager().getServiceByName(RequestService.class.getName(), RequestService.class);
if (requestService == null) {
throw new IllegalStateException("Could not get the DSpace RequestService to start the request transaction");
}
// Establish a request related to the current session
// that will trigger the various request listeners
requestService.startRequest();
// Run the main() method
try
{
Object[] arguments = {useargs};
// Useful for debugging, so left in the code...
/**System.out.print("About to execute: " + className);
for (String param : useargs)
{
System.out.print(" " + param);
}
System.out.println("");**/
Method main = target.getMethod("main", argTypes);
Object output = main.invoke(null, arguments);
// ensure we close out the request (happy request)
requestService.endRequest(null);
}
catch (Exception e)
{
// Failure occurred in the request so we destroy it
requestService.endRequest(e);
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
- System.err.println("Exception: " + e.getMessage());
+ // Exceptions from the script are reported as a 'cause'
+ Throwable cause = e.getCause();
+ System.err.println("Exception: " + cause.getMessage());
+ cause.printStackTrace();
System.exit(1);
}
}
// Destroy the service kernel
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
System.exit(0);
}
}
// Destroy the service kernel if it is still alive
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
// The command wasn't found
System.err.println("Command not found: " + args[0]);
display();
System.exit(1);
}
/**
* Load the launcher configuration file
*
* @return The XML configuration file Document
*/
private static Document getConfig()
{
// Load the launcher configuration file
String config = ConfigurationManager.getProperty("dspace.dir") +
System.getProperty("file.separator") + "config" +
System.getProperty("file.separator") + "launcher.xml";
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = null;
try
{
doc = saxBuilder.build(config);
}
catch (Exception e)
{
System.err.println("Unable to load the launcher configuration file: [dspace]/config/launcher.xml");
System.err.println(e.getMessage());
System.exit(1);
}
return doc;
}
/**
* Display the commands that the current launcher config file knows about
*/
private static void display()
{
Document doc = getConfig();
List<Element> commands = doc.getRootElement().getChildren("command");
System.out.println("Usage: dspace [command-name] {parameters}");
for (Element command : commands)
{
System.out.println(" - " + command.getChild("name").getValue() +
": " + command.getChild("description").getValue());
}
}
}
| true | true | public static void main(String[] args)
{
// Check that there is at least one argument
if (args.length < 1)
{
System.err.println("You must provide at least one command argument");
display();
System.exit(1);
}
// Initalise the service manager kernel
try {
kernelImpl = DSpaceKernelInit.getKernel(null);
if (!kernelImpl.isRunning())
{
kernelImpl.start(ConfigurationManager.getProperty("dspace.dir"));
}
} catch (Exception e)
{
// Failed to start so destroy it and log and throw an exception
try
{
kernelImpl.destroy();
}
catch (Exception e1)
{
// Nothing to do
}
String message = "Failure during filter init: " + e.getMessage();
System.err.println(message + ":" + e);
throw new RuntimeException(message, e);
}
// Parse the configuration file looking for the command entered
Document doc = getConfig();
String request = args[0];
Element root = doc.getRootElement();
List<Element> commands = root.getChildren("command");
for (Element command : commands)
{
if (request.equalsIgnoreCase(command.getChild("name").getValue()))
{
// Run each step
List<Element> steps = command.getChildren("step");
for (Element step : steps)
{
// Instantiate the class
Class target = null;
String className = step.getChild("class").getValue();
try
{
target = Class.forName(className,
true,
Thread.currentThread().getContextClassLoader());
}
catch (ClassNotFoundException e)
{
System.err.println("Error in launcher.xml: Invalid class name: " + className);
System.exit(1);
}
// Strip the leading argument from the args, and add the arguments
// Set <passargs>false</passargs> if the arguments should not be passed on
String[] useargs = args.clone();
Class[] argTypes = {useargs.getClass()};
boolean passargs = true;
if ((step.getAttribute("passuserargs") != null) &&
("false".equalsIgnoreCase(step.getAttribute("passuserargs").getValue())))
{
passargs = false;
}
if ((args.length == 1) || (!passargs))
{
useargs = new String[0];
}
else
{
String[] argsnew = new String[useargs.length - 1];
for (int i = 1; i < useargs.length; i++)
{
argsnew[i - 1] = useargs[i];
}
useargs = argsnew;
}
// Add any extra properties
List<Element> bits = step.getChildren("argument");
if (step.getChild("argument") != null)
{
String[] argsnew = new String[useargs.length + bits.size()];
int i = 0;
for (Element arg : bits)
{
argsnew[i++] = arg.getValue();
}
for (; i < bits.size() + useargs.length; i++)
{
argsnew[i] = useargs[i - bits.size()];
}
useargs = argsnew;
}
// Establish the request service startup
RequestService requestService = kernelImpl.getServiceManager().getServiceByName(RequestService.class.getName(), RequestService.class);
if (requestService == null) {
throw new IllegalStateException("Could not get the DSpace RequestService to start the request transaction");
}
// Establish a request related to the current session
// that will trigger the various request listeners
requestService.startRequest();
// Run the main() method
try
{
Object[] arguments = {useargs};
// Useful for debugging, so left in the code...
/**System.out.print("About to execute: " + className);
for (String param : useargs)
{
System.out.print(" " + param);
}
System.out.println("");**/
Method main = target.getMethod("main", argTypes);
Object output = main.invoke(null, arguments);
// ensure we close out the request (happy request)
requestService.endRequest(null);
}
catch (Exception e)
{
// Failure occurred in the request so we destroy it
requestService.endRequest(e);
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
System.err.println("Exception: " + e.getMessage());
System.exit(1);
}
}
// Destroy the service kernel
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
System.exit(0);
}
}
// Destroy the service kernel if it is still alive
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
// The command wasn't found
System.err.println("Command not found: " + args[0]);
display();
System.exit(1);
}
| public static void main(String[] args)
{
// Check that there is at least one argument
if (args.length < 1)
{
System.err.println("You must provide at least one command argument");
display();
System.exit(1);
}
// Initalise the service manager kernel
try {
kernelImpl = DSpaceKernelInit.getKernel(null);
if (!kernelImpl.isRunning())
{
kernelImpl.start(ConfigurationManager.getProperty("dspace.dir"));
}
} catch (Exception e)
{
// Failed to start so destroy it and log and throw an exception
try
{
kernelImpl.destroy();
}
catch (Exception e1)
{
// Nothing to do
}
String message = "Failure during filter init: " + e.getMessage();
System.err.println(message + ":" + e);
throw new RuntimeException(message, e);
}
// Parse the configuration file looking for the command entered
Document doc = getConfig();
String request = args[0];
Element root = doc.getRootElement();
List<Element> commands = root.getChildren("command");
for (Element command : commands)
{
if (request.equalsIgnoreCase(command.getChild("name").getValue()))
{
// Run each step
List<Element> steps = command.getChildren("step");
for (Element step : steps)
{
// Instantiate the class
Class target = null;
String className = step.getChild("class").getValue();
try
{
target = Class.forName(className,
true,
Thread.currentThread().getContextClassLoader());
}
catch (ClassNotFoundException e)
{
System.err.println("Error in launcher.xml: Invalid class name: " + className);
System.exit(1);
}
// Strip the leading argument from the args, and add the arguments
// Set <passargs>false</passargs> if the arguments should not be passed on
String[] useargs = args.clone();
Class[] argTypes = {useargs.getClass()};
boolean passargs = true;
if ((step.getAttribute("passuserargs") != null) &&
("false".equalsIgnoreCase(step.getAttribute("passuserargs").getValue())))
{
passargs = false;
}
if ((args.length == 1) || (!passargs))
{
useargs = new String[0];
}
else
{
String[] argsnew = new String[useargs.length - 1];
for (int i = 1; i < useargs.length; i++)
{
argsnew[i - 1] = useargs[i];
}
useargs = argsnew;
}
// Add any extra properties
List<Element> bits = step.getChildren("argument");
if (step.getChild("argument") != null)
{
String[] argsnew = new String[useargs.length + bits.size()];
int i = 0;
for (Element arg : bits)
{
argsnew[i++] = arg.getValue();
}
for (; i < bits.size() + useargs.length; i++)
{
argsnew[i] = useargs[i - bits.size()];
}
useargs = argsnew;
}
// Establish the request service startup
RequestService requestService = kernelImpl.getServiceManager().getServiceByName(RequestService.class.getName(), RequestService.class);
if (requestService == null) {
throw new IllegalStateException("Could not get the DSpace RequestService to start the request transaction");
}
// Establish a request related to the current session
// that will trigger the various request listeners
requestService.startRequest();
// Run the main() method
try
{
Object[] arguments = {useargs};
// Useful for debugging, so left in the code...
/**System.out.print("About to execute: " + className);
for (String param : useargs)
{
System.out.print(" " + param);
}
System.out.println("");**/
Method main = target.getMethod("main", argTypes);
Object output = main.invoke(null, arguments);
// ensure we close out the request (happy request)
requestService.endRequest(null);
}
catch (Exception e)
{
// Failure occurred in the request so we destroy it
requestService.endRequest(e);
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
// Exceptions from the script are reported as a 'cause'
Throwable cause = e.getCause();
System.err.println("Exception: " + cause.getMessage());
cause.printStackTrace();
System.exit(1);
}
}
// Destroy the service kernel
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
System.exit(0);
}
}
// Destroy the service kernel if it is still alive
if (kernelImpl != null)
{
kernelImpl.destroy();
kernelImpl = null;
}
// The command wasn't found
System.err.println("Command not found: " + args[0]);
display();
System.exit(1);
}
|
diff --git a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/edit/InlineCellEditController.java b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/edit/InlineCellEditController.java
index 5e45ca1c..4317b050 100644
--- a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/edit/InlineCellEditController.java
+++ b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/edit/InlineCellEditController.java
@@ -1,154 +1,154 @@
/*******************************************************************************
* Copyright (c) 2012 Original authors and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Original authors and others - initial API and implementation
******************************************************************************/
package org.eclipse.nebula.widgets.nattable.edit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.edit.editor.ICellEditor;
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
import org.eclipse.nebula.widgets.nattable.layer.ILayerListener;
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.widget.EditModeEnum;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* Controls edit behavior when a cell is being edited in place where it is
* normally displayed in the NatTable. An edit control will be rendered on top
* of the of the cell to be edited and will handle the edit behavior.
*/
public class InlineCellEditController {
private static Map<ILayer, ILayerListener> layerListenerMap = new HashMap<ILayer, ILayerListener>();
public static boolean editCellInline(ILayerCell cell, Character initialEditValue, final Composite parent, IConfigRegistry configRegistry) {
try {
ActiveCellEditor.commit();
final List<String> configLabels = cell.getConfigLabels().getLabels();
Rectangle cellBounds = cell.getBounds();
ILayer layer = cell.getLayer();
int columnPosition = layer.getColumnPositionByX(cellBounds.x);
int rowPosition = layer.getRowPositionByY(cellBounds.y);
boolean editable = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, DisplayMode.EDIT, configLabels).isEditable(cell, configRegistry);
if (!editable) {
return false;
}
ICellEditor cellEditor = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITOR, DisplayMode.EDIT, configLabels);
ICellEditHandler editHandler = new SingleEditHandler(
cellEditor,
layer,
columnPosition,
rowPosition);
final Rectangle editorBounds = layer.getLayerPainter().adjustCellBounds(columnPosition, rowPosition, new Rectangle(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height));
Object originalCanonicalValue = cell.getDataValue();
ActiveCellEditor.activate(cellEditor, parent, originalCanonicalValue, initialEditValue, EditModeEnum.INLINE, editHandler, cell, configRegistry);
final Control editorControl = ActiveCellEditor.getControl();
if (editorControl != null) {
editorControl.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (!ActiveCellEditor.commit()) {
- if (e.widget instanceof Control) {
+ if (e.widget instanceof Control && !e.widget.isDisposed()) {
((Control)e.widget).forceFocus();
}
}
else {
parent.forceFocus();
}
}
});
editorControl.setBounds(editorBounds);
ILayerListener layerListener = layerListenerMap.get(layer);
if (layerListener == null) {
layerListener = new InlineCellEditLayerListener(layer);
layerListenerMap.put(layer, layerListener);
layer.addLayerListener(layerListener);
}
}
} catch (Exception e) {
if(cell == null){
System.err.println("Cell being edited is no longer available. Character: " + initialEditValue); //$NON-NLS-1$
} else {
System.err.println("Error while editing cell (inline): Cell: " + cell + "; Character: " + initialEditValue); //$NON-NLS-1$ //$NON-NLS-2$
}
e.printStackTrace();
}
return true;
}
public static void dispose() {
layerListenerMap.clear();
}
static class InlineCellEditLayerListener implements ILayerListener {
private final ILayer layer;
InlineCellEditLayerListener(ILayer layer) {
this.layer = layer;
}
public void handleLayerEvent(ILayerEvent event) {
if (event instanceof CellSelectionEvent && ActiveCellEditor.isValid()) {
int selectedCellColumnPosition = 0;
int selectedCellRowPosition = 0;
CellSelectionEvent csEvent = (CellSelectionEvent) event;
selectedCellColumnPosition = csEvent.getColumnPosition();
selectedCellRowPosition = csEvent.getRowPosition();
int editorColumnPosition = ActiveCellEditor.getColumnPosition();
int editorRowPosition = ActiveCellEditor.getRowPosition();
int editorColumnIndex = ActiveCellEditor.getColumnIndex();
int editorRowIndex = ActiveCellEditor.getRowIndex();
int selectedColumnIndex = layer.getColumnIndexByPosition(selectedCellColumnPosition);
int selectedRowIndex = layer.getRowIndexByPosition(selectedCellRowPosition);
Control editorControl = ActiveCellEditor.getControl();
if (selectedColumnIndex != editorColumnIndex || selectedRowIndex != editorRowIndex) {
ActiveCellEditor.close();
}
else if (editorControl != null && !editorControl.isDisposed()) {
Rectangle cellBounds = layer.getBoundsByPosition(editorColumnPosition, editorRowPosition);
Rectangle adjustedCellBounds = layer.getLayerPainter().adjustCellBounds(editorColumnPosition, editorRowPosition, cellBounds);
editorControl.setBounds(adjustedCellBounds);
}
}
}
}
}
| true | true | public static boolean editCellInline(ILayerCell cell, Character initialEditValue, final Composite parent, IConfigRegistry configRegistry) {
try {
ActiveCellEditor.commit();
final List<String> configLabels = cell.getConfigLabels().getLabels();
Rectangle cellBounds = cell.getBounds();
ILayer layer = cell.getLayer();
int columnPosition = layer.getColumnPositionByX(cellBounds.x);
int rowPosition = layer.getRowPositionByY(cellBounds.y);
boolean editable = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, DisplayMode.EDIT, configLabels).isEditable(cell, configRegistry);
if (!editable) {
return false;
}
ICellEditor cellEditor = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITOR, DisplayMode.EDIT, configLabels);
ICellEditHandler editHandler = new SingleEditHandler(
cellEditor,
layer,
columnPosition,
rowPosition);
final Rectangle editorBounds = layer.getLayerPainter().adjustCellBounds(columnPosition, rowPosition, new Rectangle(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height));
Object originalCanonicalValue = cell.getDataValue();
ActiveCellEditor.activate(cellEditor, parent, originalCanonicalValue, initialEditValue, EditModeEnum.INLINE, editHandler, cell, configRegistry);
final Control editorControl = ActiveCellEditor.getControl();
if (editorControl != null) {
editorControl.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (!ActiveCellEditor.commit()) {
if (e.widget instanceof Control) {
((Control)e.widget).forceFocus();
}
}
else {
parent.forceFocus();
}
}
});
editorControl.setBounds(editorBounds);
ILayerListener layerListener = layerListenerMap.get(layer);
if (layerListener == null) {
layerListener = new InlineCellEditLayerListener(layer);
layerListenerMap.put(layer, layerListener);
layer.addLayerListener(layerListener);
}
}
} catch (Exception e) {
if(cell == null){
System.err.println("Cell being edited is no longer available. Character: " + initialEditValue); //$NON-NLS-1$
} else {
System.err.println("Error while editing cell (inline): Cell: " + cell + "; Character: " + initialEditValue); //$NON-NLS-1$ //$NON-NLS-2$
}
e.printStackTrace();
}
return true;
}
| public static boolean editCellInline(ILayerCell cell, Character initialEditValue, final Composite parent, IConfigRegistry configRegistry) {
try {
ActiveCellEditor.commit();
final List<String> configLabels = cell.getConfigLabels().getLabels();
Rectangle cellBounds = cell.getBounds();
ILayer layer = cell.getLayer();
int columnPosition = layer.getColumnPositionByX(cellBounds.x);
int rowPosition = layer.getRowPositionByY(cellBounds.y);
boolean editable = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, DisplayMode.EDIT, configLabels).isEditable(cell, configRegistry);
if (!editable) {
return false;
}
ICellEditor cellEditor = configRegistry.getConfigAttribute(EditConfigAttributes.CELL_EDITOR, DisplayMode.EDIT, configLabels);
ICellEditHandler editHandler = new SingleEditHandler(
cellEditor,
layer,
columnPosition,
rowPosition);
final Rectangle editorBounds = layer.getLayerPainter().adjustCellBounds(columnPosition, rowPosition, new Rectangle(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height));
Object originalCanonicalValue = cell.getDataValue();
ActiveCellEditor.activate(cellEditor, parent, originalCanonicalValue, initialEditValue, EditModeEnum.INLINE, editHandler, cell, configRegistry);
final Control editorControl = ActiveCellEditor.getControl();
if (editorControl != null) {
editorControl.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (!ActiveCellEditor.commit()) {
if (e.widget instanceof Control && !e.widget.isDisposed()) {
((Control)e.widget).forceFocus();
}
}
else {
parent.forceFocus();
}
}
});
editorControl.setBounds(editorBounds);
ILayerListener layerListener = layerListenerMap.get(layer);
if (layerListener == null) {
layerListener = new InlineCellEditLayerListener(layer);
layerListenerMap.put(layer, layerListener);
layer.addLayerListener(layerListener);
}
}
} catch (Exception e) {
if(cell == null){
System.err.println("Cell being edited is no longer available. Character: " + initialEditValue); //$NON-NLS-1$
} else {
System.err.println("Error while editing cell (inline): Cell: " + cell + "; Character: " + initialEditValue); //$NON-NLS-1$ //$NON-NLS-2$
}
e.printStackTrace();
}
return true;
}
|
diff --git a/src/main/java/com/superdownloader/proEasy/processors/FtpSender.java b/src/main/java/com/superdownloader/proEasy/processors/FtpSender.java
index 7e4828f..982d47a 100644
--- a/src/main/java/com/superdownloader/proEasy/processors/FtpSender.java
+++ b/src/main/java/com/superdownloader/proEasy/processors/FtpSender.java
@@ -1,108 +1,108 @@
package com.superdownloader.proEasy.processors;
import java.io.File;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.superdownloader.common.ftp.FtpUploader;
import com.superdownloader.common.ftp.FtpUploaderCommons;
import com.superdownloader.proEasy.exceptions.TransportException;
/**
* @author harley
*
*/
@Service(value = "ftpSender")
public class FtpSender implements Processor {
private static final Logger LOGGER = LoggerFactory.getLogger(FtpSender.class);
@Override
public void process(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
FtpUploader ftpUploader = new FtpUploaderCommons();
String ftp_user = (String) msg.getHeader(Headers.FTP_USERNAME);
String ftp_pass = (String) msg.getHeader(Headers.FTP_PASSWORD);
String ftp_server = (String) msg.getHeader(Headers.FTP_URL);
String ftp_remoteDir = (String) msg.getHeader(Headers.FTP_REMOTE_DIR);
@SuppressWarnings("unchecked")
List<String> filesToUpload = (List<String>) msg.getHeader(Headers.FILES);
try {
ftpUploader.configure(ftp_server, ftp_user, ftp_pass, ftp_remoteDir);
// Connect and Upload
- LOGGER.info("Connecting to {}...", ftp_server);
ftpUploader.connect();
+ LOGGER.info("Connected to {}", ftp_server);
for (String toUpload : filesToUpload) {
LOGGER.info("Uploading {}...", toUpload);
ftpUploader.upload(new File(toUpload));
}
} catch (Exception e) {
throw new TransportException("Error at uploading file via FTP", e);
} finally {
// Disconnect and Exit
- LOGGER.info("Disconnecting...");
ftpUploader.disconnect();
+ LOGGER.info("Disconnected");
}
}
/**
* TODO: This was implemented based in ftp endpoint that has Camel (Couldn't get it work properly)
* Currently only upload the file get! We need to upload the path in the first
* line of this file!!
* Also check the remote path
*
public String sendToFtp(Exchange exchange) {
Message msg = exchange.getIn();
if (exchange.getProperty(Exchange.SLIP_ENDPOINT) == null) {
List<String> filesToUpload = (List<String>) msg.getHeader(Headers.FILES);
File f = new File(filesToUpload.get(0));
LOGGER.debug("{}", exchange.getProperties());
LOGGER.debug("{}", msg.getHeaders());
String ftp_user = (String) msg.getHeader(Headers.FTP_USERNAME);
String ftp_pass = (String) msg.getHeader(Headers.FTP_PASSWORD);
String ftp_url = (String) msg.getHeader(Headers.FTP_URL);
String ftp_remoteDir = (String) msg.getHeader(Headers.FTP_REMOTE_DIR);
// Create ftp endoint
StringBuilder ftpEndpoint = new StringBuilder("ftp://")
.append(ftp_user)
.append("@")
.append(ftp_url)
.append("/")
//.append(ftp_remoteDir)
.append("?password=")
.append(ftp_pass);
ftpEndpoint.append("&connectTimeout=" + TIMEOUT);
ftpEndpoint.append("&timeout=" + TIMEOUT);
ftpEndpoint.append("&soTimeout=" + TIMEOUT);
ftpEndpoint.append("&throwExceptionOnConnectFailed=true");
ftpEndpoint.append("&disconnect=true");
ftpEndpoint.append("&binary=true");
ftpEndpoint.append("&recursive=true");
ftpEndpoint.append("&doneFileName="+f.getName());
ftpEndpoint.append("&fileName="+filesToUpload.get(0));
return ftpEndpoint.toString();
} else {
return null;
}
}*/
}
| false | true | public void process(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
FtpUploader ftpUploader = new FtpUploaderCommons();
String ftp_user = (String) msg.getHeader(Headers.FTP_USERNAME);
String ftp_pass = (String) msg.getHeader(Headers.FTP_PASSWORD);
String ftp_server = (String) msg.getHeader(Headers.FTP_URL);
String ftp_remoteDir = (String) msg.getHeader(Headers.FTP_REMOTE_DIR);
@SuppressWarnings("unchecked")
List<String> filesToUpload = (List<String>) msg.getHeader(Headers.FILES);
try {
ftpUploader.configure(ftp_server, ftp_user, ftp_pass, ftp_remoteDir);
// Connect and Upload
LOGGER.info("Connecting to {}...", ftp_server);
ftpUploader.connect();
for (String toUpload : filesToUpload) {
LOGGER.info("Uploading {}...", toUpload);
ftpUploader.upload(new File(toUpload));
}
} catch (Exception e) {
throw new TransportException("Error at uploading file via FTP", e);
} finally {
// Disconnect and Exit
LOGGER.info("Disconnecting...");
ftpUploader.disconnect();
}
}
| public void process(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
FtpUploader ftpUploader = new FtpUploaderCommons();
String ftp_user = (String) msg.getHeader(Headers.FTP_USERNAME);
String ftp_pass = (String) msg.getHeader(Headers.FTP_PASSWORD);
String ftp_server = (String) msg.getHeader(Headers.FTP_URL);
String ftp_remoteDir = (String) msg.getHeader(Headers.FTP_REMOTE_DIR);
@SuppressWarnings("unchecked")
List<String> filesToUpload = (List<String>) msg.getHeader(Headers.FILES);
try {
ftpUploader.configure(ftp_server, ftp_user, ftp_pass, ftp_remoteDir);
// Connect and Upload
ftpUploader.connect();
LOGGER.info("Connected to {}", ftp_server);
for (String toUpload : filesToUpload) {
LOGGER.info("Uploading {}...", toUpload);
ftpUploader.upload(new File(toUpload));
}
} catch (Exception e) {
throw new TransportException("Error at uploading file via FTP", e);
} finally {
// Disconnect and Exit
ftpUploader.disconnect();
LOGGER.info("Disconnected");
}
}
|
diff --git a/Bukkit-CleanChat/src/cleanChat/tjnome/main/conf/CleanChatConf.java b/Bukkit-CleanChat/src/cleanChat/tjnome/main/conf/CleanChatConf.java
index 9be84b3..60400f3 100644
--- a/Bukkit-CleanChat/src/cleanChat/tjnome/main/conf/CleanChatConf.java
+++ b/Bukkit-CleanChat/src/cleanChat/tjnome/main/conf/CleanChatConf.java
@@ -1,58 +1,58 @@
package cleanChat.tjnome.main.conf;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.bukkit.configuration.file.YamlConfiguration;
import cleanChat.tjnome.main.CleanChat;
public class CleanChatConf {
private CleanChat plugin;
private HashMap<String, Object> configDefaults = new HashMap<String, Object>();
private YamlConfiguration config;
private File configFile;
public CleanChatConf(CleanChat plugin) {
this.plugin = plugin;
}
// Server
public boolean login;
public boolean logout;
public void load() {
this.config = new YamlConfiguration();
this.configFile = new File(plugin.getDataFolder(), "config.yml");
//Server
- this.configDefaults.put("Server.remove-login-msg", false);
- this.configDefaults.put("Server.remove-logout-msg", false);
+ this.configDefaults.put("Server.remove-login-msg", true);
+ this.configDefaults.put("Server.remove-logout-msg", true);
if (!this.configFile.exists()) {
for (String key : this.configDefaults.keySet()) {
this.config.set(key, this.configDefaults.get(key));
}
try {
config.save(this.configFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
config.load(this.configFile);
} catch (Exception e) {
e.printStackTrace();
}
}
this.login = config.getBoolean("Server.remove-login-msg");
this.logout = config.getBoolean("Server.remove-logout-msg");
}
public void cleanup() {
configDefaults.clear();
}
}
| true | true | public void load() {
this.config = new YamlConfiguration();
this.configFile = new File(plugin.getDataFolder(), "config.yml");
//Server
this.configDefaults.put("Server.remove-login-msg", false);
this.configDefaults.put("Server.remove-logout-msg", false);
if (!this.configFile.exists()) {
for (String key : this.configDefaults.keySet()) {
this.config.set(key, this.configDefaults.get(key));
}
try {
config.save(this.configFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
config.load(this.configFile);
} catch (Exception e) {
e.printStackTrace();
}
}
this.login = config.getBoolean("Server.remove-login-msg");
this.logout = config.getBoolean("Server.remove-logout-msg");
}
| public void load() {
this.config = new YamlConfiguration();
this.configFile = new File(plugin.getDataFolder(), "config.yml");
//Server
this.configDefaults.put("Server.remove-login-msg", true);
this.configDefaults.put("Server.remove-logout-msg", true);
if (!this.configFile.exists()) {
for (String key : this.configDefaults.keySet()) {
this.config.set(key, this.configDefaults.get(key));
}
try {
config.save(this.configFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
config.load(this.configFile);
} catch (Exception e) {
e.printStackTrace();
}
}
this.login = config.getBoolean("Server.remove-login-msg");
this.logout = config.getBoolean("Server.remove-logout-msg");
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/AutomaticUpdatesPreferencePage.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/AutomaticUpdatesPreferencePage.java
index bb23bec22..d6dba46bc 100644
--- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/AutomaticUpdatesPreferencePage.java
+++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/AutomaticUpdatesPreferencePage.java
@@ -1,297 +1,296 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.sdk.prefs;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.equinox.internal.p2.ui.sdk.*;
import org.eclipse.equinox.internal.p2.ui.sdk.updates.AutomaticUpdatesPopup;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public class AutomaticUpdatesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private Button enabledCheck;
private Button onStartupRadio, onScheduleRadio;
private Combo dayCombo;
private Label atLabel;
private Combo hourCombo;
private Button searchOnlyRadio, searchAndDownloadRadio;
private Button remindOnceRadio, remindScheduleRadio;
private Combo remindElapseCombo;
private Group updateScheduleGroup, downloadGroup, remindGroup;
public void init(IWorkbench workbench) {
// nothing to init
}
protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
layout.marginWidth = layout.marginHeight = 0;
container.setLayout(layout);
enabledCheck = new Button(container, SWT.CHECK);
enabledCheck.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findUpdates);
createSpacer(container, 1);
updateScheduleGroup = new Group(container, SWT.NONE);
updateScheduleGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_UpdateSchedule);
layout = new GridLayout();
layout.numColumns = 3;
updateScheduleGroup.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
updateScheduleGroup.setLayoutData(gd);
onStartupRadio = new Button(updateScheduleGroup, SWT.RADIO);
onStartupRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findOnStart);
gd = new GridData();
gd.horizontalSpan = 3;
onStartupRadio.setLayoutData(gd);
onStartupRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
onScheduleRadio = new Button(updateScheduleGroup, SWT.RADIO);
onScheduleRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findOnSchedule);
gd = new GridData();
gd.horizontalSpan = 3;
onScheduleRadio.setLayoutData(gd);
onScheduleRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
dayCombo = new Combo(updateScheduleGroup, SWT.READ_ONLY);
dayCombo.setItems(AutomaticUpdateScheduler.DAYS);
gd = new GridData();
gd.widthHint = 200;
gd.horizontalIndent = 30;
dayCombo.setLayoutData(gd);
atLabel = new Label(updateScheduleGroup, SWT.NULL);
atLabel.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_at);
hourCombo = new Combo(updateScheduleGroup, SWT.READ_ONLY);
hourCombo.setItems(AutomaticUpdateScheduler.HOURS);
gd = new GridData();
- gd.widthHint = 100;
hourCombo.setLayoutData(gd);
createSpacer(container, 1);
downloadGroup = new Group(container, SWT.NONE);
downloadGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_downloadOptions);
layout = new GridLayout();
layout.numColumns = 3;
downloadGroup.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
downloadGroup.setLayoutData(gd);
searchOnlyRadio = new Button(downloadGroup, SWT.RADIO);
searchOnlyRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_searchAndNotify);
gd = new GridData();
gd.horizontalSpan = 3;
searchOnlyRadio.setLayoutData(gd);
searchOnlyRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
searchAndDownloadRadio = new Button(downloadGroup, SWT.RADIO);
searchAndDownloadRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_downloadAndNotify);
gd = new GridData();
gd.horizontalSpan = 3;
searchAndDownloadRadio.setLayoutData(gd);
searchAndDownloadRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
createSpacer(container, 1);
remindGroup = new Group(container, SWT.NONE);
remindGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindGroup);
layout = new GridLayout();
layout.numColumns = 3;
remindGroup.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
remindGroup.setLayoutData(gd);
remindOnceRadio = new Button(remindGroup, SWT.RADIO);
remindOnceRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindOnce);
gd = new GridData();
gd.horizontalSpan = 3;
remindOnceRadio.setLayoutData(gd);
remindOnceRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
remindScheduleRadio = new Button(remindGroup, SWT.RADIO);
remindScheduleRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindSchedule);
gd = new GridData();
gd.horizontalSpan = 3;
remindScheduleRadio.setLayoutData(gd);
remindScheduleRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
remindElapseCombo = new Combo(remindGroup, SWT.READ_ONLY);
remindElapseCombo.setItems(AutomaticUpdatesPopup.ELAPSED);
gd = new GridData();
gd.widthHint = 200;
gd.horizontalIndent = 30;
remindElapseCombo.setLayoutData(gd);
initialize();
enabledCheck.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
Dialog.applyDialogFont(container);
return container;
}
protected void createSpacer(Composite composite, int columnSpan) {
Label label = new Label(composite, SWT.NONE);
GridData gd = new GridData();
gd.horizontalSpan = columnSpan;
label.setLayoutData(gd);
}
private void initialize() {
Preferences pref = ProvSDKUIActivator.getDefault().getPluginPreferences();
enabledCheck.setSelection(pref.getBoolean(PreferenceConstants.PREF_AUTO_UPDATE_ENABLED));
setSchedule(pref.getString(PreferenceConstants.PREF_AUTO_UPDATE_SCHEDULE));
dayCombo.setText(AutomaticUpdateScheduler.DAYS[getDay(pref, false)]);
hourCombo.setText(AutomaticUpdateScheduler.HOURS[getHour(pref, false)]);
remindScheduleRadio.setSelection(pref.getBoolean(PreferenceConstants.PREF_REMIND_SCHEDULE));
remindOnceRadio.setSelection(!pref.getBoolean(PreferenceConstants.PREF_REMIND_SCHEDULE));
remindElapseCombo.setText(pref.getString(PreferenceConstants.PREF_REMIND_ELAPSED));
searchOnlyRadio.setSelection(!pref.getBoolean(PreferenceConstants.PREF_DOWNLOAD_ONLY));
searchAndDownloadRadio.setSelection(pref.getBoolean(PreferenceConstants.PREF_DOWNLOAD_ONLY));
pageChanged();
}
private void setSchedule(String value) {
if (value.equals(PreferenceConstants.PREF_UPDATE_ON_STARTUP))
onStartupRadio.setSelection(true);
else
onScheduleRadio.setSelection(true);
}
void pageChanged() {
boolean master = enabledCheck.getSelection();
updateScheduleGroup.setEnabled(master);
onStartupRadio.setEnabled(master);
onScheduleRadio.setEnabled(master);
dayCombo.setEnabled(master && onScheduleRadio.getSelection());
atLabel.setEnabled(master && onScheduleRadio.getSelection());
hourCombo.setEnabled(master && onScheduleRadio.getSelection());
downloadGroup.setEnabled(master);
searchOnlyRadio.setEnabled(master);
searchAndDownloadRadio.setEnabled(master);
remindGroup.setEnabled(master);
remindScheduleRadio.setEnabled(master);
remindOnceRadio.setEnabled(master);
remindElapseCombo.setEnabled(master && remindScheduleRadio.getSelection());
}
protected void performDefaults() {
super.performDefaults();
Preferences pref = ProvSDKUIActivator.getDefault().getPluginPreferences();
enabledCheck.setSelection(pref.getDefaultBoolean(PreferenceConstants.PREF_AUTO_UPDATE_ENABLED));
setSchedule(pref.getDefaultString(PreferenceConstants.PREF_AUTO_UPDATE_SCHEDULE));
onScheduleRadio.setSelection(pref.getDefaultBoolean(PreferenceConstants.PREF_AUTO_UPDATE_SCHEDULE));
dayCombo.setText(AutomaticUpdateScheduler.DAYS[getDay(pref, true)]);
hourCombo.setText(AutomaticUpdateScheduler.HOURS[getHour(pref, true)]);
remindOnceRadio.setSelection(!pref.getDefaultBoolean(PreferenceConstants.PREF_REMIND_SCHEDULE));
remindScheduleRadio.setSelection(pref.getDefaultBoolean(PreferenceConstants.PREF_REMIND_SCHEDULE));
remindElapseCombo.setText(pref.getDefaultString(PreferenceConstants.PREF_REMIND_ELAPSED));
searchOnlyRadio.setSelection(!pref.getDefaultBoolean(PreferenceConstants.PREF_DOWNLOAD_ONLY));
searchAndDownloadRadio.setSelection(pref.getDefaultBoolean(PreferenceConstants.PREF_DOWNLOAD_ONLY));
pageChanged();
}
/**
* Method declared on IPreferencePage.
* Subclasses should override
*/
public boolean performOk() {
Preferences pref = ProvSDKUIActivator.getDefault().getPluginPreferences();
pref.setValue(PreferenceConstants.PREF_AUTO_UPDATE_ENABLED, enabledCheck.getSelection());
if (onStartupRadio.getSelection())
pref.setValue(PreferenceConstants.PREF_AUTO_UPDATE_SCHEDULE, PreferenceConstants.PREF_UPDATE_ON_STARTUP);
else
pref.setValue(PreferenceConstants.PREF_AUTO_UPDATE_SCHEDULE, PreferenceConstants.PREF_UPDATE_ON_SCHEDULE);
if (remindScheduleRadio.getSelection()) {
pref.setValue(PreferenceConstants.PREF_REMIND_SCHEDULE, true);
pref.setValue(PreferenceConstants.PREF_REMIND_ELAPSED, remindElapseCombo.getText());
} else {
pref.setValue(PreferenceConstants.PREF_REMIND_SCHEDULE, false);
}
pref.setValue(AutomaticUpdateScheduler.P_DAY, dayCombo.getText());
pref.setValue(AutomaticUpdateScheduler.P_HOUR, hourCombo.getText());
pref.setValue(PreferenceConstants.PREF_DOWNLOAD_ONLY, searchAndDownloadRadio.getSelection());
ProvSDKUIActivator.getDefault().savePluginPreferences();
ProvSDKUIActivator.getDefault().getScheduler().rescheduleUpdate();
return true;
}
private int getDay(Preferences pref, boolean useDefault) {
String day = useDefault ? pref.getDefaultString(AutomaticUpdateScheduler.P_DAY) : pref.getString(AutomaticUpdateScheduler.P_DAY);
for (int i = 0; i < AutomaticUpdateScheduler.DAYS.length; i++)
if (AutomaticUpdateScheduler.DAYS[i].equals(day))
return i;
return 0;
}
private int getHour(Preferences pref, boolean useDefault) {
String hour = useDefault ? pref.getDefaultString(AutomaticUpdateScheduler.P_HOUR) : pref.getString(AutomaticUpdateScheduler.P_HOUR);
for (int i = 0; i < AutomaticUpdateScheduler.HOURS.length; i++)
if (AutomaticUpdateScheduler.HOURS[i].equals(hour))
return i;
return 0;
}
}
| true | true | protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
layout.marginWidth = layout.marginHeight = 0;
container.setLayout(layout);
enabledCheck = new Button(container, SWT.CHECK);
enabledCheck.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findUpdates);
createSpacer(container, 1);
updateScheduleGroup = new Group(container, SWT.NONE);
updateScheduleGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_UpdateSchedule);
layout = new GridLayout();
layout.numColumns = 3;
updateScheduleGroup.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
updateScheduleGroup.setLayoutData(gd);
onStartupRadio = new Button(updateScheduleGroup, SWT.RADIO);
onStartupRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findOnStart);
gd = new GridData();
gd.horizontalSpan = 3;
onStartupRadio.setLayoutData(gd);
onStartupRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
onScheduleRadio = new Button(updateScheduleGroup, SWT.RADIO);
onScheduleRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findOnSchedule);
gd = new GridData();
gd.horizontalSpan = 3;
onScheduleRadio.setLayoutData(gd);
onScheduleRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
dayCombo = new Combo(updateScheduleGroup, SWT.READ_ONLY);
dayCombo.setItems(AutomaticUpdateScheduler.DAYS);
gd = new GridData();
gd.widthHint = 200;
gd.horizontalIndent = 30;
dayCombo.setLayoutData(gd);
atLabel = new Label(updateScheduleGroup, SWT.NULL);
atLabel.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_at);
hourCombo = new Combo(updateScheduleGroup, SWT.READ_ONLY);
hourCombo.setItems(AutomaticUpdateScheduler.HOURS);
gd = new GridData();
gd.widthHint = 100;
hourCombo.setLayoutData(gd);
createSpacer(container, 1);
downloadGroup = new Group(container, SWT.NONE);
downloadGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_downloadOptions);
layout = new GridLayout();
layout.numColumns = 3;
downloadGroup.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
downloadGroup.setLayoutData(gd);
searchOnlyRadio = new Button(downloadGroup, SWT.RADIO);
searchOnlyRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_searchAndNotify);
gd = new GridData();
gd.horizontalSpan = 3;
searchOnlyRadio.setLayoutData(gd);
searchOnlyRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
searchAndDownloadRadio = new Button(downloadGroup, SWT.RADIO);
searchAndDownloadRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_downloadAndNotify);
gd = new GridData();
gd.horizontalSpan = 3;
searchAndDownloadRadio.setLayoutData(gd);
searchAndDownloadRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
createSpacer(container, 1);
remindGroup = new Group(container, SWT.NONE);
remindGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindGroup);
layout = new GridLayout();
layout.numColumns = 3;
remindGroup.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
remindGroup.setLayoutData(gd);
remindOnceRadio = new Button(remindGroup, SWT.RADIO);
remindOnceRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindOnce);
gd = new GridData();
gd.horizontalSpan = 3;
remindOnceRadio.setLayoutData(gd);
remindOnceRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
remindScheduleRadio = new Button(remindGroup, SWT.RADIO);
remindScheduleRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindSchedule);
gd = new GridData();
gd.horizontalSpan = 3;
remindScheduleRadio.setLayoutData(gd);
remindScheduleRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
remindElapseCombo = new Combo(remindGroup, SWT.READ_ONLY);
remindElapseCombo.setItems(AutomaticUpdatesPopup.ELAPSED);
gd = new GridData();
gd.widthHint = 200;
gd.horizontalIndent = 30;
remindElapseCombo.setLayoutData(gd);
initialize();
enabledCheck.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
Dialog.applyDialogFont(container);
return container;
}
| protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
layout.marginWidth = layout.marginHeight = 0;
container.setLayout(layout);
enabledCheck = new Button(container, SWT.CHECK);
enabledCheck.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findUpdates);
createSpacer(container, 1);
updateScheduleGroup = new Group(container, SWT.NONE);
updateScheduleGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_UpdateSchedule);
layout = new GridLayout();
layout.numColumns = 3;
updateScheduleGroup.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
updateScheduleGroup.setLayoutData(gd);
onStartupRadio = new Button(updateScheduleGroup, SWT.RADIO);
onStartupRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findOnStart);
gd = new GridData();
gd.horizontalSpan = 3;
onStartupRadio.setLayoutData(gd);
onStartupRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
onScheduleRadio = new Button(updateScheduleGroup, SWT.RADIO);
onScheduleRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_findOnSchedule);
gd = new GridData();
gd.horizontalSpan = 3;
onScheduleRadio.setLayoutData(gd);
onScheduleRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
dayCombo = new Combo(updateScheduleGroup, SWT.READ_ONLY);
dayCombo.setItems(AutomaticUpdateScheduler.DAYS);
gd = new GridData();
gd.widthHint = 200;
gd.horizontalIndent = 30;
dayCombo.setLayoutData(gd);
atLabel = new Label(updateScheduleGroup, SWT.NULL);
atLabel.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_at);
hourCombo = new Combo(updateScheduleGroup, SWT.READ_ONLY);
hourCombo.setItems(AutomaticUpdateScheduler.HOURS);
gd = new GridData();
hourCombo.setLayoutData(gd);
createSpacer(container, 1);
downloadGroup = new Group(container, SWT.NONE);
downloadGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_downloadOptions);
layout = new GridLayout();
layout.numColumns = 3;
downloadGroup.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
downloadGroup.setLayoutData(gd);
searchOnlyRadio = new Button(downloadGroup, SWT.RADIO);
searchOnlyRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_searchAndNotify);
gd = new GridData();
gd.horizontalSpan = 3;
searchOnlyRadio.setLayoutData(gd);
searchOnlyRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
searchAndDownloadRadio = new Button(downloadGroup, SWT.RADIO);
searchAndDownloadRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_downloadAndNotify);
gd = new GridData();
gd.horizontalSpan = 3;
searchAndDownloadRadio.setLayoutData(gd);
searchAndDownloadRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
createSpacer(container, 1);
remindGroup = new Group(container, SWT.NONE);
remindGroup.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindGroup);
layout = new GridLayout();
layout.numColumns = 3;
remindGroup.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
remindGroup.setLayoutData(gd);
remindOnceRadio = new Button(remindGroup, SWT.RADIO);
remindOnceRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindOnce);
gd = new GridData();
gd.horizontalSpan = 3;
remindOnceRadio.setLayoutData(gd);
remindOnceRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
remindScheduleRadio = new Button(remindGroup, SWT.RADIO);
remindScheduleRadio.setText(ProvSDKMessages.AutomaticUpdatesPreferencePage_RemindSchedule);
gd = new GridData();
gd.horizontalSpan = 3;
remindScheduleRadio.setLayoutData(gd);
remindScheduleRadio.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
remindElapseCombo = new Combo(remindGroup, SWT.READ_ONLY);
remindElapseCombo.setItems(AutomaticUpdatesPopup.ELAPSED);
gd = new GridData();
gd.widthHint = 200;
gd.horizontalIndent = 30;
remindElapseCombo.setLayoutData(gd);
initialize();
enabledCheck.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChanged();
}
});
Dialog.applyDialogFont(container);
return container;
}
|
diff --git a/src/en/trudan/ConstructionSites/PlayerCommands.java b/src/en/trudan/ConstructionSites/PlayerCommands.java
index 2a22c95..5e08cf6 100644
--- a/src/en/trudan/ConstructionSites/PlayerCommands.java
+++ b/src/en/trudan/ConstructionSites/PlayerCommands.java
@@ -1,57 +1,57 @@
package en.trudan.ConstructionSites;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.getspout.spout.inventory.CustomInventory;
import en.trudan.ConstructionSites.Data.ConstructionSite;
import en.trudan.ConstructionSites.Data.FileHandler;
public class PlayerCommands {
public static ConstructionSites main = ConstructionSites.main;
public static FileHandler fh = main.getFH();
public static void proccess(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName();
if(commandName.equalsIgnoreCase("construct")) {
if(args.length >= 1) {
String subcommandName = args[0];
if(subcommandName.equalsIgnoreCase("trade")) {
if(args.length == 2) {
if(fh.getConstructionSite(args[1]) != null) {
ConstructionSite site = fh.getConstructionSite(args[1]);
// Trade items into the construction site
Player player = (Player) sender;
String siteName = "Construction Site Materials";
CustomInventory inv = new CustomInventory(54,siteName);
- ItemStack[] stacks = site.getChest();
+ ItemStack[] stacks = site.getMaterialStorage().getChest();
for(ItemStack stack : stacks) {
inv.addItem(stack);
}
((org.getspout.spoutapi.player.SpoutPlayer) player).openInventoryWindow((Inventory) inv);
}
else {
sender.sendMessage(ChatColor.RED+"That construction site does not exist!");
}
}
else {
sender.sendMessage(ChatColor.GRAY+"Correct Usage: "+ChatColor.GREEN+"/construct trade <Site name>");
}
}
}
}
}
}
| true | true | public static void proccess(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName();
if(commandName.equalsIgnoreCase("construct")) {
if(args.length >= 1) {
String subcommandName = args[0];
if(subcommandName.equalsIgnoreCase("trade")) {
if(args.length == 2) {
if(fh.getConstructionSite(args[1]) != null) {
ConstructionSite site = fh.getConstructionSite(args[1]);
// Trade items into the construction site
Player player = (Player) sender;
String siteName = "Construction Site Materials";
CustomInventory inv = new CustomInventory(54,siteName);
ItemStack[] stacks = site.getChest();
for(ItemStack stack : stacks) {
inv.addItem(stack);
}
((org.getspout.spoutapi.player.SpoutPlayer) player).openInventoryWindow((Inventory) inv);
}
else {
sender.sendMessage(ChatColor.RED+"That construction site does not exist!");
}
}
else {
sender.sendMessage(ChatColor.GRAY+"Correct Usage: "+ChatColor.GREEN+"/construct trade <Site name>");
}
}
}
}
}
| public static void proccess(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName();
if(commandName.equalsIgnoreCase("construct")) {
if(args.length >= 1) {
String subcommandName = args[0];
if(subcommandName.equalsIgnoreCase("trade")) {
if(args.length == 2) {
if(fh.getConstructionSite(args[1]) != null) {
ConstructionSite site = fh.getConstructionSite(args[1]);
// Trade items into the construction site
Player player = (Player) sender;
String siteName = "Construction Site Materials";
CustomInventory inv = new CustomInventory(54,siteName);
ItemStack[] stacks = site.getMaterialStorage().getChest();
for(ItemStack stack : stacks) {
inv.addItem(stack);
}
((org.getspout.spoutapi.player.SpoutPlayer) player).openInventoryWindow((Inventory) inv);
}
else {
sender.sendMessage(ChatColor.RED+"That construction site does not exist!");
}
}
else {
sender.sendMessage(ChatColor.GRAY+"Correct Usage: "+ChatColor.GREEN+"/construct trade <Site name>");
}
}
}
}
}
|
diff --git a/core/src/main/java/uk/ac/bbsrc/tgac/miso/core/data/impl/illumina/IlluminaRun.java b/core/src/main/java/uk/ac/bbsrc/tgac/miso/core/data/impl/illumina/IlluminaRun.java
index 71a37c237..0001d242f 100644
--- a/core/src/main/java/uk/ac/bbsrc/tgac/miso/core/data/impl/illumina/IlluminaRun.java
+++ b/core/src/main/java/uk/ac/bbsrc/tgac/miso/core/data/impl/illumina/IlluminaRun.java
@@ -1,161 +1,161 @@
/*
* Copyright (c) 2012. The Genome Analysis Centre, Norwich, UK
* MISO project contacts: Robert Davey, Mario Caccamo @ TGAC
* *********************************************************************
*
* This file is part of MISO.
*
* MISO 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.
*
* MISO 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 MISO. If not, see <http://www.gnu.org/licenses/>.
*
* *********************************************************************
*/
package uk.ac.bbsrc.tgac.miso.core.data.impl.illumina;
import com.eaglegenomics.simlims.core.SecurityProfile;
import com.eaglegenomics.simlims.core.User;
import org.w3c.dom.Document;
import uk.ac.bbsrc.tgac.miso.core.data.*;
import uk.ac.bbsrc.tgac.miso.core.data.impl.RunImpl;
import uk.ac.bbsrc.tgac.miso.core.data.impl.StatusImpl;
import uk.ac.bbsrc.tgac.miso.core.data.type.PlatformType;
import uk.ac.bbsrc.tgac.miso.core.util.SubmissionUtils;
import uk.ac.bbsrc.tgac.miso.core.factory.submission.ERASubmissionFactory;
import uk.ac.bbsrc.tgac.miso.core.util.UnicodeReader;
import javax.persistence.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* uk.ac.bbsrc.tgac.miso.core.data.impl.illumina
* <p/>
* TODO Info
*
* @author Rob Davey
* @since 0.0.2
*/
@Entity
@DiscriminatorValue("Illumina")
public class IlluminaRun extends RunImpl {
public IlluminaRun() {
setPlatformType(PlatformType.ILLUMINA);
setStatus(new StatusImpl());
setSecurityProfile(new SecurityProfile());
}
public IlluminaRun(String statusXml) {
this(statusXml, null);
}
public IlluminaRun(String statusXml, User user) {
try {
Document statusDoc = SubmissionUtils.emptyDocument();
if (statusXml != null && !"".equals(statusXml)) {
SubmissionUtils.transform(new UnicodeReader(statusXml), statusDoc);
String runName = (statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
setPairedEnd(false);
if (!statusDoc.getDocumentElement().getTagName().equals("error")) {
if (statusDoc.getElementsByTagName("IsPairedEndRun").getLength() > 0) {
boolean paired = Boolean.parseBoolean(statusDoc.getElementsByTagName("IsPairedEndRun").item(0).getTextContent().toLowerCase());
setPairedEnd(paired);
}
}
- String runDirRegex = "[\\d]+_([A-z0-9])+_([\\d])+_([A-z0-9_\\+\\-]*)";
+ String runDirRegex = "[\\d]+_([A-z0-9]\\-)+_([\\d])+_([A-z0-9_\\+\\-]*)";
Matcher m = Pattern.compile(runDirRegex).matcher(runName);
if (m.matches()) {
setPlatformRunId(Integer.parseInt(m.group(2)));
}
setAlias(runName);
setFilePath(runName);
setDescription(m.group(3));
setPlatformType(PlatformType.ILLUMINA);
setStatus(new IlluminaStatus(statusXml));
if (user != null) {
setSecurityProfile(new SecurityProfile(user));
}
else {
setSecurityProfile(new SecurityProfile());
}
}
else {
log.error("No status XML for this run");
}
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
log.error("Cannot parse status: " + statusXml);
e.printStackTrace();
}
}
public IlluminaRun(User user) {
setPlatformType(PlatformType.ILLUMINA);
setStatus(new StatusImpl());
setSecurityProfile(new SecurityProfile(user));
}
public void buildSubmission() {
/*
try {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
submissionDocument = docBuilder.newDocument();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
ERASubmissionFactory.generateFullRunSubmissionXML(submissionDocument, this);
*/
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
/*
if (getFlowcells() != null) {
sb.append(" : ");
for(Flowcell f: getFlowcells()) {
sb.append(f.toString());
}
}
*/
if (getSequencerPartitionContainers() != null) {
sb.append(" : ");
for(SequencerPartitionContainer f: getSequencerPartitionContainers()) {
sb.append(f.toString());
}
}
return sb.toString();
}
/**
* Method buildReport ...
*/
public void buildReport() {
}
}
| true | true | public IlluminaRun(String statusXml, User user) {
try {
Document statusDoc = SubmissionUtils.emptyDocument();
if (statusXml != null && !"".equals(statusXml)) {
SubmissionUtils.transform(new UnicodeReader(statusXml), statusDoc);
String runName = (statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
setPairedEnd(false);
if (!statusDoc.getDocumentElement().getTagName().equals("error")) {
if (statusDoc.getElementsByTagName("IsPairedEndRun").getLength() > 0) {
boolean paired = Boolean.parseBoolean(statusDoc.getElementsByTagName("IsPairedEndRun").item(0).getTextContent().toLowerCase());
setPairedEnd(paired);
}
}
String runDirRegex = "[\\d]+_([A-z0-9])+_([\\d])+_([A-z0-9_\\+\\-]*)";
Matcher m = Pattern.compile(runDirRegex).matcher(runName);
if (m.matches()) {
setPlatformRunId(Integer.parseInt(m.group(2)));
}
setAlias(runName);
setFilePath(runName);
setDescription(m.group(3));
setPlatformType(PlatformType.ILLUMINA);
setStatus(new IlluminaStatus(statusXml));
if (user != null) {
setSecurityProfile(new SecurityProfile(user));
}
else {
setSecurityProfile(new SecurityProfile());
}
}
else {
log.error("No status XML for this run");
}
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
log.error("Cannot parse status: " + statusXml);
e.printStackTrace();
}
}
| public IlluminaRun(String statusXml, User user) {
try {
Document statusDoc = SubmissionUtils.emptyDocument();
if (statusXml != null && !"".equals(statusXml)) {
SubmissionUtils.transform(new UnicodeReader(statusXml), statusDoc);
String runName = (statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
setPairedEnd(false);
if (!statusDoc.getDocumentElement().getTagName().equals("error")) {
if (statusDoc.getElementsByTagName("IsPairedEndRun").getLength() > 0) {
boolean paired = Boolean.parseBoolean(statusDoc.getElementsByTagName("IsPairedEndRun").item(0).getTextContent().toLowerCase());
setPairedEnd(paired);
}
}
String runDirRegex = "[\\d]+_([A-z0-9]\\-)+_([\\d])+_([A-z0-9_\\+\\-]*)";
Matcher m = Pattern.compile(runDirRegex).matcher(runName);
if (m.matches()) {
setPlatformRunId(Integer.parseInt(m.group(2)));
}
setAlias(runName);
setFilePath(runName);
setDescription(m.group(3));
setPlatformType(PlatformType.ILLUMINA);
setStatus(new IlluminaStatus(statusXml));
if (user != null) {
setSecurityProfile(new SecurityProfile(user));
}
else {
setSecurityProfile(new SecurityProfile());
}
}
else {
log.error("No status XML for this run");
}
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
log.error("Cannot parse status: " + statusXml);
e.printStackTrace();
}
}
|
diff --git a/Tanks/src/blueMaggot/BlueMaggot.java b/Tanks/src/blueMaggot/BlueMaggot.java
index 904e847..5c9fa20 100644
--- a/Tanks/src/blueMaggot/BlueMaggot.java
+++ b/Tanks/src/blueMaggot/BlueMaggot.java
@@ -1,183 +1,183 @@
package blueMaggot;
import entity.Tank;
import gfx.MenuBackground;
import gfx.MenuLevelSelect;
import gfx.MenuOptions;
import gfx.MenuTitle;
import gfx.ResourceManager;
import gfx.UIElement;
import gfx.MenuScoreBoard;
import inputhandler.InputHandler;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import baseGame.Rendering.*;
/**
* @author Habitats * this motherfucker starts the game
*/
public class BlueMaggot extends JFrame implements Runnable {
public InputHandler inputReal = new InputHandler();
private JLayeredPane layeredPane = new JLayeredPane();
private MenuTitle menuTitle;
private JPanel gamePanel;
public MenuScoreBoard uiScoreBoard;
public MenuLevelSelect menuLevelSelect;
public MenuOptions menuOptions;
public UIElement ui;
Game game;
private MenuBackground menuBackground;
public BlueMaggot() {
try {
ResourceManager. TANK1 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK2 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK3 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK4 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. SHELL = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Shell_temp.png")));
ResourceManager. SCOREBUBBLE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Scorebubble.png")));
ResourceManager. CROSSHAIR1 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR2 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR3 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR4 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. ROCKET = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Rocket_sheet.png")));
ResourceManager. MINE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Mine_sheet.png")));
ResourceManager. GRENADE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Grenade_temp.png")));
ResourceManager. PACKAGE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Package.png")));
ResourceManager. BUBBLEHEARTH = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/BubbleHearth.png")));
ResourceManager. AIRSTRIKEBEACON = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/AirStrikeBeacon.png")));
ResourceManager. BULLET = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Bullet.png")));
ResourceManager. COLORMASK = new Color(0x00FAE1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = getClass().getResourceAsStream("/graphics/Tank2.png");
Scanner scanner = new Scanner(stream);
ArrayList<Byte> bytes = new ArrayList<Byte>();
while(scanner.hasNextByte()){
bytes.add(scanner.nextByte());
}
System.out.println(bytes.size());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setPreferredSize(new Dimension(GameState.getInstance().width, GameState.getInstance().height));
+ setPreferredSize(new Dimension(GameState.getInstance().width, GameState.getInstance().height + 28));
setFocusable(true);
setResizable(false);
layeredPane.setBounds(0, 0, GameState.getInstance().width, GameState.getInstance().height);
layeredPane.setOpaque(false);
game = new blueMaggot.Game(this);
menuTitle = new MenuTitle(game, this);
menuOptions = new MenuOptions(game);
uiScoreBoard = new MenuScoreBoard(game);
menuLevelSelect = new MenuLevelSelect(game);
menuBackground = new MenuBackground(menuTitle);
gamePanel = new JPanel();
ui = new UIElement(0, 0, 700, 45, menuTitle.border, game);
layeredPane.add(gamePanel, new Integer(0));
layeredPane.add(ui, new Integer(1));
layeredPane.add(menuBackground, new Integer(9));
layeredPane.add(menuTitle, new Integer(10));
layeredPane.add(menuOptions, new Integer(11));
layeredPane.add(menuLevelSelect, new Integer(11));
layeredPane.add(uiScoreBoard, new Integer(12));
add(layeredPane);
pack();
setLocationRelativeTo(null);
setVisible(true);
repaint();
}
private void setUpGame() {
game.setPreferredSize(GameState.getInstance().dimension);
gamePanel.setLayout(new BorderLayout());
gamePanel.setBounds(0, 0, GameState.getInstance().width, GameState.getInstance().height);
gamePanel.add(game);
}
@Override
public void run() {
setUpGame();
}
public static void main(String[] args) {
(new BlueMaggot()).run();
}
public void tick() {
for (Tank tank : GameState.getInstance().players) {
if (tank.getNick() == null)
tank.setNick("Player");
}
if (inputReal.menu.clicked) {
inputReal.menu.clicked = false;
inputReal.releaseAll();
if (!menuTitle.isVisible()) {
menuTitle.setVisible(true);
menuBackground.setVisible(true);
menuTitle.repaint();
GameState.getInstance().setPaused(true);
}
}
if (GameState.getInstance().isRunning() && !ui.isVisible()) {
ui.setVisible(true);
}
// TODO: Implement scoreboard
// if (inputReal.tab.down) {
// uiScoreBoard.setVisible(true);
// } else
// uiScoreBoard.setVisible(false);
if (GameState.getInstance().isGameOver()) {
menuTitle.setVisible(true);
uiScoreBoard.setVisible(true);
GameState.getInstance().setPaused(true);
GameState.getInstance().setRunning(false);
menuBackground.setVisible(true);
menuTitle.repaint();
}
for (Tank tank : GameState.getInstance().players) {
if (tank.getScore() != tank.getOldScore()) {
tank.setOldScore(tank.getScore());
ui.repaint();
System.out.println("p" + tank.getId() + ": " + tank.getScore());
}
}
if (inputReal.down1.clicked || inputReal.down2.clicked) {
ui.repaint();
}
}
}
| true | true | public BlueMaggot() {
try {
ResourceManager. TANK1 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK2 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK3 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK4 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. SHELL = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Shell_temp.png")));
ResourceManager. SCOREBUBBLE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Scorebubble.png")));
ResourceManager. CROSSHAIR1 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR2 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR3 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR4 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. ROCKET = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Rocket_sheet.png")));
ResourceManager. MINE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Mine_sheet.png")));
ResourceManager. GRENADE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Grenade_temp.png")));
ResourceManager. PACKAGE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Package.png")));
ResourceManager. BUBBLEHEARTH = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/BubbleHearth.png")));
ResourceManager. AIRSTRIKEBEACON = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/AirStrikeBeacon.png")));
ResourceManager. BULLET = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Bullet.png")));
ResourceManager. COLORMASK = new Color(0x00FAE1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = getClass().getResourceAsStream("/graphics/Tank2.png");
Scanner scanner = new Scanner(stream);
ArrayList<Byte> bytes = new ArrayList<Byte>();
while(scanner.hasNextByte()){
bytes.add(scanner.nextByte());
}
System.out.println(bytes.size());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(GameState.getInstance().width, GameState.getInstance().height));
setFocusable(true);
setResizable(false);
layeredPane.setBounds(0, 0, GameState.getInstance().width, GameState.getInstance().height);
layeredPane.setOpaque(false);
game = new blueMaggot.Game(this);
menuTitle = new MenuTitle(game, this);
menuOptions = new MenuOptions(game);
uiScoreBoard = new MenuScoreBoard(game);
menuLevelSelect = new MenuLevelSelect(game);
menuBackground = new MenuBackground(menuTitle);
gamePanel = new JPanel();
ui = new UIElement(0, 0, 700, 45, menuTitle.border, game);
layeredPane.add(gamePanel, new Integer(0));
layeredPane.add(ui, new Integer(1));
layeredPane.add(menuBackground, new Integer(9));
layeredPane.add(menuTitle, new Integer(10));
layeredPane.add(menuOptions, new Integer(11));
layeredPane.add(menuLevelSelect, new Integer(11));
layeredPane.add(uiScoreBoard, new Integer(12));
add(layeredPane);
pack();
setLocationRelativeTo(null);
setVisible(true);
repaint();
}
| public BlueMaggot() {
try {
ResourceManager. TANK1 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK2 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK3 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. TANK4 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Tank2.png")));
ResourceManager. SHELL = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Shell_temp.png")));
ResourceManager. SCOREBUBBLE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Scorebubble.png")));
ResourceManager. CROSSHAIR1 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR2 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR3 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. CROSSHAIR4 = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Crosshair.png")));
ResourceManager. ROCKET = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Rocket_sheet.png")));
ResourceManager. MINE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Mine_sheet.png")));
ResourceManager. GRENADE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Grenade_temp.png")));
ResourceManager. PACKAGE = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Package.png")));
ResourceManager. BUBBLEHEARTH = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/BubbleHearth.png")));
ResourceManager. AIRSTRIKEBEACON = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/AirStrikeBeacon.png")));
ResourceManager. BULLET = new RGBImage(ImageIO.read(getClass().getResourceAsStream("/graphics/Bullet.png")));
ResourceManager. COLORMASK = new Color(0x00FAE1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = getClass().getResourceAsStream("/graphics/Tank2.png");
Scanner scanner = new Scanner(stream);
ArrayList<Byte> bytes = new ArrayList<Byte>();
while(scanner.hasNextByte()){
bytes.add(scanner.nextByte());
}
System.out.println(bytes.size());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(GameState.getInstance().width, GameState.getInstance().height + 28));
setFocusable(true);
setResizable(false);
layeredPane.setBounds(0, 0, GameState.getInstance().width, GameState.getInstance().height);
layeredPane.setOpaque(false);
game = new blueMaggot.Game(this);
menuTitle = new MenuTitle(game, this);
menuOptions = new MenuOptions(game);
uiScoreBoard = new MenuScoreBoard(game);
menuLevelSelect = new MenuLevelSelect(game);
menuBackground = new MenuBackground(menuTitle);
gamePanel = new JPanel();
ui = new UIElement(0, 0, 700, 45, menuTitle.border, game);
layeredPane.add(gamePanel, new Integer(0));
layeredPane.add(ui, new Integer(1));
layeredPane.add(menuBackground, new Integer(9));
layeredPane.add(menuTitle, new Integer(10));
layeredPane.add(menuOptions, new Integer(11));
layeredPane.add(menuLevelSelect, new Integer(11));
layeredPane.add(uiScoreBoard, new Integer(12));
add(layeredPane);
pack();
setLocationRelativeTo(null);
setVisible(true);
repaint();
}
|
diff --git a/src/bcut/UsefullThings.java b/src/bcut/UsefullThings.java
index b1a9d26..ce7bb7b 100644
--- a/src/bcut/UsefullThings.java
+++ b/src/bcut/UsefullThings.java
@@ -1,122 +1,122 @@
package bcut;
import java.util.logging.Level;
import net.minecraft.src.Block;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
import buildcraft.BuildCraftCore;
import buildcraft.core.DefaultProps;
import buildcraft.factory.BlockMiningWell;
import buildcraft.factory.TileQuarry;
import buildcraft.factory.network.PacketHandlerFactory;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
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.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import bcut.PacketHandler;
@Mod(name = "BuildCraft UsefullThings", version = "0.0.3", useMetadata = false, modid = "UsefullThings")
@NetworkMod(channels = {"bcut"}
,versionBounds = "[0.0.3,)"
,clientSideRequired = true
,serverSideRequired = false
//,packetHandler = PacketHandler.class
)
public class UsefullThings
{
public BlockUsefullThings usefullthingsBlock;
public int usefullthingsblockId;
public BlockLuminolamp luminolampBlock;
public int luminolampBlockId;
public static int rendererId;
@Instance("UsefullThings")
public static UsefullThings instance;
@SidedProxy(clientSide = "bcut.ClientProxy", serverSide = "bcut.CommonProxy")
public static CommonProxy proxy;
@PreInit
public void PreInit(FMLPreInitializationEvent evt)
{
Configuration cfg = new Configuration(evt.getSuggestedConfigurationFile());
try {
cfg.load();
} catch (Exception e) {
FMLLog.log(Level.SEVERE, e, "UsefullThings config error");
}
Property firstblockId = cfg.getOrCreateBlockIdProperty("cobblegen.id", 200);
Property luminolampId = cfg.getOrCreateBlockIdProperty("luminolamp.id", 201);
firstblockId.comment = "Block Id of cogglegen machines";
firstblockId.comment = "Block Id of luminescence lighting";
usefullthingsblockId = firstblockId.getInt(200);
luminolampBlockId = luminolampId.getInt(201);
cfg.save();
}
@Init
public void Init(FMLInitializationEvent evt) {
usefullthingsBlock = new BlockUsefullThings(usefullthingsblockId);
luminolampBlock = new BlockLuminolamp(luminolampBlockId);
GameRegistry.registerBlock(usefullthingsBlock, ItemBlockUsefullThing.class);
GameRegistry.registerBlock(luminolampBlock);
LanguageRegistry.addName(luminolampBlock, "Luminoforium white lamp");
GameRegistry.registerTileEntity(TileUsefullThings.class, "CobbleGen");
for (UsefullThingsType typ : UsefullThingsType.values()) {
GameRegistry.registerTileEntity(typ.TileClass, typ.name());
}
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,0),
new Object[] { "opo", "lgw", "opo",
'o', Block.obsidian,
'p', Block.pistonBase,
'l', Item.bucketLava,
'w', Item.bucketWater,
'g', BuildCraftCore.goldGearItem,
});
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,1),
new Object[] { "#g#", "###", "b#b",
'g', BuildCraftCore.goldGearItem,
'b', Block.blockSteel,
- '#', usefullthingsBlock
+ '#', new ItemStack(usefullthingsBlock, 1 ,0)
+ });
+ GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,2),
+ new Object[] { "#g#", "###", "b#b",
+ 'g', BuildCraftCore.goldGearItem,
+ 'b', Block.blockSteel,
+ '#', new ItemStack(usefullthingsBlock, 1 ,1)
});
-// GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,2),
-// new Object[] { "#g#", "###", "b#b",
-// 'g', BuildCraftCore.goldGearItem,
-// 'b', Block.blockSteel,
-// '#', "tile.cobblegen.1"
-// });
GameRegistry.addRecipe(new ItemStack(luminolampBlock, 1),
new Object[] { " b ", "rrr", " g ",
'g', Block.glass,
'r', Item.redstone,
'b', Block.fenceIron
});
}
@PostInit
public void PostInit(FMLPostInitializationEvent evt) {
}
}
| false | true | public void Init(FMLInitializationEvent evt) {
usefullthingsBlock = new BlockUsefullThings(usefullthingsblockId);
luminolampBlock = new BlockLuminolamp(luminolampBlockId);
GameRegistry.registerBlock(usefullthingsBlock, ItemBlockUsefullThing.class);
GameRegistry.registerBlock(luminolampBlock);
LanguageRegistry.addName(luminolampBlock, "Luminoforium white lamp");
GameRegistry.registerTileEntity(TileUsefullThings.class, "CobbleGen");
for (UsefullThingsType typ : UsefullThingsType.values()) {
GameRegistry.registerTileEntity(typ.TileClass, typ.name());
}
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,0),
new Object[] { "opo", "lgw", "opo",
'o', Block.obsidian,
'p', Block.pistonBase,
'l', Item.bucketLava,
'w', Item.bucketWater,
'g', BuildCraftCore.goldGearItem,
});
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,1),
new Object[] { "#g#", "###", "b#b",
'g', BuildCraftCore.goldGearItem,
'b', Block.blockSteel,
'#', usefullthingsBlock
});
// GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,2),
// new Object[] { "#g#", "###", "b#b",
// 'g', BuildCraftCore.goldGearItem,
// 'b', Block.blockSteel,
// '#', "tile.cobblegen.1"
// });
GameRegistry.addRecipe(new ItemStack(luminolampBlock, 1),
new Object[] { " b ", "rrr", " g ",
'g', Block.glass,
'r', Item.redstone,
'b', Block.fenceIron
});
}
| public void Init(FMLInitializationEvent evt) {
usefullthingsBlock = new BlockUsefullThings(usefullthingsblockId);
luminolampBlock = new BlockLuminolamp(luminolampBlockId);
GameRegistry.registerBlock(usefullthingsBlock, ItemBlockUsefullThing.class);
GameRegistry.registerBlock(luminolampBlock);
LanguageRegistry.addName(luminolampBlock, "Luminoforium white lamp");
GameRegistry.registerTileEntity(TileUsefullThings.class, "CobbleGen");
for (UsefullThingsType typ : UsefullThingsType.values()) {
GameRegistry.registerTileEntity(typ.TileClass, typ.name());
}
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,0),
new Object[] { "opo", "lgw", "opo",
'o', Block.obsidian,
'p', Block.pistonBase,
'l', Item.bucketLava,
'w', Item.bucketWater,
'g', BuildCraftCore.goldGearItem,
});
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,1),
new Object[] { "#g#", "###", "b#b",
'g', BuildCraftCore.goldGearItem,
'b', Block.blockSteel,
'#', new ItemStack(usefullthingsBlock, 1 ,0)
});
GameRegistry.addRecipe(new ItemStack(usefullthingsBlock, 1 ,2),
new Object[] { "#g#", "###", "b#b",
'g', BuildCraftCore.goldGearItem,
'b', Block.blockSteel,
'#', new ItemStack(usefullthingsBlock, 1 ,1)
});
GameRegistry.addRecipe(new ItemStack(luminolampBlock, 1),
new Object[] { " b ", "rrr", " g ",
'g', Block.glass,
'r', Item.redstone,
'b', Block.fenceIron
});
}
|
diff --git a/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java b/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java
index e12afae7c..1c1f5e6b8 100644
--- a/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java
+++ b/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java
@@ -1,353 +1,353 @@
/**
* Copyright 2011-2013 Asakusa Framework Team.
*
* 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.asakusafw.testdriver.excel;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.asakusafw.testdriver.core.DataModelDefinition;
import com.asakusafw.testdriver.core.DataModelReflection;
import com.asakusafw.testdriver.core.DataModelSink;
import com.asakusafw.testdriver.core.PropertyName;
import com.asakusafw.testdriver.core.PropertyType;
import com.asakusafw.testdriver.core.TestContext;
import com.asakusafw.testdriver.model.SimpleDataModelDefinition;
/**
* Test for {@link ExcelSheetSink}.
*/
public class ExcelSheetSinkTest {
static final DataModelDefinition<Simple> SIMPLE = new SimpleDataModelDefinition<Simple>(Simple.class);
/**
* Temporary folder.
*/
@Rule
public final TemporaryFolder folder = new TemporaryFolder();
/**
* simple.
* @throws Exception if occur
*/
@Test
public void simple() throws Exception {
verify("simple.xls");
}
/**
* using xslx.
* @throws Exception if occur
*/
@Test
public void xssf() throws Exception {
verify("simple.xlsx", ".xlsx");
}
/**
* automatically creates folder.
* @throws Exception if occur
*/
@Test
public void create_folder() throws Exception {
File container = folder.newFolder("middle");
File file = new File(container, "file.xls");
assertThat(container.delete(), is(true));
assertThat(file.isFile(), is(false));
ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file);
DataModelSink sink = factory.createSink(SIMPLE, new TestContext.Empty());
try {
sink.put(SIMPLE.toReflection(new Simple()));
} finally {
sink.close();
}
assertThat(file.isFile(), is(true));
}
/**
* multiple rows.
* @throws Exception if occur
*/
@Test
public void multiple() throws Exception {
verify("multiple.xls");
}
/**
* contains blank cells.
* @throws Exception if occur
*/
@Test
public void blank_cell() throws Exception {
verify("blank_cell.xls");
}
/**
* stringified by '.
* @throws Exception if occur
*/
@Test
public void stringify() throws Exception {
verify("stringify.xls");
}
/**
* empty string.
* @throws Exception if occur
*/
@Test
public void empty_string() throws Exception {
verify("empty_string.xls");
}
/**
* boolean values.
* @throws Exception if occur
*/
@Test
public void boolean_values() throws Exception {
verify("boolean.xls");
}
/**
* byte values.
* @throws Exception if occur
*/
@Test
public void byte_values() throws Exception {
verify("byte.xls");
}
/**
* short values.
* @throws Exception if occur
*/
@Test
public void short_values() throws Exception {
verify("short.xls");
}
/**
* int values.
* @throws Exception if occur
*/
@Test
public void int_values() throws Exception {
verify("int.xls");
}
/**
* long values.
* @throws Exception if occur
*/
@Test
public void long_values() throws Exception {
verify("long.xls");
}
/**
* float values.
* @throws Exception if occur
*/
@Test
public void float_values() throws Exception {
verify("float.xls");
}
/**
* double values.
* @throws Exception if occur
*/
@Test
public void double_values() throws Exception {
verify("double.xls");
}
/**
* big integer values.
* @throws Exception if occur
*/
@Test
public void integer_values() throws Exception {
verify("integer.xls");
}
/**
* big decimal values.
* @throws Exception if occur
*/
@Test
public void decimal_values() throws Exception {
verify("decimal.xls");
}
/**
* date values.
* @throws Exception if occur
*/
@Test
public void date_values() throws Exception {
verify("date.xls");
}
/**
* date values.
* @throws Exception if occur
*/
@Test
public void datetime_values() throws Exception {
verify("datetime.xls");
}
/**
* contains blank row.
* @throws Exception if occur
*/
@Test
public void blank_row() throws Exception {
verify("blank_row.xls");
}
/**
* contains blank row but is decorated.
* @throws Exception if occur
*/
@Test
public void decorated_blank_row() throws Exception {
verify("decorated_blank_row.xls");
}
/**
* many columns.
* @throws Exception if occur
*/
@Test
public void many_columns() throws Exception {
Object[] value = new Object[256];
Map<PropertyName, PropertyType> map = new TreeMap<PropertyName, PropertyType>();
for (int i = 0; i < value.length; i++) {
map.put(PropertyName.newInstance(String.format("p%04x", i)), PropertyType.INT);
value[i] = i;
}
ArrayModelDefinition def = new ArrayModelDefinition(map);
File file = folder.newFile("temp.xls");
ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file);
DataModelSink sink = factory.createSink(def, new TestContext.Empty());
try {
sink.put(def.toReflection(value));
} finally {
sink.close();
}
InputStream in = new FileInputStream(file);
try {
Workbook workbook = Util.openWorkbookFor(file.getPath(), in);
Sheet sheet = workbook.getSheetAt(0);
Row title = sheet.getRow(0);
- assertThat(title.getLastCellNum(), is((short) 255));
+ assertThat(title.getLastCellNum(), is((short) 256));
Row content = sheet.getRow(1);
for (int i = 0; i < title.getLastCellNum(); i++) {
assertThat(content.getCell(i).getNumericCellValue(), is((double) (Integer) value[i]));
}
} finally {
in.close();
}
}
private void verify(String file) throws IOException {
verify(file, ".xls");
}
private void verify(String file, String extension) throws IOException {
Set<DataModelReflection> expected = collect(open(file));
File temp = folder.newFile("temp" + extension);
ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(temp);
DataModelSink sink = factory.createSink(SIMPLE, new TestContext.Empty());
try {
for (DataModelReflection model : expected) {
sink.put(model);
}
} finally {
sink.close();
}
Set<DataModelReflection> actual = collect(open(temp.toURI().toURL()));
assertThat(actual, is(expected));
}
private Set<DataModelReflection> collect(ExcelSheetDataModelSource source) throws IOException {
Set<DataModelReflection> results = new HashSet<DataModelReflection>();
try {
while (true) {
DataModelReflection next = source.next();
if (next == null) {
break;
}
assertThat(next.toString(), results.contains(source), is(false));
results.add(next);
}
} finally {
source.close();
}
return results;
}
private ExcelSheetDataModelSource open(String file) throws IOException {
URL resource = getClass().getResource("data/" + file);
assertThat(file, resource, not(nullValue()));
return open(resource);
}
private ExcelSheetDataModelSource open(URL resource) throws IOException {
URI uri;
try {
uri = resource.toURI();
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
InputStream in = resource.openStream();
try {
Workbook book = Util.openWorkbookFor(resource.getFile(), in);
Sheet sheet = book.getSheetAt(0);
return new ExcelSheetDataModelSource(SIMPLE, uri, sheet);
} finally {
in.close();
}
}
}
| true | true | public void many_columns() throws Exception {
Object[] value = new Object[256];
Map<PropertyName, PropertyType> map = new TreeMap<PropertyName, PropertyType>();
for (int i = 0; i < value.length; i++) {
map.put(PropertyName.newInstance(String.format("p%04x", i)), PropertyType.INT);
value[i] = i;
}
ArrayModelDefinition def = new ArrayModelDefinition(map);
File file = folder.newFile("temp.xls");
ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file);
DataModelSink sink = factory.createSink(def, new TestContext.Empty());
try {
sink.put(def.toReflection(value));
} finally {
sink.close();
}
InputStream in = new FileInputStream(file);
try {
Workbook workbook = Util.openWorkbookFor(file.getPath(), in);
Sheet sheet = workbook.getSheetAt(0);
Row title = sheet.getRow(0);
assertThat(title.getLastCellNum(), is((short) 255));
Row content = sheet.getRow(1);
for (int i = 0; i < title.getLastCellNum(); i++) {
assertThat(content.getCell(i).getNumericCellValue(), is((double) (Integer) value[i]));
}
} finally {
in.close();
}
}
| public void many_columns() throws Exception {
Object[] value = new Object[256];
Map<PropertyName, PropertyType> map = new TreeMap<PropertyName, PropertyType>();
for (int i = 0; i < value.length; i++) {
map.put(PropertyName.newInstance(String.format("p%04x", i)), PropertyType.INT);
value[i] = i;
}
ArrayModelDefinition def = new ArrayModelDefinition(map);
File file = folder.newFile("temp.xls");
ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file);
DataModelSink sink = factory.createSink(def, new TestContext.Empty());
try {
sink.put(def.toReflection(value));
} finally {
sink.close();
}
InputStream in = new FileInputStream(file);
try {
Workbook workbook = Util.openWorkbookFor(file.getPath(), in);
Sheet sheet = workbook.getSheetAt(0);
Row title = sheet.getRow(0);
assertThat(title.getLastCellNum(), is((short) 256));
Row content = sheet.getRow(1);
for (int i = 0; i < title.getLastCellNum(); i++) {
assertThat(content.getCell(i).getNumericCellValue(), is((double) (Integer) value[i]));
}
} finally {
in.close();
}
}
|
diff --git a/p084.java b/p084.java
index 26ce60e..b3baade 100644
--- a/p084.java
+++ b/p084.java
@@ -1,125 +1,136 @@
/*
* Solution to Project Euler problem 84
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.util.Arrays;
import java.util.Random;
public final class p084 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p084().run());
}
private Random random = new Random();
/*
* This is a statistical sampling approximation algorithm that simply simulates the game for a fixed number of dice rolls.
* An exact algorithm would involve calculating the eigenvector of the largest eigenvalue of the transition matrix (which is practical),
* but averaging over all possible permutations of both the Chance and Community Chest decks (which is computationally infeasible).
*/
public String run() {
final int[] visitCounts = new int[40];
CardDeck chance = new CardDeck(16);
CardDeck communityChest = new CardDeck(16);
int consecutiveDoubles = 0;
int location = 0;
for (int i = 0; i < 100000000; i++) {
// Roll tetrahedral dice
int die0 = random.nextInt(4) + 1;
int die1 = random.nextInt(4) + 1;
- if (die0 == die1) {
+ if (die0 == die1)
consecutiveDoubles++;
- if (consecutiveDoubles == 3)
- location = 30;
- } else
+ else
consecutiveDoubles = 0;
- location = (location + die0 + die1) % 40;
+ if (consecutiveDoubles < 3)
+ location = (location + die0 + die1) % 40;
+ else {
+ location = 30;
+ consecutiveDoubles = 0;
+ }
// Process actions for some locations
switch (location) {
case 2: case 17: case 33: // Community chest
switch (communityChest.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
}
break;
case 7: case 22: case 36: // Chance
switch (chance.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
case 2: location = 11; break;
case 3: location = 24; break;
case 4: location = 39; break;
case 5: location = 5; break;
case 6: case 7: // Next railway
location = (location + 5) / 10 % 4 * 10 + 5;
break;
case 8: // Next utility
location = location > 12 && location < 28 ? 28 : 12;
break;
- case 9: location -= 3; break;
+ case 9:
+ location -= 3;
+ if (location == 33) {
+ switch (communityChest.nextCard()) {
+ case 0: location = 0; break;
+ case 1: location = 10; break;
+ }
+ }
+ break;
}
break;
// Go to jail
case 30:
location = 10;
break;
}
visitCounts[location]++;
}
// Embed index into count, invert so that maximum becomes minimum
for (int i = 0; i < visitCounts.length; i++)
visitCounts[i] = ~visitCounts[i] << 6 | i;
Arrays.sort(visitCounts);
String result = "";
for (int i = 0; i < 3; i++)
result += String.format("%02d", visitCounts[i] & 0x3F);
return result;
}
private class CardDeck {
private int[] cards;
private int index;
public CardDeck(int size) {
cards = new int[size];
for (int i = 0; i < cards.length; i++)
cards[i] = i;
index = size;
}
public int nextCard() {
if (index == cards.length) {
// Fisher-Yates shuffle
for (int i = cards.length - 1; i >= 0; i--) {
int j = random.nextInt(i + 1);
int temp = cards[i];
cards[i] = cards[j];
cards[j] = temp;
}
index = 0;
}
int result = cards[index];
index++;
return result;
}
}
}
| false | true | public String run() {
final int[] visitCounts = new int[40];
CardDeck chance = new CardDeck(16);
CardDeck communityChest = new CardDeck(16);
int consecutiveDoubles = 0;
int location = 0;
for (int i = 0; i < 100000000; i++) {
// Roll tetrahedral dice
int die0 = random.nextInt(4) + 1;
int die1 = random.nextInt(4) + 1;
if (die0 == die1) {
consecutiveDoubles++;
if (consecutiveDoubles == 3)
location = 30;
} else
consecutiveDoubles = 0;
location = (location + die0 + die1) % 40;
// Process actions for some locations
switch (location) {
case 2: case 17: case 33: // Community chest
switch (communityChest.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
}
break;
case 7: case 22: case 36: // Chance
switch (chance.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
case 2: location = 11; break;
case 3: location = 24; break;
case 4: location = 39; break;
case 5: location = 5; break;
case 6: case 7: // Next railway
location = (location + 5) / 10 % 4 * 10 + 5;
break;
case 8: // Next utility
location = location > 12 && location < 28 ? 28 : 12;
break;
case 9: location -= 3; break;
}
break;
// Go to jail
case 30:
location = 10;
break;
}
visitCounts[location]++;
}
// Embed index into count, invert so that maximum becomes minimum
for (int i = 0; i < visitCounts.length; i++)
visitCounts[i] = ~visitCounts[i] << 6 | i;
Arrays.sort(visitCounts);
String result = "";
for (int i = 0; i < 3; i++)
result += String.format("%02d", visitCounts[i] & 0x3F);
return result;
}
| public String run() {
final int[] visitCounts = new int[40];
CardDeck chance = new CardDeck(16);
CardDeck communityChest = new CardDeck(16);
int consecutiveDoubles = 0;
int location = 0;
for (int i = 0; i < 100000000; i++) {
// Roll tetrahedral dice
int die0 = random.nextInt(4) + 1;
int die1 = random.nextInt(4) + 1;
if (die0 == die1)
consecutiveDoubles++;
else
consecutiveDoubles = 0;
if (consecutiveDoubles < 3)
location = (location + die0 + die1) % 40;
else {
location = 30;
consecutiveDoubles = 0;
}
// Process actions for some locations
switch (location) {
case 2: case 17: case 33: // Community chest
switch (communityChest.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
}
break;
case 7: case 22: case 36: // Chance
switch (chance.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
case 2: location = 11; break;
case 3: location = 24; break;
case 4: location = 39; break;
case 5: location = 5; break;
case 6: case 7: // Next railway
location = (location + 5) / 10 % 4 * 10 + 5;
break;
case 8: // Next utility
location = location > 12 && location < 28 ? 28 : 12;
break;
case 9:
location -= 3;
if (location == 33) {
switch (communityChest.nextCard()) {
case 0: location = 0; break;
case 1: location = 10; break;
}
}
break;
}
break;
// Go to jail
case 30:
location = 10;
break;
}
visitCounts[location]++;
}
// Embed index into count, invert so that maximum becomes minimum
for (int i = 0; i < visitCounts.length; i++)
visitCounts[i] = ~visitCounts[i] << 6 | i;
Arrays.sort(visitCounts);
String result = "";
for (int i = 0; i < 3; i++)
result += String.format("%02d", visitCounts[i] & 0x3F);
return result;
}
|
diff --git a/core/src/main/java/org/dynjs/runtime/linker/PrimitivesLinker.java b/core/src/main/java/org/dynjs/runtime/linker/PrimitivesLinker.java
index 509f3791..719958fd 100644
--- a/core/src/main/java/org/dynjs/runtime/linker/PrimitivesLinker.java
+++ b/core/src/main/java/org/dynjs/runtime/linker/PrimitivesLinker.java
@@ -1,79 +1,79 @@
/**
* Copyright 2011 Douglas Campos
* Copyright 2011 dynjs contributors
*
* 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.dynjs.runtime.linker;
import org.dynalang.dynalink.linker.CallSiteDescriptor;
import org.dynalang.dynalink.linker.GuardedInvocation;
import org.dynalang.dynalink.linker.LinkRequest;
import org.dynalang.dynalink.linker.LinkerServices;
import org.dynalang.dynalink.linker.TypeBasedGuardingDynamicLinker;
import org.dynalang.dynalink.support.Guards;
import org.dynjs.runtime.extensions.BooleanOperations;
import org.dynjs.runtime.extensions.NumberOperations;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.util.HashMap;
import java.util.Map;
public class PrimitivesLinker implements TypeBasedGuardingDynamicLinker {
private static final Map<Class, Map<String, MethodHandle>> vtable = new HashMap() {{
put(Double.class, VTablePopulator.vtableFrom(NumberOperations.class));
put(Boolean.class, VTablePopulator.vtableFrom(BooleanOperations.class));
}};
@Override
public boolean canLinkType(Class<?> type) {
return vtable.containsKey(type);
}
@Override
public GuardedInvocation getGuardedInvocation(LinkRequest linkRequest, LinkerServices linkerServices) throws Exception {
Object[] arguments = linkRequest.getArguments();
Object receiver = arguments[0];
Class<? extends Object> receiverClass = receiver.getClass();
Map<String, MethodHandle> vtable = PrimitivesLinker.vtable.get(receiverClass);
CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
MethodType targetMethodType = methodTypeForArguments(descriptor, arguments, receiverClass);
String selector = descriptor.getName() + targetMethodType.toMethodDescriptorString();
MethodHandle handle = vtable.get(selector);
if (handle != null) {
- if (descriptor.getMethodType().toMethodDescriptorString() != handle.type().toMethodDescriptorString()) {
+ if (!descriptor.getMethodType().equals(handle.type())) {
handle = linkerServices.asType(handle, descriptor.getMethodType());
}
return new GuardedInvocation(handle, Guards.isInstance(receiverClass, 1, descriptor.getMethodType()));
}
return null;
}
private MethodType methodTypeForArguments(CallSiteDescriptor descriptor, Object[] arguments, Class<? extends Object> receiverClass) {
MethodType targetMethodType = MethodType.genericMethodType(arguments.length);
Class<?> originalReturnType = descriptor.getMethodType().returnType();
if (originalReturnType != Object.class) {
targetMethodType = targetMethodType.changeReturnType(originalReturnType);
} else {
targetMethodType = targetMethodType.changeReturnType(receiverClass);
}
for (int i = 0; i < arguments.length; i++) {
Object argument = arguments[i];
targetMethodType = targetMethodType.changeParameterType(i, argument.getClass());
}
return targetMethodType;
}
}
| true | true | public GuardedInvocation getGuardedInvocation(LinkRequest linkRequest, LinkerServices linkerServices) throws Exception {
Object[] arguments = linkRequest.getArguments();
Object receiver = arguments[0];
Class<? extends Object> receiverClass = receiver.getClass();
Map<String, MethodHandle> vtable = PrimitivesLinker.vtable.get(receiverClass);
CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
MethodType targetMethodType = methodTypeForArguments(descriptor, arguments, receiverClass);
String selector = descriptor.getName() + targetMethodType.toMethodDescriptorString();
MethodHandle handle = vtable.get(selector);
if (handle != null) {
if (descriptor.getMethodType().toMethodDescriptorString() != handle.type().toMethodDescriptorString()) {
handle = linkerServices.asType(handle, descriptor.getMethodType());
}
return new GuardedInvocation(handle, Guards.isInstance(receiverClass, 1, descriptor.getMethodType()));
}
return null;
}
| public GuardedInvocation getGuardedInvocation(LinkRequest linkRequest, LinkerServices linkerServices) throws Exception {
Object[] arguments = linkRequest.getArguments();
Object receiver = arguments[0];
Class<? extends Object> receiverClass = receiver.getClass();
Map<String, MethodHandle> vtable = PrimitivesLinker.vtable.get(receiverClass);
CallSiteDescriptor descriptor = linkRequest.getCallSiteDescriptor();
MethodType targetMethodType = methodTypeForArguments(descriptor, arguments, receiverClass);
String selector = descriptor.getName() + targetMethodType.toMethodDescriptorString();
MethodHandle handle = vtable.get(selector);
if (handle != null) {
if (!descriptor.getMethodType().equals(handle.type())) {
handle = linkerServices.asType(handle, descriptor.getMethodType());
}
return new GuardedInvocation(handle, Guards.isInstance(receiverClass, 1, descriptor.getMethodType()));
}
return null;
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/AcquisitionProcess.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/AcquisitionProcess.java
index 7c830c63..65eae06f 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/AcquisitionProcess.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/AcquisitionProcess.java
@@ -1,341 +1,342 @@
/*
* @(#)AcquisitionProcess.java
*
* Copyright 2009 Instituto Superior Tecnico
* Founding Authors: Luis Cruz, Nuno Ochoa, Paulo Abrantes
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the Expenditure Tracking Module.
*
* The Expenditure Tracking Module 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.
*
* The Expenditure Tracking Module 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 the Expenditure Tracking Module. If not, see <http://www.gnu.org/licenses/>.
*
*/
package pt.ist.expenditureTrackingSystem.domain.acquisitions;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import myorg.domain.User;
import myorg.domain.exceptions.DomainException;
import myorg.domain.util.Money;
import myorg.util.ClassNameBundle;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
import pt.ist.expenditureTrackingSystem.domain.ProcessState;
import pt.ist.expenditureTrackingSystem.domain.dto.PayingUnitTotalBean;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
import pt.ist.expenditureTrackingSystem.domain.organization.Supplier;
import pt.ist.expenditureTrackingSystem.domain.organization.Unit;
@ClassNameBundle(bundle = "resources/ExpenditureResources")
/**
*
* @author Paulo Abrantes
* @author Luis Cruz
* @author João Alfaiate
*
*/
public abstract class AcquisitionProcess extends AcquisitionProcess_Base {
public AcquisitionProcess() {
super();
setOjbConcreteClass(getClass().getName());
super.setSkipSupplierFundAllocation(Boolean.FALSE);
setProcessNumber(constructProcessNumber());
}
protected String constructProcessNumber() {
final ExpenditureTrackingSystem instance = getExpenditureTrackingSystem();
if (instance.hasProcessPrefix()) {
return instance.getInstitutionalProcessNumberPrefix() + "/" + getYear() + "/" + getAcquisitionProcessNumber();
}
return getYear() + "/" + getAcquisitionProcessNumber();
}
@Override
public void migrateProcessNumber() {
final ExpenditureTrackingSystem instance = getExpenditureTrackingSystem();
if (!getProcessNumber().startsWith(instance.getInstitutionalProcessNumberPrefix())) {
setProcessNumber(constructProcessNumber());
}
}
public boolean isAvailableForCurrentUser() {
final Person loggedPerson = getLoggedPerson();
return loggedPerson != null && isAvailableForPerson(loggedPerson);
}
public boolean isAvailableForPerson(final Person person) {
final User user = person.getUser();
return ExpenditureTrackingSystem.isAcquisitionCentralGroupMember(user)
|| ExpenditureTrackingSystem.isAcquisitionCentralManagerGroupMember(user)
|| ExpenditureTrackingSystem.isAccountingManagerGroupMember(user)
|| ExpenditureTrackingSystem.isProjectAccountingManagerGroupMember(user)
|| ExpenditureTrackingSystem.isTreasuryMemberGroupMember(user)
|| ExpenditureTrackingSystem.isAcquisitionsProcessAuditorGroupMember(user)
|| ExpenditureTrackingSystem.isFundCommitmentManagerGroupMember(user)
+ || ExpenditureTrackingSystem.isFundCommitmentManagerGroupMember(user)
|| getRequestor() == person
|| isTakenByPerson(person.getUser())
|| getRequestingUnit().isResponsible(person)
|| isResponsibleForAtLeastOnePayingUnit(person)
|| isAccountingEmployee(person)
|| isProjectAccountingEmployee(person)
|| isTreasuryMember(person)
|| isObserver(person);
}
@Override
public boolean isAccessible(User user) {
return isAvailableForPerson(user.getExpenditurePerson());
}
public boolean isActive() {
return getLastAcquisitionProcessState().isActive();
}
public AcquisitionProcessState getAcquisitionProcessState() {
return getLastAcquisitionProcessState();
}
protected AcquisitionProcessState getLastAcquisitionProcessState() {
AcquisitionProcessState state = (AcquisitionProcessState) getCurrentProcessState();
if (state == null) {
state = (AcquisitionProcessState) Collections.max(getProcessStates(), ProcessState.COMPARATOR_BY_WHEN);
}
return state;
}
public AcquisitionProcessStateType getAcquisitionProcessStateType() {
return getLastAcquisitionProcessState().getAcquisitionProcessStateType();
}
@Override
public boolean isPendingApproval() {
return getLastAcquisitionProcessState().isPendingApproval();
}
public boolean isApproved() {
final AcquisitionProcessStateType acquisitionProcessStateType = getAcquisitionProcessStateType();
return acquisitionProcessStateType.compareTo(AcquisitionProcessStateType.SUBMITTED_FOR_FUNDS_ALLOCATION) <= 0
&& isActive();
}
public boolean isAllocatedToSupplier() {
return getLastAcquisitionProcessState().isAllocatedToSupplier();
}
public boolean isAllocatedToUnit() {
return getLastAcquisitionProcessState().isAllocatedToUnit();
}
public boolean isPayed() {
return getLastAcquisitionProcessState().isPayed();
}
public boolean isAllocatedToUnit(Unit unit) {
return isAllocatedToUnit() && getPayingUnits().contains(unit);
}
public boolean isAcquisitionProcessed() {
return getLastAcquisitionProcessState().isAcquisitionProcessed();
}
public boolean isInvoiceReceived() {
final AcquisitionRequest acquisitionRequest = getAcquisitionRequest();
return getLastAcquisitionProcessState().isInvoiceReceived();
}
public boolean isPastInvoiceReceived() {
final AcquisitionRequest acquisitionRequest = getAcquisitionRequest();
return getLastAcquisitionProcessState().isPastInvoiceReceived();
}
public Unit getUnit() {
return getRequestingUnit();
}
public Money getAmountAllocatedToUnit(Unit unit) {
return getAcquisitionRequest().getAmountAllocatedToUnit(unit);
}
public Money getAcquisitionRequestValueLimit() {
return null;
}
public Unit getRequestingUnit() {
return getAcquisitionRequest().getRequestingUnit();
}
public boolean isAllowedToViewCostCenterExpenditures() {
try {
return (getUnit() != null && isResponsibleForUnit())
|| ExpenditureTrackingSystem.isAccountingManagerGroupMember()
|| ExpenditureTrackingSystem.isProjectAccountingManagerGroupMember()
|| isAccountingEmployee()
|| isProjectAccountingEmployee()
|| ExpenditureTrackingSystem.isManager();
} catch (Exception e) {
e.printStackTrace();
throw new Error(e);
}
}
public boolean isAllowedToViewSupplierExpenditures() {
return ExpenditureTrackingSystem.isAcquisitionCentralGroupMember()
|| ExpenditureTrackingSystem.isAcquisitionCentralManagerGroupMember()
|| ExpenditureTrackingSystem.isManager();
}
public boolean checkRealValues() {
return getAcquisitionRequest().checkRealValues();
}
public Integer getYear() {
return getPaymentProcessYear().getYear();
}
/*
* use getProcessNumber() instead
*/
@Deprecated
public String getAcquisitionProcessId() {
return getProcessNumber();
}
public boolean isProcessFlowCharAvailable() {
return false;
}
public List<AcquisitionProcessStateType> getAvailableStates() {
return Collections.emptyList();
}
public String getAllocationIds() {
StringBuilder builder = new StringBuilder();
for (PayingUnitTotalBean bean : getAcquisitionRequest().getTotalAmountsForEachPayingUnit()) {
builder.append(bean.getFinancer().getFundAllocationIds());
}
return builder.toString();
}
public String getEffectiveAllocationIds() {
StringBuilder builder = new StringBuilder();
for (PayingUnitTotalBean bean : getAcquisitionRequest().getTotalAmountsForEachPayingUnit()) {
builder.append(bean.getFinancer().getEffectiveFundAllocationIds());
}
return builder.toString();
}
public AcquisitionRequest getRequest() {
return getAcquisitionRequest();
}
@Override
public boolean isInGenesis() {
return getAcquisitionProcessState().isInGenesis();
}
@Override
public boolean isInApprovedState() {
return getAcquisitionProcessState().isInApprovedState();
}
@Override
public boolean isPendingFundAllocation() {
return getAcquisitionProcessState().isInAllocatedToSupplierState();
}
@Override
public boolean isInAuthorizedState() {
return getAcquisitionProcessState().isAuthorized();
}
@Override
public boolean isInvoiceConfirmed() {
return getAcquisitionProcessState().isInvoiceConfirmed();
}
@Override
public boolean isAllocatedPermanently() {
return getAcquisitionProcessState().isAllocatedPermanently();
}
@Override
public Collection<Supplier> getSuppliers() {
return getRequest().getSuppliers();
}
@Override
public String getProcessStateName() {
return getLastAcquisitionProcessState().getLocalizedName();
}
@Override
public int getProcessStateOrder() {
return getLastAcquisitionProcessState().getAcquisitionProcessStateType().ordinal();
}
public Boolean getShouldSkipSupplierFundAllocation() {
return getSkipSupplierFundAllocation();
}
public String getAcquisitionRequestDocumentID() {
return hasPurchaseOrderDocument() ? getPurchaseOrderDocument().getRequestId() : ExpenditureTrackingSystem.getInstance()
.nextAcquisitionRequestDocumentID();
}
// TODO: delete this method... it's not used.
public AcquisitionProposalDocument getAcquisitionProposalDocument() {
List<AcquisitionProposalDocument> files = getFiles(AcquisitionProposalDocument.class);
return files.isEmpty() ? null : files.get(0);
}
public boolean hasAcquisitionProposalDocument() {
return !getFiles(AcquisitionProposalDocument.class).isEmpty();
}
public void setPurchaseOrderDocument(PurchaseOrderDocument document) {
addFiles(document);
}
public PurchaseOrderDocument getPurchaseOrderDocument() {
List<PurchaseOrderDocument> files = getFiles(PurchaseOrderDocument.class);
if (files.size() > 1) {
throw new DomainException("error.should.only.have.one.purchaseOrder");
}
return files.isEmpty() ? null : files.get(0);
}
public boolean hasPurchaseOrderDocument() {
return !getFiles(PurchaseOrderDocument.class).isEmpty();
}
@Override
public boolean isCanceled() {
return getLastAcquisitionProcessState().isCanceled()
|| getLastAcquisitionProcessState().isRejected();
}
@Override
public void revertToState(ProcessState processState) {
final AcquisitionProcessState acquisitionProcessState = (AcquisitionProcessState) processState;
final AcquisitionProcessStateType acquisitionProcessStateType = acquisitionProcessState.getAcquisitionProcessStateType();
if (acquisitionProcessStateType != null && acquisitionProcessStateType != AcquisitionProcessStateType.CANCELED) {
new AcquisitionProcessState(this, acquisitionProcessStateType);
}
}
}
| true | true | public boolean isAvailableForPerson(final Person person) {
final User user = person.getUser();
return ExpenditureTrackingSystem.isAcquisitionCentralGroupMember(user)
|| ExpenditureTrackingSystem.isAcquisitionCentralManagerGroupMember(user)
|| ExpenditureTrackingSystem.isAccountingManagerGroupMember(user)
|| ExpenditureTrackingSystem.isProjectAccountingManagerGroupMember(user)
|| ExpenditureTrackingSystem.isTreasuryMemberGroupMember(user)
|| ExpenditureTrackingSystem.isAcquisitionsProcessAuditorGroupMember(user)
|| ExpenditureTrackingSystem.isFundCommitmentManagerGroupMember(user)
|| getRequestor() == person
|| isTakenByPerson(person.getUser())
|| getRequestingUnit().isResponsible(person)
|| isResponsibleForAtLeastOnePayingUnit(person)
|| isAccountingEmployee(person)
|| isProjectAccountingEmployee(person)
|| isTreasuryMember(person)
|| isObserver(person);
}
| public boolean isAvailableForPerson(final Person person) {
final User user = person.getUser();
return ExpenditureTrackingSystem.isAcquisitionCentralGroupMember(user)
|| ExpenditureTrackingSystem.isAcquisitionCentralManagerGroupMember(user)
|| ExpenditureTrackingSystem.isAccountingManagerGroupMember(user)
|| ExpenditureTrackingSystem.isProjectAccountingManagerGroupMember(user)
|| ExpenditureTrackingSystem.isTreasuryMemberGroupMember(user)
|| ExpenditureTrackingSystem.isAcquisitionsProcessAuditorGroupMember(user)
|| ExpenditureTrackingSystem.isFundCommitmentManagerGroupMember(user)
|| ExpenditureTrackingSystem.isFundCommitmentManagerGroupMember(user)
|| getRequestor() == person
|| isTakenByPerson(person.getUser())
|| getRequestingUnit().isResponsible(person)
|| isResponsibleForAtLeastOnePayingUnit(person)
|| isAccountingEmployee(person)
|| isProjectAccountingEmployee(person)
|| isTreasuryMember(person)
|| isObserver(person);
}
|
diff --git a/src/jvm/clj_json/JsonExt.java b/src/jvm/clj_json/JsonExt.java
index b327cbb..a1fde0a 100644
--- a/src/jvm/clj_json/JsonExt.java
+++ b/src/jvm/clj_json/JsonExt.java
@@ -1,143 +1,143 @@
package clj_json;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonGenerator;
import java.math.BigInteger;
import java.util.Map;
import java.util.Set;
import clojure.lang.IFn;
import clojure.lang.ISeq;
import clojure.lang.IPersistentMap;
import clojure.lang.IPersistentVector;
import clojure.lang.IMapEntry;
import clojure.lang.Keyword;
import clojure.lang.PersistentArrayMap;
import clojure.lang.PersistentVector;
import clojure.lang.ITransientMap;
import clojure.lang.IPersistentList;
import clojure.lang.ITransientCollection;
import clojure.lang.Seqable;
public class JsonExt {
public static class Generator {
final JsonGenerator jg;
final Map coercions;
public Generator(JsonGenerator jg, Map coercions){
this.jg = jg;
this.coercions = coercions;
}
public void generate(Object obj) throws Exception{
- if (this.coercions != null) {
+ if (this.coercions != null && obj != null) {
IFn fn;
while ((fn = (IFn)coercions.get(obj.getClass())) != null){
obj = fn.invoke(obj);
}
}
if (obj instanceof String) {
jg.writeString((String) obj);
} else if (obj instanceof Number) {
if (obj instanceof Integer) {
jg.writeNumber((Integer) obj);
} else if (obj instanceof Long) {
jg.writeNumber((Long) obj);
} else if (obj instanceof BigInteger) {
jg.writeNumber((BigInteger) obj);
} else if (obj instanceof Double) {
jg.writeNumber((Double) obj);
} else if (obj instanceof Float) {
jg.writeNumber((Float) obj);
}
} else if (obj instanceof Boolean) {
jg.writeBoolean((Boolean) obj);
} else if (obj == null) {
jg.writeNull();
} else if (obj instanceof Keyword) {
jg.writeString(((Keyword) obj).getName());
} else if (obj instanceof IPersistentMap) {
IPersistentMap map = (IPersistentMap) obj;
ISeq mSeq = map.seq();
jg.writeStartObject();
while (mSeq != null) {
IMapEntry me = (IMapEntry) mSeq.first();
Object key = me.key();
if (key instanceof Keyword) {
jg.writeFieldName(((Keyword) key).getName());
} else if (key instanceof Integer) {
jg.writeFieldName(((Integer) key).toString());
} else if (key instanceof BigInteger) {
jg.writeFieldName(((BigInteger) key).toString());
} else if (key instanceof Long) {
jg.writeFieldName(((Long) key).toString());
} else {
jg.writeFieldName((String) key);
}
generate(me.val());
mSeq = mSeq.next();
}
jg.writeEndObject();
} else if (obj instanceof Iterable) {
jg.writeStartArray();
for (Object o : (Iterable)obj){
generate(o);
}
jg.writeEndArray();
}
else {
throw new Exception("Cannot generate " + obj);
}
}
}
public static void generate(JsonGenerator jg, Map coercions, Object obj) throws Exception {
Generator g = new Generator(jg, coercions);
g.generate(obj);
}
public static Object parse(JsonParser jp, boolean first, boolean keywords, Object eofValue) throws Exception {
if (first) {
jp.nextToken();
if (jp.getCurrentToken() == null) {
return eofValue;
}
}
switch (jp.getCurrentToken()) {
case START_OBJECT:
ITransientMap map = PersistentArrayMap.EMPTY.asTransient();
jp.nextToken();
while (jp.getCurrentToken() != JsonToken.END_OBJECT) {
String keyStr = jp.getText();
jp.nextToken();
Object key = keywords ? Keyword.intern(keyStr) : keyStr;
map = map.assoc(key, parse(jp, false, keywords, eofValue));
jp.nextToken();
}
return map.persistent();
case START_ARRAY:
ITransientCollection vec = PersistentVector.EMPTY.asTransient();
jp.nextToken();
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
vec = vec.conj(parse(jp, false, keywords, eofValue));
jp.nextToken();
}
return vec.persistent();
case VALUE_STRING:
return jp.getText();
case VALUE_NUMBER_INT:
return jp.getNumberValue();
case VALUE_NUMBER_FLOAT:
return jp.getDoubleValue();
case VALUE_TRUE:
return Boolean.TRUE;
case VALUE_FALSE:
return Boolean.FALSE;
case VALUE_NULL:
return null;
default:
throw new Exception("Cannot parse " + jp.getCurrentToken());
}
}
}
| true | true | public void generate(Object obj) throws Exception{
if (this.coercions != null) {
IFn fn;
while ((fn = (IFn)coercions.get(obj.getClass())) != null){
obj = fn.invoke(obj);
}
}
if (obj instanceof String) {
jg.writeString((String) obj);
} else if (obj instanceof Number) {
if (obj instanceof Integer) {
jg.writeNumber((Integer) obj);
} else if (obj instanceof Long) {
jg.writeNumber((Long) obj);
} else if (obj instanceof BigInteger) {
jg.writeNumber((BigInteger) obj);
} else if (obj instanceof Double) {
jg.writeNumber((Double) obj);
} else if (obj instanceof Float) {
jg.writeNumber((Float) obj);
}
} else if (obj instanceof Boolean) {
jg.writeBoolean((Boolean) obj);
} else if (obj == null) {
jg.writeNull();
} else if (obj instanceof Keyword) {
jg.writeString(((Keyword) obj).getName());
} else if (obj instanceof IPersistentMap) {
IPersistentMap map = (IPersistentMap) obj;
ISeq mSeq = map.seq();
jg.writeStartObject();
while (mSeq != null) {
IMapEntry me = (IMapEntry) mSeq.first();
Object key = me.key();
if (key instanceof Keyword) {
jg.writeFieldName(((Keyword) key).getName());
} else if (key instanceof Integer) {
jg.writeFieldName(((Integer) key).toString());
} else if (key instanceof BigInteger) {
jg.writeFieldName(((BigInteger) key).toString());
} else if (key instanceof Long) {
jg.writeFieldName(((Long) key).toString());
} else {
jg.writeFieldName((String) key);
}
generate(me.val());
mSeq = mSeq.next();
}
jg.writeEndObject();
} else if (obj instanceof Iterable) {
jg.writeStartArray();
for (Object o : (Iterable)obj){
generate(o);
}
jg.writeEndArray();
}
else {
throw new Exception("Cannot generate " + obj);
}
}
| public void generate(Object obj) throws Exception{
if (this.coercions != null && obj != null) {
IFn fn;
while ((fn = (IFn)coercions.get(obj.getClass())) != null){
obj = fn.invoke(obj);
}
}
if (obj instanceof String) {
jg.writeString((String) obj);
} else if (obj instanceof Number) {
if (obj instanceof Integer) {
jg.writeNumber((Integer) obj);
} else if (obj instanceof Long) {
jg.writeNumber((Long) obj);
} else if (obj instanceof BigInteger) {
jg.writeNumber((BigInteger) obj);
} else if (obj instanceof Double) {
jg.writeNumber((Double) obj);
} else if (obj instanceof Float) {
jg.writeNumber((Float) obj);
}
} else if (obj instanceof Boolean) {
jg.writeBoolean((Boolean) obj);
} else if (obj == null) {
jg.writeNull();
} else if (obj instanceof Keyword) {
jg.writeString(((Keyword) obj).getName());
} else if (obj instanceof IPersistentMap) {
IPersistentMap map = (IPersistentMap) obj;
ISeq mSeq = map.seq();
jg.writeStartObject();
while (mSeq != null) {
IMapEntry me = (IMapEntry) mSeq.first();
Object key = me.key();
if (key instanceof Keyword) {
jg.writeFieldName(((Keyword) key).getName());
} else if (key instanceof Integer) {
jg.writeFieldName(((Integer) key).toString());
} else if (key instanceof BigInteger) {
jg.writeFieldName(((BigInteger) key).toString());
} else if (key instanceof Long) {
jg.writeFieldName(((Long) key).toString());
} else {
jg.writeFieldName((String) key);
}
generate(me.val());
mSeq = mSeq.next();
}
jg.writeEndObject();
} else if (obj instanceof Iterable) {
jg.writeStartArray();
for (Object o : (Iterable)obj){
generate(o);
}
jg.writeEndArray();
}
else {
throw new Exception("Cannot generate " + obj);
}
}
|
diff --git a/galaxy-config-bundler/src/main/java/com/proofpoint/galaxy/configbundler/AddComponentCommand.java b/galaxy-config-bundler/src/main/java/com/proofpoint/galaxy/configbundler/AddComponentCommand.java
index 259adc2..1d8147b 100644
--- a/galaxy-config-bundler/src/main/java/com/proofpoint/galaxy/configbundler/AddComponentCommand.java
+++ b/galaxy-config-bundler/src/main/java/com/proofpoint/galaxy/configbundler/AddComponentCommand.java
@@ -1,38 +1,38 @@
package com.proofpoint.galaxy.configbundler;
import com.google.common.base.Preconditions;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.iq80.cli.Arguments;
import org.iq80.cli.Command;
import java.io.File;
import java.util.concurrent.Callable;
@Command(name = "add", description = "Add config for a component")
public class AddComponentCommand
implements Callable<Void>
{
@Arguments(required = true)
public String component;
@Override
public Void call()
throws Exception
{
Preconditions.checkNotNull(component, "component is null");
Git git = Git.open(new File("."));
Model model = new Model(git);
- Preconditions.checkArgument(model.getBundle(component) != null, "Component already exists: %s", component);
+ Preconditions.checkArgument(model.getBundle(component) == null, "Component already exists: %s", component);
Bundle bundle = model.createBundle(component);
model.activateBundle(bundle);
return null;
}
}
| true | true | public Void call()
throws Exception
{
Preconditions.checkNotNull(component, "component is null");
Git git = Git.open(new File("."));
Model model = new Model(git);
Preconditions.checkArgument(model.getBundle(component) != null, "Component already exists: %s", component);
Bundle bundle = model.createBundle(component);
model.activateBundle(bundle);
return null;
}
| public Void call()
throws Exception
{
Preconditions.checkNotNull(component, "component is null");
Git git = Git.open(new File("."));
Model model = new Model(git);
Preconditions.checkArgument(model.getBundle(component) == null, "Component already exists: %s", component);
Bundle bundle = model.createBundle(component);
model.activateBundle(bundle);
return null;
}
|
diff --git a/src/main/java/com/erdfelt/maven/xmlfresh/XmlFormatter.java b/src/main/java/com/erdfelt/maven/xmlfresh/XmlFormatter.java
index 1c10b9b..debc71f 100644
--- a/src/main/java/com/erdfelt/maven/xmlfresh/XmlFormatter.java
+++ b/src/main/java/com/erdfelt/maven/xmlfresh/XmlFormatter.java
@@ -1,101 +1,99 @@
package com.erdfelt.maven.xmlfresh;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.maven.plugin.MojoFailureException;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xml.sax.SAXException;
import com.erdfelt.maven.xmlfresh.io.IO;
public class XmlFormatter
{
private Tidy tidy;
public XmlFormatter()
{
tidy = new Tidy();
// Properties can be found at http://tidy.sourceforge.net/docs/quickref.html
Properties props = new Properties();
props.setProperty("output-xml","true");
props.setProperty("input-xml","true");
props.setProperty("add-xml-space","false");
props.setProperty("add-xml-decl","true");
- props.setProperty("char-encoding","utf8");
- props.setProperty("output-encoding","utf8");
props.setProperty("wrap","120");
props.setProperty("indent","true");
props.setProperty("indent-spaces","2");
// Not present in jtidy (yet)
// props.setProperty("sort-attributes","true");
// props.setProperty("hide-end-tags","false");
tidy.setConfigurationFromProps(props);
// Make output quiet
tidy.setOnlyErrors(true);
tidy.setQuiet(true);
// TODO configure tidy here
}
/**
* Read xml file using JTidy
*/
public Document read(File xmlFile) throws IOException, ParserConfigurationException, SAXException
{
FileReader reader = null;
try
{
reader = new FileReader(xmlFile);
return tidy.parseDOM(reader,null);
}
finally
{
IO.close(reader);
}
}
public void writePretty(File xmlFile, Document doc) throws IOException
{
FileOutputStream out = null;
try
{
System.out.printf("Writing XML: %s%n",xmlFile);
out = new FileOutputStream(xmlFile,false);
writePretty(out,doc);
}
finally
{
IO.close(out);
}
}
public void writePretty(OutputStream out, Document doc) throws IOException
{
tidy.pprint(doc,out);
}
public void format(File file) throws MojoFailureException
{
try
{
Document doc = read(file);
writePretty(file,doc);
}
catch (Throwable t)
{
throw new MojoFailureException("Failed to format XML: " + file,t);
}
}
}
| true | true | public XmlFormatter()
{
tidy = new Tidy();
// Properties can be found at http://tidy.sourceforge.net/docs/quickref.html
Properties props = new Properties();
props.setProperty("output-xml","true");
props.setProperty("input-xml","true");
props.setProperty("add-xml-space","false");
props.setProperty("add-xml-decl","true");
props.setProperty("char-encoding","utf8");
props.setProperty("output-encoding","utf8");
props.setProperty("wrap","120");
props.setProperty("indent","true");
props.setProperty("indent-spaces","2");
// Not present in jtidy (yet)
// props.setProperty("sort-attributes","true");
// props.setProperty("hide-end-tags","false");
tidy.setConfigurationFromProps(props);
// Make output quiet
tidy.setOnlyErrors(true);
tidy.setQuiet(true);
// TODO configure tidy here
}
| public XmlFormatter()
{
tidy = new Tidy();
// Properties can be found at http://tidy.sourceforge.net/docs/quickref.html
Properties props = new Properties();
props.setProperty("output-xml","true");
props.setProperty("input-xml","true");
props.setProperty("add-xml-space","false");
props.setProperty("add-xml-decl","true");
props.setProperty("wrap","120");
props.setProperty("indent","true");
props.setProperty("indent-spaces","2");
// Not present in jtidy (yet)
// props.setProperty("sort-attributes","true");
// props.setProperty("hide-end-tags","false");
tidy.setConfigurationFromProps(props);
// Make output quiet
tidy.setOnlyErrors(true);
tidy.setQuiet(true);
// TODO configure tidy here
}
|
diff --git a/java/opennlp/textgrounder/models/Model.java b/java/opennlp/textgrounder/models/Model.java
index 3f060a02..11d5fb95 100644
--- a/java/opennlp/textgrounder/models/Model.java
+++ b/java/opennlp/textgrounder/models/Model.java
@@ -1,483 +1,484 @@
package opennlp.textgrounder.models;
import java.io.IOException;
import opennlp.textgrounder.textstructs.TokenArrayBuffer;
import opennlp.textgrounder.textstructs.TextProcessor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import opennlp.textgrounder.gazetteers.*;
import opennlp.textgrounder.geo.*;
import opennlp.textgrounder.textstructs.*;
import opennlp.textgrounder.models.callbacks.*;
import opennlp.textgrounder.ners.*;
import opennlp.textgrounder.topostructs.*;
/**
* Base abstract class for all training models. Defines some methods for
* interfacing with gazetteers. Declares some fields that deal with regions
* and placenames.
*
* @author
*/
public abstract class Model {
// Minimum number of pixels the (small) square region (NOT our Region) represented by each city must occupy on the screen for its label to appear:
private final static int MIN_LOD_PIXELS = 16;
/**
* Number of paragraphs to consider as one document.
*/
protected int paragraphsAsDocs;
/**
* Dimensions of regionArray.
*/
protected int regionArrayWidth, regionArrayHeight;
/**
* Array of locations that have been identified in training data
*/
protected List<Location> locations;
/**
* Training data
*/
protected String inputPath;
/**
* Name of kml file (i.e. Google Earth format xml) to generate output to
*/
protected String kmlOutputFilename;
/**
* Height of bars for Google Earth KML output
*/
protected int barScale = 50000;
/**
* Gazetteer that holds geographic information
*/
protected Gazetteer gazetteer;
/**
* Array of array of toponym indices by document. This includes only the
* toponyms and none of the non-toponyms.
*/
protected TextProcessor textProcessor;
/**
* Quick lookup table for gazetteer info based on toponym
*/
protected Hashtable<String, List<Location>> gazCache;
/**
* Size of regions on cartesian reduction of globe. Globe is defined to be
* 360 degrees longitude and 180 degrees latitude
*/
protected double degreesPerRegion;
/**
* Array of regions defined by dividing globe dimensions by degreesPerRegion.
*/
protected Region[][] regionArray;
/**
* Number of regions which have been activated in regionArray
*/
protected int activeRegions;
/**
* Collection of training data
*/
protected Lexicon lexicon;
/**
* Flag that tells system to ignore the input file(s) and instead run on every locality in the gazetteer
*/
protected File inputFile;
protected boolean runWholeGazetteer = false;
protected int windowSize;
protected TokenArrayBuffer tokenArrayBuffer;
//protected int indexInTAB = 0;
public Model() {
}
public Model(Gazetteer gaz, int bscale, int paragraphsAsDocs) {
barScale = bscale;
gazetteer = gaz;
lexicon = new Lexicon();
}
public Model(CommandLineOptions options) throws Exception {
runWholeGazetteer = options.getRunWholeGazetteer();
if (!runWholeGazetteer) {
inputPath = options.getTrainInputPath();
if (inputPath == null) {
System.out.println("Error: You must specify an input filename with the -i flag.");
System.exit(0);
}
inputFile = new File(inputPath);
} else {
inputPath = null;
inputFile = null;
}
String gazTypeArg = options.getGazetteType().toLowerCase();
if (gazTypeArg.startsWith("c")) {
gazetteer = new CensusGazetteer();
} else if (gazTypeArg.startsWith("n")) {
gazetteer = new NGAGazetteer();
} else if (gazTypeArg.startsWith("u")) {
gazetteer = new USGSGazetteer();
} else if (gazTypeArg.startsWith("w")) {
gazetteer = new WGGazetteer();
} else if (gazTypeArg.startsWith("t")) {
gazetteer = new TRGazetteer();
} else {
System.err.println("Error: unrecognized gazetteer type: " + gazTypeArg);
System.err.println("Please enter w, c, u, g, or t.");
System.exit(0);
//myGaz = new WGGazetteer();
}
kmlOutputFilename = options.getKMLOutputFilename();
degreesPerRegion = options.getDegreesPerRegion();
if (!runWholeGazetteer) {
gazCache = new Hashtable<String, List<Location>>();
paragraphsAsDocs = options.getParagraphsAsDocs();
lexicon = new Lexicon();
textProcessor = new TextProcessor(lexicon, paragraphsAsDocs);
}
barScale = options.getBarScale();
windowSize = options.getWindowSize();
}
public void initializeRegionArray() {
activeRegions = 0;
regionArrayWidth = 360 / (int) degreesPerRegion;
regionArrayHeight = 180 / (int) degreesPerRegion;
regionArray = new Region[regionArrayWidth][regionArrayHeight];
for (int w = 0; w < regionArrayWidth; w++) {
for (int h = 0; h < regionArrayHeight; h++) {
regionArray[w][h] = null;
}
}
}
public void printRegionArray() {
System.out.println();
for (int h = 0; h < regionArrayHeight; h++) {
for (int w = 0; w < regionArrayWidth; w++) {
if (regionArray[w][h] == null) {
System.out.print("0");
} else {
System.out.print("1");
}
}
System.out.println();
}
System.out.println(activeRegions + " active regions for this document out of a possible "
+ (regionArrayHeight * regionArrayWidth) + " (region size = "
+ degreesPerRegion + " x " + degreesPerRegion + " degrees).");
}
public void activateRegionsForWholeGaz() throws Exception {
System.out.println("Running whole gazetteer through system...");
//locations = new ArrayList<Location>();
locations = gazetteer.getAllLocalities();
addLocationsToRegionArray(locations);
//locations = null; //////////////// uncomment this to get a null pointer but much faster termination
// if you only want to know the number of active regions :)
}
/**
* Remove punctuation from first and last characters of a string
*
* @param aString String to strip
* @return Input stripped of punctuation
*/
protected String stripPunc(String aString) {
while (aString.length() > 0 && !Character.isLetterOrDigit(aString.charAt(0))) {
aString = aString.substring(1);
}
while (aString.length() > 0 && !Character.isLetterOrDigit(aString.charAt(aString.length() - 1))) {
aString = aString.substring(0, aString.length() - 1);
}
return aString;
}
/**
* Add locations to the 2D regionArray. To be used by classes that
* do not use a RegionMapperCallback.
*
* @param locs list of locations.
*/
protected void addLocationsToRegionArray(List<Location> locs) {
addLocationsToRegionArray(locs, new NullRegionMapperCallback());
}
/**
* Add locations to 2D regionArray. To be used by classes and methods that
* use a RegionMapperCallback
*
* @param locs list of locations
* @param regionMapper callback class for handling mappings of locations
* and regions
*/
protected void addLocationsToRegionArray(List<Location> locs,
RegionMapperCallback regionMapper) {
for (Location loc : locs) {
/*if(loc.coord.latitude < -180.0 || loc.coord.longitude > 180.0
|| loc.coord.longitude < -90.0 || loc.coord.longitude > 900) {
// switched?
}*/
int curX = (int) (loc.coord.latitude + 180) / (int) degreesPerRegion;
int curY = (int) (loc.coord.longitude + 90) / (int) degreesPerRegion;
//System.out.println(loc.coord.latitude + ", " + loc.coord.longitude + " goes to");
//System.out.println(curX + " " + curY);
if(curX < 0 || curY < 0) {
if(curX < 0) curX = 0;
if(curY < 0) curY = 0;
System.err.println("Warning: " + loc.name + " had invalid coordinates (" + loc.coord + "); mapping it to [" + curX + "][" + curY + "]");
}
if (regionArray[curX][curY] == null) {
double minLon = loc.coord.longitude - loc.coord.longitude % degreesPerRegion;
double maxLon = minLon + degreesPerRegion;
double minLat = loc.coord.latitude - loc.coord.latitude % degreesPerRegion;
double maxLat = minLat + degreesPerRegion;
regionArray[curX][curY] = new Region(minLon, maxLon, minLat, maxLat);
activeRegions++;
}
regionMapper.addToPlace(loc, regionArray[curX][curY]);
}
}
public void writeXMLFile(String inputFilename) throws Exception {
writeXMLFile(inputFilename, kmlOutputFilename, locations);
}
public void processPath() throws Exception {
tokenArrayBuffer = new TokenArrayBuffer(lexicon);
processPath(inputFile, textProcessor, tokenArrayBuffer, new NullStopwordList());
tokenArrayBuffer.convertToPrimitiveArrays();
}
public void processPath(File myPath, TextProcessor textProcessor,
TokenArrayBuffer tokenArrayBuffer, StopwordList stopwordList) throws IOException {
if (myPath.isDirectory()) {
for (String pathname : myPath.list()) {
processPath(new File(myPath.getCanonicalPath() + File.separator + pathname), textProcessor, tokenArrayBuffer, stopwordList);
}
} else {
textProcessor.addToponymsFromFile(myPath.getCanonicalPath(), tokenArrayBuffer, stopwordList);
}
}
/**
* Output tagged and disambiguated placenames to Google Earth kml file.
*
* @throws Exception
*/
public void writeXMLFile() throws Exception {
if (!runWholeGazetteer) {
writeXMLFile(inputPath, kmlOutputFilename, locations);
} else {
writeXMLFile("WHOLE_GAZETTEER", kmlOutputFilename, locations);
}
}
/**
* Output tagged and disambiguated placenames to Google Earth kml file.
*
* @param inputPath
* @param kmlOutputFilename
* @param locations
* @throws Exception
*/
public void writeXMLFile(String inputFilename, String outputFilename,
List<Location> locations) throws Exception {
BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename));
int dotKmlIndex = outputFilename.lastIndexOf(".kml");
String contextFilename = outputFilename.substring(0, dotKmlIndex) + "-context.kml";
BufferedWriter contextOut = new BufferedWriter(new FileWriter(contextFilename));
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
+ "\t<Document>\n"
+ "\t\t<Style id=\"bar\">\n"
+ "\t\t\t<PolyStyle>\n"
+ "\t\t\t\t<outline>0</outline>\n"
+ "\t\t\t</PolyStyle>\n"
+ "\t\t\t<IconStyle>\n"
+ "\t\t\t\t<Icon></Icon>\n"
+ "\t\t\t</IconStyle>\n"
+ "\t\t</Style>\n"
+ "\t\t<Folder>\n"
+ "\t\t\t<name>" + inputFilename + "</name>\n"
+ "\t\t\t<open>1</open>\n"
+ "\t\t\t<description>Distribution of place names found in " + inputFilename + "</description>\n"
+ "\t\t\t<LookAt>\n"
+ "\t\t\t\t<latitude>42</latitude>\n"
+ "\t\t\t\t<longitude>-102</longitude>\n"
+ "\t\t\t\t<altitude>0</altitude>\n"
+ "\t\t\t\t<range>5000000</range>\n"
+ "\t\t\t\t<tilt>53.454348562403</tilt>\n"
+ "\t\t\t\t<heading>0</heading>\n"
+ "\t\t\t</LookAt>\n");
contextOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
+ "\t<Document>\n"
+ "\t\t<Style id=\"context\">\n"
+ "\t\t\t<LabelStyle>\n"
+ "\t\t\t\t<scale>0</scale>\n"
+ "\t\t\t</LabelStyle>\n"
+ "\t\t</Style>\n"
+ "\t\t<Folder>\n"
+ "\t\t\t<name>" + inputFilename + " CONTEXTS</name>\n"
+ "\t\t\t<open>1</open>\n"
+ "\t\t\t<description>Contexts of place names found in " + inputFilename + "</description>\n"
+ "\t\t\t<LookAt>\n"
+ "\t\t\t\t<latitude>42</latitude>\n"
+ "\t\t\t\t<longitude>-102</longitude>\n"
+ "\t\t\t\t<altitude>0</altitude>\n"
+ "\t\t\t\t<range>5000000</range>\n"
+ "\t\t\t\t<tilt>53.454348562403</tilt>\n"
+ "\t\t\t\t<heading>0</heading>\n"
+ "\t\t\t</LookAt>\n");
/*TObjectIntIterator<String> placeIterator = placeCounts.iterator();
for (int i = placeCounts.size(); i-- > 0;) {
placeIterator.advance();
String placename = placeIterator.key();
double height = Math.log(placeIterator.value()) * barScale;
Coordinate coord;
if(gazetteer instanceof WGGazetteer)
coord = ((WGGazetteer)gazetteer).baselineGet(placename);
else
coord = gazetteer.get(placename);
if(coord.longitude == 9999.99) // sentinel
continue;*/
for (int i = 0; i < locations.size(); i++) {//Location loc : locations) {
Location loc = locations.get(i);
double height = Math.log(loc.count) * barScale;
double radius = .15;
//String kmlPolygon = coord.toKMLPolygon(4,radius,height); // a square
String kmlPolygon = loc.coord.toKMLPolygon(10, radius, height);
String placename = loc.name;
Coordinate coord = loc.coord;
out.write("\t\t\t<Placemark>\n"
+ "\t\t\t\t<name>" + placename + "</name>\n"
+ "\t\t\t\t<Region>"
+ "\t\t\t\t\t<LatLonAltBox>"
+ "\t\t\t\t\t\t<north>" + (coord.longitude + radius) + "</north>"
+ "\t\t\t\t\t\t<south>" + (coord.longitude - radius) + "</south>"
+ "\t\t\t\t\t\t<east>" + (coord.latitude + radius) + "</east>"
+ "\t\t\t\t\t\t<west>" + (coord.latitude - radius) + "</west>"
+ "\t\t\t\t\t</LatLonAltBox>"
+ "\t\t\t\t\t<Lod>"
+ "\t\t\t\t\t\t<minLodPixels>" + MIN_LOD_PIXELS + "</minLodPixels>"
+ "\t\t\t\t\t</Lod>"
+ "\t\t\t\t</Region>"
+ "\t\t\t\t<styleUrl>#bar</styleUrl>\n"
+ "\t\t\t\t<Point>\n"
+ "\t\t\t\t\t<coordinates>\n"
+ "\t\t\t\t\t\t" + coord + ""
+ "\t\t\t\t\t</coordinates>"
+ "\t\t\t\t</Point>"
+ "\t\t\t</Placemark>"
+ "\t\t\t<Placemark>"
+ "\t\t\t\t<name>" + placename + " POLYGON</name>"
+ "\t\t\t\t<styleUrl>#bar</styleUrl>"
+ "\t\t\t\t<Style><PolyStyle><color>dc0155ff</color></PolyStyle></Style>"
+ "\t\t\t\t<Polygon>"
+ "\t\t\t\t\t<extrude>1</extrude><tessellate>1</tessellate>"
+ "\t\t\t\t\t<altitudeMode>relativeToGround</altitudeMode>"
+ "\t\t\t\t\t<outerBoundaryIs>"
+ "\t\t\t\t\t\t<LinearRing>"
+ "\t\t\t\t\t\t\t" + kmlPolygon + ""
+ "\t\t\t\t\t\t</LinearRing>"
+ "\t\t\t\t\t</outerBoundaryIs>"
+ "\t\t\t\t</Polygon>"
+ "\t\t\t</Placemark>\n");
//System.out.println("Contexts for " + placename);
/*while(indexInTAB < tokenArrayBuffer.toponymVector.size() && tokenArrayBuffer.toponymVector.get(indexInTAB) == 0) {
indexInTAB++;
}*/
for (int j = 0; j < loc.backPointers.size(); j++) {
int index = loc.backPointers.get(j);
String context = tokenArrayBuffer.getContextAround(index, windowSize, true);
+ context = context.replaceAll("<", "<"); // sanitization
Coordinate spiralPoint = coord.getNthSpiralPoint(j, 0.13);
contextOut.write("\t\t\t<Placemark>\n"
+ "\t\t\t\t<name>" + placename + " #" + (j + 1) + "</name>\n"
+ "\t\t\t\t<description>" + context + "</description>\n"
+ "\t\t\t\t<Region>"
+ "\t\t\t\t\t<LatLonAltBox>"
+ "\t\t\t\t\t\t<north>" + (spiralPoint.longitude + radius) + "</north>"
+ "\t\t\t\t\t\t<south>" + (spiralPoint.longitude - radius) + "</south>"
+ "\t\t\t\t\t\t<east>" + (spiralPoint.latitude + radius) + "</east>"
+ "\t\t\t\t\t\t<west>" + (spiralPoint.latitude - radius) + "</west>"
+ "\t\t\t\t\t</LatLonAltBox>"
+ "\t\t\t\t\t<Lod>"
+ "\t\t\t\t\t\t<minLodPixels>" + MIN_LOD_PIXELS + "</minLodPixels>"
+ "\t\t\t\t\t</Lod>"
+ "\t\t\t\t</Region>"
+ "\t\t\t\t<styleUrl>#context</styleUrl>\n"
+ "\t\t\t\t<Point>\n"
+ "\t\t\t\t\t<coordinates>" + spiralPoint + "</coordinates>\n"
+ "\t\t\t\t</Point>\n"
+ "\t\t\t</Placemark>\n");
}
//indexInTAB++;
//if(i >= 10) System.exit(0);
}
out.write("\t\t</Folder>\n\t</Document>\n</kml>");
contextOut.write("\t\t</Folder>\n\t</Document>\n</kml>");
out.close();
contextOut.close();
}
/**
* Train model. For access from main routines.
*/
public abstract void train();
/**
* @return the kmlOutputFilename
*/
public String getOutputFilename() {
return kmlOutputFilename;
}
/**
* @return the inputFile
*/
public File getInputFile() {
return inputFile;
}
/**
* @return the textProcessor
*/
public TextProcessor getTextProcessor() {
return textProcessor;
}
}
| true | true | public void writeXMLFile(String inputFilename, String outputFilename,
List<Location> locations) throws Exception {
BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename));
int dotKmlIndex = outputFilename.lastIndexOf(".kml");
String contextFilename = outputFilename.substring(0, dotKmlIndex) + "-context.kml";
BufferedWriter contextOut = new BufferedWriter(new FileWriter(contextFilename));
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
+ "\t<Document>\n"
+ "\t\t<Style id=\"bar\">\n"
+ "\t\t\t<PolyStyle>\n"
+ "\t\t\t\t<outline>0</outline>\n"
+ "\t\t\t</PolyStyle>\n"
+ "\t\t\t<IconStyle>\n"
+ "\t\t\t\t<Icon></Icon>\n"
+ "\t\t\t</IconStyle>\n"
+ "\t\t</Style>\n"
+ "\t\t<Folder>\n"
+ "\t\t\t<name>" + inputFilename + "</name>\n"
+ "\t\t\t<open>1</open>\n"
+ "\t\t\t<description>Distribution of place names found in " + inputFilename + "</description>\n"
+ "\t\t\t<LookAt>\n"
+ "\t\t\t\t<latitude>42</latitude>\n"
+ "\t\t\t\t<longitude>-102</longitude>\n"
+ "\t\t\t\t<altitude>0</altitude>\n"
+ "\t\t\t\t<range>5000000</range>\n"
+ "\t\t\t\t<tilt>53.454348562403</tilt>\n"
+ "\t\t\t\t<heading>0</heading>\n"
+ "\t\t\t</LookAt>\n");
contextOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
+ "\t<Document>\n"
+ "\t\t<Style id=\"context\">\n"
+ "\t\t\t<LabelStyle>\n"
+ "\t\t\t\t<scale>0</scale>\n"
+ "\t\t\t</LabelStyle>\n"
+ "\t\t</Style>\n"
+ "\t\t<Folder>\n"
+ "\t\t\t<name>" + inputFilename + " CONTEXTS</name>\n"
+ "\t\t\t<open>1</open>\n"
+ "\t\t\t<description>Contexts of place names found in " + inputFilename + "</description>\n"
+ "\t\t\t<LookAt>\n"
+ "\t\t\t\t<latitude>42</latitude>\n"
+ "\t\t\t\t<longitude>-102</longitude>\n"
+ "\t\t\t\t<altitude>0</altitude>\n"
+ "\t\t\t\t<range>5000000</range>\n"
+ "\t\t\t\t<tilt>53.454348562403</tilt>\n"
+ "\t\t\t\t<heading>0</heading>\n"
+ "\t\t\t</LookAt>\n");
/*TObjectIntIterator<String> placeIterator = placeCounts.iterator();
for (int i = placeCounts.size(); i-- > 0;) {
placeIterator.advance();
String placename = placeIterator.key();
double height = Math.log(placeIterator.value()) * barScale;
Coordinate coord;
if(gazetteer instanceof WGGazetteer)
coord = ((WGGazetteer)gazetteer).baselineGet(placename);
else
coord = gazetteer.get(placename);
if(coord.longitude == 9999.99) // sentinel
continue;*/
for (int i = 0; i < locations.size(); i++) {//Location loc : locations) {
Location loc = locations.get(i);
double height = Math.log(loc.count) * barScale;
double radius = .15;
//String kmlPolygon = coord.toKMLPolygon(4,radius,height); // a square
String kmlPolygon = loc.coord.toKMLPolygon(10, radius, height);
String placename = loc.name;
Coordinate coord = loc.coord;
out.write("\t\t\t<Placemark>\n"
+ "\t\t\t\t<name>" + placename + "</name>\n"
+ "\t\t\t\t<Region>"
+ "\t\t\t\t\t<LatLonAltBox>"
+ "\t\t\t\t\t\t<north>" + (coord.longitude + radius) + "</north>"
+ "\t\t\t\t\t\t<south>" + (coord.longitude - radius) + "</south>"
+ "\t\t\t\t\t\t<east>" + (coord.latitude + radius) + "</east>"
+ "\t\t\t\t\t\t<west>" + (coord.latitude - radius) + "</west>"
+ "\t\t\t\t\t</LatLonAltBox>"
+ "\t\t\t\t\t<Lod>"
+ "\t\t\t\t\t\t<minLodPixels>" + MIN_LOD_PIXELS + "</minLodPixels>"
+ "\t\t\t\t\t</Lod>"
+ "\t\t\t\t</Region>"
+ "\t\t\t\t<styleUrl>#bar</styleUrl>\n"
+ "\t\t\t\t<Point>\n"
+ "\t\t\t\t\t<coordinates>\n"
+ "\t\t\t\t\t\t" + coord + ""
+ "\t\t\t\t\t</coordinates>"
+ "\t\t\t\t</Point>"
+ "\t\t\t</Placemark>"
+ "\t\t\t<Placemark>"
+ "\t\t\t\t<name>" + placename + " POLYGON</name>"
+ "\t\t\t\t<styleUrl>#bar</styleUrl>"
+ "\t\t\t\t<Style><PolyStyle><color>dc0155ff</color></PolyStyle></Style>"
+ "\t\t\t\t<Polygon>"
+ "\t\t\t\t\t<extrude>1</extrude><tessellate>1</tessellate>"
+ "\t\t\t\t\t<altitudeMode>relativeToGround</altitudeMode>"
+ "\t\t\t\t\t<outerBoundaryIs>"
+ "\t\t\t\t\t\t<LinearRing>"
+ "\t\t\t\t\t\t\t" + kmlPolygon + ""
+ "\t\t\t\t\t\t</LinearRing>"
+ "\t\t\t\t\t</outerBoundaryIs>"
+ "\t\t\t\t</Polygon>"
+ "\t\t\t</Placemark>\n");
//System.out.println("Contexts for " + placename);
/*while(indexInTAB < tokenArrayBuffer.toponymVector.size() && tokenArrayBuffer.toponymVector.get(indexInTAB) == 0) {
indexInTAB++;
}*/
for (int j = 0; j < loc.backPointers.size(); j++) {
int index = loc.backPointers.get(j);
String context = tokenArrayBuffer.getContextAround(index, windowSize, true);
Coordinate spiralPoint = coord.getNthSpiralPoint(j, 0.13);
contextOut.write("\t\t\t<Placemark>\n"
+ "\t\t\t\t<name>" + placename + " #" + (j + 1) + "</name>\n"
+ "\t\t\t\t<description>" + context + "</description>\n"
+ "\t\t\t\t<Region>"
+ "\t\t\t\t\t<LatLonAltBox>"
+ "\t\t\t\t\t\t<north>" + (spiralPoint.longitude + radius) + "</north>"
+ "\t\t\t\t\t\t<south>" + (spiralPoint.longitude - radius) + "</south>"
+ "\t\t\t\t\t\t<east>" + (spiralPoint.latitude + radius) + "</east>"
+ "\t\t\t\t\t\t<west>" + (spiralPoint.latitude - radius) + "</west>"
+ "\t\t\t\t\t</LatLonAltBox>"
+ "\t\t\t\t\t<Lod>"
+ "\t\t\t\t\t\t<minLodPixels>" + MIN_LOD_PIXELS + "</minLodPixels>"
+ "\t\t\t\t\t</Lod>"
+ "\t\t\t\t</Region>"
+ "\t\t\t\t<styleUrl>#context</styleUrl>\n"
+ "\t\t\t\t<Point>\n"
+ "\t\t\t\t\t<coordinates>" + spiralPoint + "</coordinates>\n"
+ "\t\t\t\t</Point>\n"
+ "\t\t\t</Placemark>\n");
}
//indexInTAB++;
//if(i >= 10) System.exit(0);
}
out.write("\t\t</Folder>\n\t</Document>\n</kml>");
contextOut.write("\t\t</Folder>\n\t</Document>\n</kml>");
out.close();
contextOut.close();
}
/**
* Train model. For access from main routines.
*/
public abstract void train();
/**
* @return the kmlOutputFilename
*/
public String getOutputFilename() {
return kmlOutputFilename;
}
/**
* @return the inputFile
*/
public File getInputFile() {
return inputFile;
}
/**
* @return the textProcessor
*/
public TextProcessor getTextProcessor() {
return textProcessor;
}
}
| public void writeXMLFile(String inputFilename, String outputFilename,
List<Location> locations) throws Exception {
BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename));
int dotKmlIndex = outputFilename.lastIndexOf(".kml");
String contextFilename = outputFilename.substring(0, dotKmlIndex) + "-context.kml";
BufferedWriter contextOut = new BufferedWriter(new FileWriter(contextFilename));
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
+ "\t<Document>\n"
+ "\t\t<Style id=\"bar\">\n"
+ "\t\t\t<PolyStyle>\n"
+ "\t\t\t\t<outline>0</outline>\n"
+ "\t\t\t</PolyStyle>\n"
+ "\t\t\t<IconStyle>\n"
+ "\t\t\t\t<Icon></Icon>\n"
+ "\t\t\t</IconStyle>\n"
+ "\t\t</Style>\n"
+ "\t\t<Folder>\n"
+ "\t\t\t<name>" + inputFilename + "</name>\n"
+ "\t\t\t<open>1</open>\n"
+ "\t\t\t<description>Distribution of place names found in " + inputFilename + "</description>\n"
+ "\t\t\t<LookAt>\n"
+ "\t\t\t\t<latitude>42</latitude>\n"
+ "\t\t\t\t<longitude>-102</longitude>\n"
+ "\t\t\t\t<altitude>0</altitude>\n"
+ "\t\t\t\t<range>5000000</range>\n"
+ "\t\t\t\t<tilt>53.454348562403</tilt>\n"
+ "\t\t\t\t<heading>0</heading>\n"
+ "\t\t\t</LookAt>\n");
contextOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
+ "\t<Document>\n"
+ "\t\t<Style id=\"context\">\n"
+ "\t\t\t<LabelStyle>\n"
+ "\t\t\t\t<scale>0</scale>\n"
+ "\t\t\t</LabelStyle>\n"
+ "\t\t</Style>\n"
+ "\t\t<Folder>\n"
+ "\t\t\t<name>" + inputFilename + " CONTEXTS</name>\n"
+ "\t\t\t<open>1</open>\n"
+ "\t\t\t<description>Contexts of place names found in " + inputFilename + "</description>\n"
+ "\t\t\t<LookAt>\n"
+ "\t\t\t\t<latitude>42</latitude>\n"
+ "\t\t\t\t<longitude>-102</longitude>\n"
+ "\t\t\t\t<altitude>0</altitude>\n"
+ "\t\t\t\t<range>5000000</range>\n"
+ "\t\t\t\t<tilt>53.454348562403</tilt>\n"
+ "\t\t\t\t<heading>0</heading>\n"
+ "\t\t\t</LookAt>\n");
/*TObjectIntIterator<String> placeIterator = placeCounts.iterator();
for (int i = placeCounts.size(); i-- > 0;) {
placeIterator.advance();
String placename = placeIterator.key();
double height = Math.log(placeIterator.value()) * barScale;
Coordinate coord;
if(gazetteer instanceof WGGazetteer)
coord = ((WGGazetteer)gazetteer).baselineGet(placename);
else
coord = gazetteer.get(placename);
if(coord.longitude == 9999.99) // sentinel
continue;*/
for (int i = 0; i < locations.size(); i++) {//Location loc : locations) {
Location loc = locations.get(i);
double height = Math.log(loc.count) * barScale;
double radius = .15;
//String kmlPolygon = coord.toKMLPolygon(4,radius,height); // a square
String kmlPolygon = loc.coord.toKMLPolygon(10, radius, height);
String placename = loc.name;
Coordinate coord = loc.coord;
out.write("\t\t\t<Placemark>\n"
+ "\t\t\t\t<name>" + placename + "</name>\n"
+ "\t\t\t\t<Region>"
+ "\t\t\t\t\t<LatLonAltBox>"
+ "\t\t\t\t\t\t<north>" + (coord.longitude + radius) + "</north>"
+ "\t\t\t\t\t\t<south>" + (coord.longitude - radius) + "</south>"
+ "\t\t\t\t\t\t<east>" + (coord.latitude + radius) + "</east>"
+ "\t\t\t\t\t\t<west>" + (coord.latitude - radius) + "</west>"
+ "\t\t\t\t\t</LatLonAltBox>"
+ "\t\t\t\t\t<Lod>"
+ "\t\t\t\t\t\t<minLodPixels>" + MIN_LOD_PIXELS + "</minLodPixels>"
+ "\t\t\t\t\t</Lod>"
+ "\t\t\t\t</Region>"
+ "\t\t\t\t<styleUrl>#bar</styleUrl>\n"
+ "\t\t\t\t<Point>\n"
+ "\t\t\t\t\t<coordinates>\n"
+ "\t\t\t\t\t\t" + coord + ""
+ "\t\t\t\t\t</coordinates>"
+ "\t\t\t\t</Point>"
+ "\t\t\t</Placemark>"
+ "\t\t\t<Placemark>"
+ "\t\t\t\t<name>" + placename + " POLYGON</name>"
+ "\t\t\t\t<styleUrl>#bar</styleUrl>"
+ "\t\t\t\t<Style><PolyStyle><color>dc0155ff</color></PolyStyle></Style>"
+ "\t\t\t\t<Polygon>"
+ "\t\t\t\t\t<extrude>1</extrude><tessellate>1</tessellate>"
+ "\t\t\t\t\t<altitudeMode>relativeToGround</altitudeMode>"
+ "\t\t\t\t\t<outerBoundaryIs>"
+ "\t\t\t\t\t\t<LinearRing>"
+ "\t\t\t\t\t\t\t" + kmlPolygon + ""
+ "\t\t\t\t\t\t</LinearRing>"
+ "\t\t\t\t\t</outerBoundaryIs>"
+ "\t\t\t\t</Polygon>"
+ "\t\t\t</Placemark>\n");
//System.out.println("Contexts for " + placename);
/*while(indexInTAB < tokenArrayBuffer.toponymVector.size() && tokenArrayBuffer.toponymVector.get(indexInTAB) == 0) {
indexInTAB++;
}*/
for (int j = 0; j < loc.backPointers.size(); j++) {
int index = loc.backPointers.get(j);
String context = tokenArrayBuffer.getContextAround(index, windowSize, true);
context = context.replaceAll("<", "<"); // sanitization
Coordinate spiralPoint = coord.getNthSpiralPoint(j, 0.13);
contextOut.write("\t\t\t<Placemark>\n"
+ "\t\t\t\t<name>" + placename + " #" + (j + 1) + "</name>\n"
+ "\t\t\t\t<description>" + context + "</description>\n"
+ "\t\t\t\t<Region>"
+ "\t\t\t\t\t<LatLonAltBox>"
+ "\t\t\t\t\t\t<north>" + (spiralPoint.longitude + radius) + "</north>"
+ "\t\t\t\t\t\t<south>" + (spiralPoint.longitude - radius) + "</south>"
+ "\t\t\t\t\t\t<east>" + (spiralPoint.latitude + radius) + "</east>"
+ "\t\t\t\t\t\t<west>" + (spiralPoint.latitude - radius) + "</west>"
+ "\t\t\t\t\t</LatLonAltBox>"
+ "\t\t\t\t\t<Lod>"
+ "\t\t\t\t\t\t<minLodPixels>" + MIN_LOD_PIXELS + "</minLodPixels>"
+ "\t\t\t\t\t</Lod>"
+ "\t\t\t\t</Region>"
+ "\t\t\t\t<styleUrl>#context</styleUrl>\n"
+ "\t\t\t\t<Point>\n"
+ "\t\t\t\t\t<coordinates>" + spiralPoint + "</coordinates>\n"
+ "\t\t\t\t</Point>\n"
+ "\t\t\t</Placemark>\n");
}
//indexInTAB++;
//if(i >= 10) System.exit(0);
}
out.write("\t\t</Folder>\n\t</Document>\n</kml>");
contextOut.write("\t\t</Folder>\n\t</Document>\n</kml>");
out.close();
contextOut.close();
}
/**
* Train model. For access from main routines.
*/
public abstract void train();
/**
* @return the kmlOutputFilename
*/
public String getOutputFilename() {
return kmlOutputFilename;
}
/**
* @return the inputFile
*/
public File getInputFile() {
return inputFile;
}
/**
* @return the textProcessor
*/
public TextProcessor getTextProcessor() {
return textProcessor;
}
}
|
diff --git a/ajaxterm/src/test/java/org/kohsuke/ajaxterm4j/SessionTest.java b/ajaxterm/src/test/java/org/kohsuke/ajaxterm4j/SessionTest.java
index 3f535f6..2d4660e 100644
--- a/ajaxterm/src/test/java/org/kohsuke/ajaxterm4j/SessionTest.java
+++ b/ajaxterm/src/test/java/org/kohsuke/ajaxterm4j/SessionTest.java
@@ -1,29 +1,30 @@
package org.kohsuke.ajaxterm4j;
import org.junit.Test;
import org.kohsuke.ajaxterm.Session;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
/**
* @author Kohsuke Kawaguchi
*/
public class SessionTest {
@Test
public void basics() throws Exception {
Session s = new Session(80,25,Session.getAjaxTerm(),"/bin/bash","-i");
assertThat(s.isAlive(), is(true));
+ s.write("export PS1=:\n");
s.write("echo hello world\n");
Thread.sleep(5000);
String dump = s.getTerminal().dumpLatin1();
- assertThat(dump, containsString(" echo hello world"));
+ assertThat(dump, containsString(":echo hello world"));
assertThat(dump, containsString("\nhello world"));
System.out.println(dump);
s.write("exit 3\n");
s.join(1000);
assertThat(s.isAlive(), is(false));
assertThat(s.getChildProcess().exitValue(), is(3));
}
}
| false | true | public void basics() throws Exception {
Session s = new Session(80,25,Session.getAjaxTerm(),"/bin/bash","-i");
assertThat(s.isAlive(), is(true));
s.write("echo hello world\n");
Thread.sleep(5000);
String dump = s.getTerminal().dumpLatin1();
assertThat(dump, containsString(" echo hello world"));
assertThat(dump, containsString("\nhello world"));
System.out.println(dump);
s.write("exit 3\n");
s.join(1000);
assertThat(s.isAlive(), is(false));
assertThat(s.getChildProcess().exitValue(), is(3));
}
| public void basics() throws Exception {
Session s = new Session(80,25,Session.getAjaxTerm(),"/bin/bash","-i");
assertThat(s.isAlive(), is(true));
s.write("export PS1=:\n");
s.write("echo hello world\n");
Thread.sleep(5000);
String dump = s.getTerminal().dumpLatin1();
assertThat(dump, containsString(":echo hello world"));
assertThat(dump, containsString("\nhello world"));
System.out.println(dump);
s.write("exit 3\n");
s.join(1000);
assertThat(s.isAlive(), is(false));
assertThat(s.getChildProcess().exitValue(), is(3));
}
|
diff --git a/src/eu/trentorise/smartcampus/ac/UserRegistration.java b/src/eu/trentorise/smartcampus/ac/UserRegistration.java
index 0ffc802..4cca452 100644
--- a/src/eu/trentorise/smartcampus/ac/UserRegistration.java
+++ b/src/eu/trentorise/smartcampus/ac/UserRegistration.java
@@ -1,53 +1,53 @@
package eu.trentorise.smartcampus.ac;
import java.io.IOException;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider;
public class UserRegistration {
static AlertDialog.Builder builder;
public static void upgradeuser(final Context ctx, final Activity activity) {
builder = new AlertDialog.Builder(ctx);
final AMSCAccessProvider accessprovider = new AMSCAccessProvider();
//
// dialogbox for registration
DialogInterface.OnClickListener updateDialogClickListener;
updateDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//upgrade the user
AMSCAccessProvider ac = new AMSCAccessProvider();
ac.promote(activity, null, ac.readToken(ctx, null));
break;
case DialogInterface.BUTTON_NEGATIVE:
//CLOSE
break;
}
}
};
- builder.setCancelable(false).setMessage("Would you authenticate yourself?")
+ builder.setCancelable(false).setMessage(ctx.getString(R.string.auth_question))
.setPositiveButton(android.R.string.yes, updateDialogClickListener)
.setNegativeButton(android.R.string.no, updateDialogClickListener).show();
}
}
| true | true | public static void upgradeuser(final Context ctx, final Activity activity) {
builder = new AlertDialog.Builder(ctx);
final AMSCAccessProvider accessprovider = new AMSCAccessProvider();
//
// dialogbox for registration
DialogInterface.OnClickListener updateDialogClickListener;
updateDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//upgrade the user
AMSCAccessProvider ac = new AMSCAccessProvider();
ac.promote(activity, null, ac.readToken(ctx, null));
break;
case DialogInterface.BUTTON_NEGATIVE:
//CLOSE
break;
}
}
};
builder.setCancelable(false).setMessage("Would you authenticate yourself?")
.setPositiveButton(android.R.string.yes, updateDialogClickListener)
.setNegativeButton(android.R.string.no, updateDialogClickListener).show();
}
| public static void upgradeuser(final Context ctx, final Activity activity) {
builder = new AlertDialog.Builder(ctx);
final AMSCAccessProvider accessprovider = new AMSCAccessProvider();
//
// dialogbox for registration
DialogInterface.OnClickListener updateDialogClickListener;
updateDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//upgrade the user
AMSCAccessProvider ac = new AMSCAccessProvider();
ac.promote(activity, null, ac.readToken(ctx, null));
break;
case DialogInterface.BUTTON_NEGATIVE:
//CLOSE
break;
}
}
};
builder.setCancelable(false).setMessage(ctx.getString(R.string.auth_question))
.setPositiveButton(android.R.string.yes, updateDialogClickListener)
.setNegativeButton(android.R.string.no, updateDialogClickListener).show();
}
|
diff --git a/src/haven/Tex.java b/src/haven/Tex.java
index 24880d7..a766257 100644
--- a/src/haven/Tex.java
+++ b/src/haven/Tex.java
@@ -1,72 +1,72 @@
package haven;
import java.awt.Color;
import java.nio.*;
import java.util.*;
import javax.media.opengl.*;
public abstract class Tex {
protected Coord dim;
public Tex(Coord sz) {
dim = sz;
}
public Coord sz() {
return(dim);
}
public static int nextp2(int in) {
int ret;
for(ret = 1; ret < in; ret <<= 1);
return(ret);
}
public abstract void render(GOut g, Coord c, Coord ul, Coord br, Coord sz);
public void render(GOut g, Coord c) {
render(g, c, Coord.z, dim, dim);
}
public void crender(GOut g, Coord c, Coord ul, Coord sz, Coord tsz) {
if((tsz.x == 0) || (tsz.y == 0))
return;
if((c.x >= ul.x + sz.x) || (c.y >= ul.y + sz.y) ||
- (c.x + tsz.x <= 0) || (c.y + tsz.y <= 0))
+ (c.x + tsz.x <= ul.x) || (c.y + tsz.y <= ul.y))
return;
Coord t = new Coord(c);
Coord uld = new Coord(0, 0);
Coord brd = new Coord(dim);
Coord szd = new Coord(tsz);
if(c.x < ul.x) {
int pd = ul.x - c.x;
t.x = ul.x;
uld.x = (pd * dim.x) / tsz.x;
szd.x -= pd;
}
if(c.y < ul.y) {
int pd = ul.y - c.y;
t.y = ul.y;
uld.y = (pd * dim.y) / tsz.y;
szd.y -= pd;
}
if(c.x + tsz.x > ul.x + sz.x) {
int pd = (c.x + tsz.x) - (ul.x + sz.x);
szd.x -= pd;
brd.x -= (pd * dim.x) / tsz.x;
}
if(c.y + tsz.y > ul.y + sz.y) {
int pd = (c.y + tsz.y) - (ul.y + sz.y);
szd.y -= pd;
brd.y -= (pd * dim.y) / tsz.y;
}
render(g, t, uld, brd, szd);
}
public void crender(GOut g, Coord c, Coord ul, Coord sz) {
crender(g, c, ul, sz, dim);
}
public void dispose() {}
}
| true | true | public void crender(GOut g, Coord c, Coord ul, Coord sz, Coord tsz) {
if((tsz.x == 0) || (tsz.y == 0))
return;
if((c.x >= ul.x + sz.x) || (c.y >= ul.y + sz.y) ||
(c.x + tsz.x <= 0) || (c.y + tsz.y <= 0))
return;
Coord t = new Coord(c);
Coord uld = new Coord(0, 0);
Coord brd = new Coord(dim);
Coord szd = new Coord(tsz);
if(c.x < ul.x) {
int pd = ul.x - c.x;
t.x = ul.x;
uld.x = (pd * dim.x) / tsz.x;
szd.x -= pd;
}
if(c.y < ul.y) {
int pd = ul.y - c.y;
t.y = ul.y;
uld.y = (pd * dim.y) / tsz.y;
szd.y -= pd;
}
if(c.x + tsz.x > ul.x + sz.x) {
int pd = (c.x + tsz.x) - (ul.x + sz.x);
szd.x -= pd;
brd.x -= (pd * dim.x) / tsz.x;
}
if(c.y + tsz.y > ul.y + sz.y) {
int pd = (c.y + tsz.y) - (ul.y + sz.y);
szd.y -= pd;
brd.y -= (pd * dim.y) / tsz.y;
}
render(g, t, uld, brd, szd);
}
| public void crender(GOut g, Coord c, Coord ul, Coord sz, Coord tsz) {
if((tsz.x == 0) || (tsz.y == 0))
return;
if((c.x >= ul.x + sz.x) || (c.y >= ul.y + sz.y) ||
(c.x + tsz.x <= ul.x) || (c.y + tsz.y <= ul.y))
return;
Coord t = new Coord(c);
Coord uld = new Coord(0, 0);
Coord brd = new Coord(dim);
Coord szd = new Coord(tsz);
if(c.x < ul.x) {
int pd = ul.x - c.x;
t.x = ul.x;
uld.x = (pd * dim.x) / tsz.x;
szd.x -= pd;
}
if(c.y < ul.y) {
int pd = ul.y - c.y;
t.y = ul.y;
uld.y = (pd * dim.y) / tsz.y;
szd.y -= pd;
}
if(c.x + tsz.x > ul.x + sz.x) {
int pd = (c.x + tsz.x) - (ul.x + sz.x);
szd.x -= pd;
brd.x -= (pd * dim.x) / tsz.x;
}
if(c.y + tsz.y > ul.y + sz.y) {
int pd = (c.y + tsz.y) - (ul.y + sz.y);
szd.y -= pd;
brd.y -= (pd * dim.y) / tsz.y;
}
render(g, t, uld, brd, szd);
}
|
diff --git a/gwt/de.graind/src/de/graind/client/widgets/monthly/MonthlyWidgetController.java b/gwt/de.graind/src/de/graind/client/widgets/monthly/MonthlyWidgetController.java
index 40f3ae4..56eb5cc 100644
--- a/gwt/de.graind/src/de/graind/client/widgets/monthly/MonthlyWidgetController.java
+++ b/gwt/de.graind/src/de/graind/client/widgets/monthly/MonthlyWidgetController.java
@@ -1,119 +1,118 @@
package de.graind.client.widgets.monthly;
import java.util.Date;
import com.google.gwt.gdata.client.DateTime;
import com.google.gwt.gdata.client.EventEntry;
import com.google.gwt.gdata.client.GData;
import com.google.gwt.gdata.client.GDataSystemPackage;
import com.google.gwt.gdata.client.calendar.CalendarEventFeed;
import com.google.gwt.gdata.client.calendar.CalendarEventFeedCallback;
import com.google.gwt.gdata.client.calendar.CalendarEventQuery;
import com.google.gwt.gdata.client.calendar.CalendarService;
import com.google.gwt.gdata.client.impl.CallErrorException;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import de.graind.client.util.CalendarUtil;
import de.graind.shared.Config;
public class MonthlyWidgetController implements MonthlyWidgetView.Controller {
private static final DateTimeFormat format = DateTimeFormat.getFormat("yyyy-MM-dd");
private MonthlyWidgetView view;
private CalendarService service;
private AsyncCallback<EventEntry[]> eventCallback;
private int year;
private int month;
public MonthlyWidgetController(MonthlyWidgetView view) {
this.view = view;
final Date now = new Date();
this.year = CalendarUtil.getYear(now);
this.month = CalendarUtil.getMonth(now);
if (GData.isLoaded(GDataSystemPackage.CALENDAR)) {
gdataLoaded();
} else {
GData.loadGDataApi(Config.API_KEY, new Runnable() {
public void run() {
gdataLoaded();
}
}, GDataSystemPackage.CALENDAR);
}
}
private void gdataLoaded() {
this.service = CalendarService.newInstance(Config.APPLICATION_NAME);
MonthlyWidgetController.this.view.init(MonthlyWidgetController.this);
fetchEventsForMonth(eventCallback);
}
private void fetchEventsForMonth(final AsyncCallback<EventEntry[]> callback) {
CalendarEventQuery query = CalendarEventQuery
.newInstance("http://www.google.com/calendar/feeds/default/private/full");
- final DateTime max = DateTime.newInstance(format.parse(year + "-" + month + "-"
- + CalendarUtil.getDaysOfMonth(year, month)));
+ final DateTime max = DateTime.newInstance(format.parse(year + "-" + (month + 1) + "-01"));
final DateTime min = DateTime.newInstance(format.parse(year + "-" + month + "-01"));
query.setMaximumStartTime(max);
query.setMinimumStartTime(min);
// get all events (more then 1000 are unlikely)
query.setMaxResults(1000);
// TODO: add entries that start at an earlier date but are still valid
service.getEventsFeed(query, new CalendarEventFeedCallback() {
@Override
public void onFailure(CallErrorException caught) {
callback.onFailure(caught);
}
@Override
public void onSuccess(CalendarEventFeed result) {
callback.onSuccess(result.getEntries());
}
});
}
@Override
public void setEventsCallback(AsyncCallback<EventEntry[]> callback) {
this.eventCallback = callback;
}
@Override
public void nextMonth() {
if (month == 12) {
month = 1;
year++;
} else {
month++;
}
fetchEventsForMonth(eventCallback);
}
@Override
public void previousMonth() {
if (month == 1) {
month = 12;
year--;
} else {
month--;
}
fetchEventsForMonth(eventCallback);
}
@Override
public int getMonth() {
return month;
}
@Override
public int getYear() {
return year;
}
}
| true | true | private void fetchEventsForMonth(final AsyncCallback<EventEntry[]> callback) {
CalendarEventQuery query = CalendarEventQuery
.newInstance("http://www.google.com/calendar/feeds/default/private/full");
final DateTime max = DateTime.newInstance(format.parse(year + "-" + month + "-"
+ CalendarUtil.getDaysOfMonth(year, month)));
final DateTime min = DateTime.newInstance(format.parse(year + "-" + month + "-01"));
query.setMaximumStartTime(max);
query.setMinimumStartTime(min);
// get all events (more then 1000 are unlikely)
query.setMaxResults(1000);
// TODO: add entries that start at an earlier date but are still valid
service.getEventsFeed(query, new CalendarEventFeedCallback() {
@Override
public void onFailure(CallErrorException caught) {
callback.onFailure(caught);
}
@Override
public void onSuccess(CalendarEventFeed result) {
callback.onSuccess(result.getEntries());
}
});
}
| private void fetchEventsForMonth(final AsyncCallback<EventEntry[]> callback) {
CalendarEventQuery query = CalendarEventQuery
.newInstance("http://www.google.com/calendar/feeds/default/private/full");
final DateTime max = DateTime.newInstance(format.parse(year + "-" + (month + 1) + "-01"));
final DateTime min = DateTime.newInstance(format.parse(year + "-" + month + "-01"));
query.setMaximumStartTime(max);
query.setMinimumStartTime(min);
// get all events (more then 1000 are unlikely)
query.setMaxResults(1000);
// TODO: add entries that start at an earlier date but are still valid
service.getEventsFeed(query, new CalendarEventFeedCallback() {
@Override
public void onFailure(CallErrorException caught) {
callback.onFailure(caught);
}
@Override
public void onSuccess(CalendarEventFeed result) {
callback.onSuccess(result.getEntries());
}
});
}
|
diff --git a/src/main/java/com/threerings/tudey/tools/SceneEditor.java b/src/main/java/com/threerings/tudey/tools/SceneEditor.java
index 1220ed5f..aac4b0c9 100644
--- a/src/main/java/com/threerings/tudey/tools/SceneEditor.java
+++ b/src/main/java/com/threerings/tudey/tools/SceneEditor.java
@@ -1,1984 +1,1984 @@
//
// $Id$
//
// Clyde library - tools for developing networked games
// Copyright (C) 2005-2012 Three Rings Design, Inc.
// http://code.google.com/p/clyde/
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.threerings.tudey.tools;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.List;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEditSupport;
import org.lwjgl.opengl.GL11;
import com.apple.eawt.Application;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.samskivert.swing.GroupLayout;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.Spacer;
import com.samskivert.swing.util.SwingUtil;
import com.samskivert.util.ArrayUtil;
import com.samskivert.util.CollectionUtil;
import com.samskivert.util.RunAnywhere;
import com.threerings.crowd.client.PlaceView;
import com.threerings.media.image.ImageUtil;
import com.threerings.config.ConfigManager;
import com.threerings.config.tools.ConfigEditor;
import com.threerings.editor.Editable;
import com.threerings.editor.EditorMessageBundle;
import com.threerings.editor.tools.BatchValidateDialog;
import com.threerings.export.BinaryExporter;
import com.threerings.export.BinaryImporter;
import com.threerings.export.XMLExporter;
import com.threerings.export.XMLImporter;
import com.threerings.expr.Scoped;
import com.threerings.math.FloatMath;
import com.threerings.math.Ray3D;
import com.threerings.math.Rect;
import com.threerings.math.Transform2D;
import com.threerings.math.Transform3D;
import com.threerings.math.Vector2f;
import com.threerings.math.Vector3f;
import com.threerings.swing.PrintStreamDialog;
import com.threerings.util.ToolUtil;
import com.threerings.opengl.camera.CameraHandler;
import com.threerings.opengl.camera.OrbitCameraHandler;
import com.threerings.opengl.camera.MouseOrbiter;
import com.threerings.opengl.compositor.RenderQueue;
import com.threerings.opengl.gui.util.Rectangle;
import com.threerings.opengl.renderer.Color4f;
import com.threerings.opengl.renderer.state.ColorState;
import com.threerings.opengl.renderer.state.RenderState;
import com.threerings.opengl.util.Grid;
import com.threerings.opengl.util.SimpleTransformable;
import com.threerings.tudey.client.TudeySceneView;
import com.threerings.tudey.client.sprite.EntrySprite;
import com.threerings.tudey.client.sprite.Sprite;
import com.threerings.tudey.config.TileConfig;
import com.threerings.tudey.data.TudeySceneModel;
import com.threerings.tudey.data.TudeySceneModel.AreaEntry;
import com.threerings.tudey.data.TudeySceneModel.Entry;
import com.threerings.tudey.data.TudeySceneModel.GlobalEntry;
import com.threerings.tudey.data.TudeySceneModel.Paint;
import com.threerings.tudey.data.TudeySceneModel.PathEntry;
import com.threerings.tudey.data.TudeySceneModel.PlaceableEntry;
import com.threerings.tudey.data.TudeySceneModel.TileEntry;
import com.threerings.tudey.util.Coord;
import com.threerings.tudey.util.EntryManipulator;
import com.threerings.tudey.util.TudeySceneMetrics;
import static com.threerings.tudey.Log.*;
/**
* The scene editor application.
*/
public class SceneEditor extends TudeyTool
implements EntryManipulator, TudeySceneModel.Observer,
KeyEventDispatcher, MouseListener, ClipboardOwner
{
/** Allows only tile entries. */
public static final Predicate<Object> TILE_ENTRY_FILTER =
Predicates.instanceOf(TileEntry.class);
/** Allows only placeable entries. */
public static final Predicate<Object> PLACEABLE_ENTRY_FILTER =
Predicates.instanceOf(PlaceableEntry.class);
/** Allows all entries except globals. */
public static final Predicate<Object> DEFAULT_ENTRY_FILTER =
Predicates.and(Predicates.instanceOf(Entry.class),
Predicates.not(Predicates.instanceOf(GlobalEntry.class)));
/** A function that transforms an Entry to its key. */
public static final Function<Entry, Object> ENTRY_TO_KEY = new Function<Entry, Object>() {
public Object apply (Entry entry) {
return entry.getKey();
}
};
/**
* The program entry point.
*/
public static void main (String[] args)
throws Exception
{
// start up the scene editor app
new SceneEditor(args.length > 0 ? args[0] : null).startup();
}
/**
* Creates the scene editor with (optionally) the path to a scene to load.
*/
public SceneEditor (String scene)
{
super("scene");
if (RunAnywhere.isMacOS()) {
setupMacSupport();
}
// we override shutdown() and may want to abort a close
_frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
_initScene = (scene == null) ? null : new File(scene);
// set the title
updateTitle();
// create the undo apparatus
_undoSupport = new UndoableEditSupport();
_undoSupport.addUndoableEditListener(_undomgr = new UndoManager());
_undomgr.setLimit(10000);
_undoSupport.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened (UndoableEditEvent event) {
updateUndoActions();
}
});
// populate the menu bar
JMenuBar menubar = new JMenuBar();
_frame.setJMenuBar(menubar);
JMenu file = createMenu("file", KeyEvent.VK_F);
menubar.add(file);
file.add(createMenuItem("new", KeyEvent.VK_N, KeyEvent.VK_N));
file.add(createMenuItem("open", KeyEvent.VK_O, KeyEvent.VK_O));
file.add(_recents = new JMenu(_msgs.get("m.recent")));
file.addSeparator();
file.add(createMenuItem("save", KeyEvent.VK_S, KeyEvent.VK_S));
file.add(createMenuItem("save_as", KeyEvent.VK_A, KeyEvent.VK_A));
file.add(_revert = createMenuItem("revert", KeyEvent.VK_R, KeyEvent.VK_R));
_revert.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("import", KeyEvent.VK_I, -1));
file.add(createMenuItem("export", KeyEvent.VK_E, -1));
file.addSeparator();
file.add(createMenuItem("import_selection", KeyEvent.VK_M, -1));
file.add(_exportSelection = createMenuItem("export_selection", KeyEvent.VK_X, -1));
_exportSelection.setEnabled(false);
file.addSeparator();
file.add(createMenuItem("test", KeyEvent.VK_T, KeyEvent.VK_B));
file.addSeparator();
file.add(createMenuItem("quit", KeyEvent.VK_Q, KeyEvent.VK_Q));
JMenu edit = createMenu("edit", KeyEvent.VK_E);
menubar.add(edit);
edit.add(_undo = createAction("undo", KeyEvent.VK_U, KeyEvent.VK_Z));
_undo.setEnabled(false);
edit.add(_redo = createAction("redo", KeyEvent.VK_R, KeyEvent.VK_Y));
_redo.setEnabled(false);
edit.addSeparator();
edit.add(new JMenuItem(_cut = createAction("cut", KeyEvent.VK_T, KeyEvent.VK_X)));
_cut.setEnabled(false);
edit.add(new JMenuItem(_copy = createAction("copy", KeyEvent.VK_C, KeyEvent.VK_C)));
_copy.setEnabled(false);
edit.add(new JMenuItem(_paste = createAction("paste", KeyEvent.VK_P, KeyEvent.VK_V)));
_paste.setEnabled(false);
edit.add(new JMenuItem(
_delete = createAction("delete", KeyEvent.VK_D, KeyEvent.VK_DELETE, 0)));
_delete.setEnabled(false);
edit.addSeparator();
edit.add(_rotateCW = createMenuItem("rotate_ccw", KeyEvent.VK_O, KeyEvent.VK_LEFT));
_rotateCW.setEnabled(false);
edit.add(_rotateCCW = createMenuItem("rotate_cw", KeyEvent.VK_E, KeyEvent.VK_RIGHT));
_rotateCCW.setEnabled(false);
edit.addSeparator();
edit.add(_raise = createMenuItem("raise", KeyEvent.VK_A, KeyEvent.VK_UP));
_raise.setEnabled(false);
edit.add(_lower = createMenuItem("lower", KeyEvent.VK_L, KeyEvent.VK_DOWN));
_lower.setEnabled(false);
edit.addSeparator();
edit.add(_saveToPalette = createMenuItem("save_to_palette", KeyEvent.VK_V, KeyEvent.VK_L));
_saveToPalette.setEnabled(false);
edit.addSeparator();
edit.add(createMenuItem("validate_refs", KeyEvent.VK_I, -1));
edit.add(createMenuItem("delete_errors", KeyEvent.VK_E, -1));
edit.addSeparator();
edit.add(createMenuItem("configs", KeyEvent.VK_N, KeyEvent.VK_G));
edit.add(createMenuItem("resources", KeyEvent.VK_S, KeyEvent.VK_E));
edit.add(createMenuItem("preferences", KeyEvent.VK_F, KeyEvent.VK_P));
JMenu view = createMenu("view", KeyEvent.VK_V);
menubar.add(view);
view.add(_showGrid = createCheckBoxMenuItem("grid", KeyEvent.VK_G, KeyEvent.VK_D));
_showGrid.setSelected(true);
view.add(_showCompass = createCheckBoxMenuItem("compass", KeyEvent.VK_O, KeyEvent.VK_M));
_showCompass.setSelected(true);
view.add(_showStats = createCheckBoxMenuItem("stats", KeyEvent.VK_S, KeyEvent.VK_T));
view.addSeparator();
view.add(createMenuItem("refresh", KeyEvent.VK_F, KeyEvent.VK_F));
view.addSeparator();
view.add(createMenuItem("raise_grid", KeyEvent.VK_R, KeyEvent.VK_UP, 0));
view.add(createMenuItem("lower_grid", KeyEvent.VK_L, KeyEvent.VK_DOWN, 0));
view.addSeparator();
view.add(createMenuItem("reorient", KeyEvent.VK_I, KeyEvent.VK_I));
view.add(createMenuItem("recenter", KeyEvent.VK_C, KeyEvent.VK_C));
view.addSeparator();
view.add(createMenuItem("prev_layer", KeyEvent.VK_P, KeyEvent.VK_UP, KeyEvent.ALT_MASK));
view.add(createMenuItem("next_layer", KeyEvent.VK_N, KeyEvent.VK_DOWN, KeyEvent.ALT_MASK));
JMenu tools = createMenu("tools", KeyEvent.VK_T);
menubar.add(tools);
tools.add(createMenuItem("batch_validate", KeyEvent.VK_B, -1));
// create the file chooser
_chooser = new JFileChooser(_prefs.get("scene_dir", null));
_chooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".dat");
}
public String getDescription () {
return _msgs.get("m.scene_files");
}
});
// and the export chooser
_exportChooser = new JFileChooser(_prefs.get("scene_export_dir", null));
_exportChooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".xml");
}
public String getDescription () {
return _msgs.get("m.xml_files");
}
});
// and the selection chooser
_selectionChooser = new JFileChooser(_prefs.get("selection_dir", null));
_selectionChooser.setFileFilter(new FileFilter() {
public boolean accept (File file) {
return file.isDirectory() || file.toString().toLowerCase().endsWith(".dat");
}
public String getDescription () {
return _msgs.get("m.selection_files");
}
});
// populate the tool bar
_toolbar.setLayout(new HGroupLayout(GroupLayout.STRETCH));
_toolbar.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
_toolbar.setFloatable(false);
_toolbar.setRollover(true);
JButton save = createIconButton("save");
_toolbar.add(save, GroupLayout.FIXED);
save.setPressedIcon(createIcon("save_click"));
_toolbar.add(new Spacer(80, 1), GroupLayout.FIXED);
_toolbar.add(_markers = createToggleButton("markers"), GroupLayout.FIXED);
_markers.setSelected(!_markersVisible);
_toolbar.add(_light = createToggleButton("light"), GroupLayout.FIXED);
_light.setSelected(!_lightingEnabled);
_toolbar.add(_fog = createToggleButton("fog"), GroupLayout.FIXED);
_fog.setSelected(!_fogEnabled);
_toolbar.add(_sound = createToggleButton("sound"), GroupLayout.FIXED);
_sound.setSelected(!_soundEnabled);
_toolbar.add(new Spacer(1, 1));
_toolbar.add(createIconButton("raise_grid"), GroupLayout.FIXED);
_toolbar.add(createIconButton("lower_grid"), GroupLayout.FIXED);
// configure the edit panel
_epanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
_epanel.setPreferredSize(new Dimension(350, 1));
// create the tool box
JPanel outer = new JPanel();
_epanel.add(outer, GroupLayout.FIXED);
ButtonGroup tgroup = new ButtonGroup();
JPanel tpanel = new JPanel(new GridLayout(0, 7, 5, 5));
outer.add(tpanel);
addTool(tpanel, tgroup, "arrow", _arrow = new Arrow(this));
addTool(tpanel, tgroup, "selector", _selector = new Selector(this));
addTool(tpanel, tgroup, "mover", _mover = new Mover(this));
addTool(tpanel, tgroup, "placer", _placer = new Placer(this));
addTool(tpanel, tgroup, "path_definer", _pathDefiner = new PathDefiner(this));
addTool(tpanel, tgroup, "area_definer", _areaDefiner = new AreaDefiner(this));
addTool(tpanel, tgroup, "global_editor", _globalEditor = new GlobalEditor(this));
addTool(tpanel, tgroup, "tile_brush", _tileBrush = new TileBrush(this));
addTool(tpanel, tgroup, "ground_brush", _groundBrush = new GroundBrush(this));
addTool(tpanel, tgroup, "wall_brush", _wallBrush = new WallBrush(this));
addTool(tpanel, tgroup, "palette", _palette = new Palette(this));
addTool(tpanel, tgroup, "eyedropper", new Eyedropper(this));
addTool(tpanel, tgroup, "eraser", new Eraser(this));
addTool(tpanel, tgroup, "notepad", new Notepad(this));
// create the option panel
_opanel = GroupLayout.makeVStretchBox(5);
// set up the layer tool, which is special and added to the _tools map by hand
_tools.put("layers", _layers = new Layers(this));
_epanel.add(_layerSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, _layers, _opanel));
_layerSplit.setBorder(BorderFactory.createEmptyBorder());
// activate the arrow tool
setActiveTool(_arrow);
// add ourself as a key dispatcher
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
// add ourself as a mouse listener
_canvas.addMouseListener(this);
}
/**
* Configure Mac support, if we're running on a Mac.
*/
// ApplicationAdapter and friends are deprecated, but the replacements are only present
// in the latest Apple Java. I'm sure we could update at some point.
@SuppressWarnings("deprecation")
protected void setupMacSupport ()
{
Application app = Application.getApplication();
if (app == null) {
return;
}
// we do not handle the "About" menu item, so remove it.
app.removeAboutMenuItem();
// add a listener to gracefully shut down
app.addApplicationListener(new com.apple.eawt.ApplicationAdapter() {
@Override public void handleQuit (com.apple.eawt.ApplicationEvent event) {
// always reject the quit, and just call shutdown()
event.setHandled(false);
shutdown();
}
});
}
/**
* Returns a reference to the scene view.
*/
public TudeySceneView getView ()
{
return _view;
}
/**
* Returns a reference to the editor grid.
*/
public EditorGrid getGrid ()
{
return _grid;
}
/**
* Checks whether the shift key is being held down.
*/
public boolean isShiftDown ()
{
return _shiftDown;
}
/**
* Checks whether either of the special modifiers (control or alt) is down.
*/
public boolean isSpecialDown ()
{
return isControlDown() || isAltDown();
}
/**
* Checks whether the control key is being held down.
*/
public boolean isControlDown ()
{
return _controlDown;
}
/**
* Checks whether the alt key is being held down.
*/
public boolean isAltDown ()
{
return _altDown;
}
/**
* Checks whether the first mouse button is being held down on the canvas.
*/
public boolean isFirstButtonDown ()
{
return _firstButtonDown;
}
/**
* Checks whether the second mouse button is being held down on the canvas.
*/
public boolean isSecondButtonDown ()
{
return _secondButtonDown;
}
/**
* Checks whether the third mouse button is being held down on the canvas.
*/
public boolean isThirdButtonDown ()
{
return _thirdButtonDown;
}
/**
* Clears the selection.
*/
public void clearSelection ()
{
setSelection();
}
/**
* Returns a Predicate that selects entries only on the current layer.
*/
public Predicate<Entry> getLayerPredicate ()
{
final int layer = _layers.getSelectedLayer();
return new Predicate<Entry>() {
public boolean apply (Entry entry) {
return (layer == _scene.getLayer(entry.getKey()));
}
};
}
/**
* Selects the specified entries and switches to either the selector tool or the arrow
* tool, depending on whether multiple entries are selected.
*/
public void select (Entry... selection)
{
if (selection.length > 1) {
setActiveTool(_selector);
} else if (selection.length > 0) {
setActiveTool(_arrow);
_arrow.edit(selection[0]);
return; // the arrow sets the selection
}
setSelection(selection);
}
/**
* Sets the selected elements.
*/
public void setSelection (Entry... selection)
{
// update the sprites' selected states
for (Entry entry : _selection) {
EntrySprite sprite = _view.getEntrySprite(entry.getKey());
if (sprite != null) {
sprite.setSelected(false);
} else {
// this is fine; the sprite has already been deleted
}
}
for (Entry entry : (_selection = selection)) {
EntrySprite sprite = _view.getEntrySprite(entry.getKey());
if (sprite != null) {
sprite.setSelected(true);
} else {
log.warning("Missing sprite for selected entry.", "entry", entry);
}
}
// clear the selection pivot for the next rotation
_selectionPivot = null;
// update the ui bits
boolean enable = (selection.length > 0);
_exportSelection.setEnabled(enable);
_cut.setEnabled(enable);
_copy.setEnabled(enable);
_delete.setEnabled(enable);
_rotateCW.setEnabled(enable);
_rotateCCW.setEnabled(enable);
_raise.setEnabled(enable);
_lower.setEnabled(enable);
_saveToPalette.setEnabled(enable);
}
/**
* Returns the selected elements.
*/
public Entry[] getSelection ()
{
return _selection;
}
/**
* Determines whether the specified entry is selected.
*/
public boolean isSelected (Entry entry)
{
return getSelectionIndex(entry) != -1;
}
/**
* Attempts to edit the entry under the mouse cursor on the currently selected layer.
*/
public void editMouseEntry ()
{
Entry entry = getMouseEntry(DEFAULT_ENTRY_FILTER);
if (entry != null) {
setActiveTool(_arrow);
_arrow.edit(entry);
}
}
/**
* Attempts to delete the entry under the mouse cursor on the currently selected layer.
*/
public void deleteMouseEntry ()
{
deleteMouseEntry(DEFAULT_ENTRY_FILTER);
}
/**
* Attempts to delete the entry under the mouse cursor on the currently selected layer.
*/
public void deleteMouseEntry (Predicate<? super Entry> filter)
{
Entry entry = getMouseEntry(filter);
if (entry != null) {
removeEntries(entry.getKey());
}
}
/**
* Attempts to "use" the entry under the mouse cursor on the currently selected layer.
*/
public void useMouseEntry ()
{
Entry entry = getMouseEntry();
if (entry instanceof PlaceableEntry) {
setActiveTool(_placer);
PlaceableEntry pentry = (PlaceableEntry)entry;
_placer.setReference(pentry.placeable);
pentry.transform.update(Transform3D.RIGID);
_placer.setAngle(pentry.transform.getRotation().getRotationZ());
} else if (entry instanceof AreaEntry) {
setActiveTool(_areaDefiner);
_areaDefiner.setReference(((AreaEntry)entry).area);
} else if (entry instanceof PathEntry) {
setActiveTool(_pathDefiner);
_pathDefiner.setReference(((PathEntry)entry).path);
} else if (entry instanceof TileEntry) {
setActiveTool(_tileBrush);
TileEntry tentry = (TileEntry)entry;
_tileBrush.setReference(tentry.tile);
_tileBrush.setRotation(tentry.rotation);
}
}
/**
* Returns a reference to the entry under the mouse cursor on the currently selected layer.
*/
public Entry getMouseEntry ()
{
return getMouseEntry(DEFAULT_ENTRY_FILTER);
}
/**
* Returns a reference to the entry under the mouse cursor on the currently selected layer.
*/
public Entry getMouseEntry (Predicate<? super Entry> filter)
{
if (!getMouseRay(_pick)) {
return null;
}
final Predicate<Entry> pred = Predicates.and(getLayerPredicate(), filter);
EntrySprite sprite = (EntrySprite)_view.getIntersection(
_pick, _pt, new Predicate<Sprite>() {
public boolean apply (Sprite sprite) {
return (sprite instanceof EntrySprite) &&
pred.apply(((EntrySprite) sprite).getEntry());
}
});
return (sprite == null) ? null : sprite.getEntry();
}
/**
* Starts moving the current selection.
*/
public void moveSelection ()
{
removeAndMove(_selection);
}
/**
* Removes the specified entries, then activates them in the mover tool.
*/
public void removeAndMove (Entry... entries)
{
incrementEditId();
removeEntries(Arrays.asList(entries));
move(entries);
}
/**
* Activates the supplied entries in the mover tool.
*/
public void move (Entry... entries)
{
setActiveTool(_mover);
_mover.move(entries);
}
/**
* Increments the edit id, ensuring that any further edits will not be merged with previous
* ones.
*/
public void incrementEditId ()
{
_editId++;
}
/**
* Adds an entry, removing any conflicting entries if necessary.
*/
public void overwriteEntries (Entry... entries)
{
Set<Object> toRemoveKeys = Sets.newHashSet();
List<TileEntry> temp = Lists.newArrayList();
for (Entry entry : entries) {
if (entry instanceof TileEntry) {
TileEntry tentry = (TileEntry)entry;
TileConfig.Original config = tentry.getConfig(getConfigManager());
Rectangle region = new Rectangle();
tentry.getRegion(config, region);
_scene.getTileEntries(region, temp);
toRemoveKeys.addAll(Collections2.transform(temp, ENTRY_TO_KEY));
temp.clear();
}
}
removeEntries(toRemoveKeys.toArray());
addEntries(entries);
}
// documentation inherited from interface EntryManipulator
public void addEntries (Entry... entries)
{
if (entries.length == 0) {
return;
}
for (Entry entry : entries) {
if (entry instanceof TileEntry) {
clearPaint((TileEntry)entry);
_layers.setSelectedLayer(0);
} else if (entry instanceof GlobalEntry) {
_layers.setSelectedLayer(0);
}
}
_undoSupport.postEdit(
new EntryEdit(_scene, _editId, _layers.getSelectedLayer(),
entries, new Entry[0], new Object[0]));
}
// documentation inherited from interface EntryManipulator
public void updateEntries (Entry... entries)
{
if (entries.length == 0) {
return;
}
for (Entry entry : entries) {
if (entry instanceof TileEntry) {
clearPaint((TileEntry)_scene.getEntry(entry.getKey()));
clearPaint((TileEntry)entry);
_layers.setSelectedLayer(0);
}
}
_undoSupport.postEdit(
new EntryEdit(_scene, _editId, _layers.getSelectedLayer(),
new Entry[0], entries, new Object[0]));
}
// documentation inherited from interface EntryManipulator
public void removeEntries (Object... keys)
{
if (keys.length == 0) {
return;
}
for (Object key : keys) {
if (key instanceof Coord) {
clearPaint((TileEntry)_scene.getEntry(key));
_layers.setSelectedLayer(0);
}
}
_undoSupport.postEdit(
new EntryEdit(_scene, _editId, _layers.getSelectedLayer(),
new Entry[0], new Entry[0], keys));
}
// documentation inherited from interface EntryManipulator
public void removeEntries (Collection<? extends Entry> coll)
{
removeEntries(Collections2.transform(coll, ENTRY_TO_KEY).toArray());
}
// documentation inherited from interface EntryManipulator
public void setPaint (Rectangle region, Paint paint)
{
_undoSupport.postEdit(new EntryEdit(_scene, _editId, _layers.getSelectedLayer(),
region, paint));
}
// documentation inherited from interface TudeySceneModel.Observer
public void entryAdded (Entry entry)
{
// no-op
}
// documentation inherited from interface TudeySceneModel.Observer
public void entryUpdated (Entry oentry, Entry nentry)
{
// update selection
int idx = getSelectionIndex(oentry);
if (idx != -1) {
_selection[idx] = nentry;
}
}
// documentation inherited from interface TudeySceneModel.Observer
public void entryRemoved (Entry oentry)
{
// update selection
int idx = getSelectionIndex(oentry);
if (idx != -1) {
setSelection(ArrayUtil.splice(_selection, idx, 1));
}
}
// documentation inherited from interface KeyEventDispatcher
public boolean dispatchKeyEvent (KeyEvent event)
{
boolean pressed;
int id = event.getID();
if (id == KeyEvent.KEY_PRESSED) {
pressed = true;
} else if (id == KeyEvent.KEY_RELEASED) {
pressed = false;
} else {
return false;
}
switch (event.getKeyCode()) {
case KeyEvent.VK_SHIFT:
_shiftDown = pressed;
break;
case KeyEvent.VK_CONTROL:
_controlDown = pressed;
break;
case KeyEvent.VK_ALT:
_altDown = pressed;
break;
}
return false;
}
// documentation inherited from interface MouseListener
public void mouseClicked (MouseEvent event)
{
if (mouseCameraEnabled() && event.getButton() == MouseEvent.BUTTON1 &&
event.getClickCount() == 2) {
editMouseEntry();
}
}
// documentation inherited from interface MouseListener
public void mousePressed (MouseEvent event)
{
if ((event.getModifiersEx() & InputEvent.ALT_DOWN_MASK) != 0) {
useMouseEntry();
}
switch (event.getButton()) {
case MouseEvent.BUTTON1:
_firstButtonDown = true;
break;
case MouseEvent.BUTTON2:
_secondButtonDown = true;
break;
case MouseEvent.BUTTON3:
_thirdButtonDown = true;
break;
}
incrementEditId();
}
// documentation inherited from interface MouseListener
public void mouseReleased (MouseEvent event)
{
switch (event.getButton()) {
case MouseEvent.BUTTON1:
_firstButtonDown = false;
break;
case MouseEvent.BUTTON2:
_secondButtonDown = false;
break;
case MouseEvent.BUTTON3:
_thirdButtonDown = false;
break;
}
incrementEditId();
}
// documentation inherited from interface MouseListener
public void mouseEntered (MouseEvent event)
{
// no-op
}
// documentation inherited from interface MouseListener
public void mouseExited (MouseEvent event)
{
// no-op
}
// documentation inherited from interface ClipboardOwner
public void lostOwnership (Clipboard clipboard, Transferable contents)
{
_paste.setEnabled(false);
}
@Override // documentation inherited
public ConfigManager getConfigManager ()
{
return (_scene == null) ? _cfgmgr : _scene.getConfigManager();
}
@Override // documentation inherited
public void setPlaceView (PlaceView view)
{
super.setPlaceView(view);
_testing = true;
// hide editor ui
if (_activeTool != null) {
_activeTool.deactivate();
}
_frame.getJMenuBar().setVisible(false);
_divsize = _pane.getDividerSize();
_gridEnabled = _showGrid.isSelected();
_showGrid.setSelected(false);
_compassEnabled = _showCompass.isSelected();
_showCompass.setSelected(false);
_pane.setDividerSize(0);
_toolbar.setVisible(false);
_epanel.setVisible(false);
SwingUtil.refresh((JComponent)_frame.getContentPane());
}
@Override // documentation inherited
public void clearPlaceView (PlaceView view)
{
// switch back to the editor view
setView(_view);
_testing = false;
// show editor ui
if (_activeTool != null) {
_activeTool.activate();
}
_frame.getJMenuBar().setVisible(true);
_pane.setDividerSize(_divsize);
_showGrid.setSelected(_gridEnabled);
_showCompass.setSelected(_compassEnabled);
_toolbar.setVisible(true);
_epanel.setVisible(true);
_pane.resetToPreferredSizes();
SwingUtil.refresh((JComponent)_frame.getContentPane());
}
@Override // documentation inherited
public void actionPerformed (ActionEvent event)
{
String action = event.getActionCommand();
EditorTool tool = _tools.get(action);
if (tool != null) {
setActiveTool(tool);
return;
}
if (action.equals("new")) {
if (saveWarning("clear the scene")) {
newScene();
}
} else if (action.equals("open")) {
if (saveWarning("open a new scene")) {
open();
}
} else if (action.equals("save")) {
if (_file != null) {
save(_file);
} else {
save();
}
} else if (action.equals("save_as")) {
save();
} else if (action.equals("revert")) {
if (saveWarning("revert to the last saved version")) {
open(_file);
}
} else if (action.equals("import")) {
importScene();
} else if (action.equals("export")) {
exportScene();
} else if (action.equals("import_selection")) {
importSelection();
} else if (action.equals("export_selection")) {
exportSelection();
} else if (action.equals("test")) {
testScene();
} else if (action.equals("undo")) {
_undomgr.undo();
updateUndoActions();
} else if (action.equals("redo")) {
_undomgr.redo();
updateUndoActions();
} else if (action.equals("cut")) {
copySelection();
deleteSelection();
} else if (action.equals("copy")) {
copySelection();
} else if (action.equals("paste")) {
Transferable contents = _frame.getToolkit().getSystemClipboard().getContents(this);
Entry[] selection = (Entry[])ToolUtil.getWrappedTransferData(contents);
if (selection != null) {
move(selection);
}
} else if (action.equals("delete")) {
deleteSelection();
} else if (action.equals("rotate_ccw")) {
rotateSelection(+1);
} else if (action.equals("rotate_cw")) {
rotateSelection(-1);
} else if (action.equals("raise")) {
raiseSelection(+1);
} else if (action.equals("lower")) {
raiseSelection(-1);
} else if (action.equals("save_to_palette")) {
setActiveTool(_palette);
_palette.add(_selection);
} else if (action.equals("validate_refs")) {
validateReferences();
} else if (action.equals("delete_errors")) {
deleteErrors();
} else if (action.equals("configs")) {
new ConfigEditor(_msgmgr, _scene.getConfigManager(), _colorpos).setVisible(true);
} else if (action.equals("raise_grid")) {
_grid.setElevation(_grid.getElevation() + 1);
} else if (action.equals("lower_grid")) {
_grid.setElevation(_grid.getElevation() - 1);
} else if (action.equals("reorient")) {
((OrbitCameraHandler)_camhand).getCoords().set(
TudeySceneMetrics.getDefaultCameraConfig().coords);
} else if (action.equals("next_layer")) {
_layers.selectLayer(true);
} else if (action.equals("prev_layer")) {
_layers.selectLayer(false);
} else if (action.equals("markers")) {
_prefs.putBoolean("markersVisible", _markersVisible = !_markers.isSelected());
wasUpdated();
} else if (action.equals("light")) {
_prefs.putBoolean("lightingEnabled", _lightingEnabled = !_light.isSelected());
wasUpdated();
} else if (action.equals("fog")) {
_prefs.putBoolean("fogEnabled", _fogEnabled = !_fog.isSelected());
wasUpdated();
} else if (action.equals("sound")) {
_prefs.putBoolean("soundEnabled", _soundEnabled = !_sound.isSelected());
wasUpdated();
} else if (action.equals("batch_validate")) {
new BatchValidateDialog(this, _frame, _prefs) {
@Override protected boolean validate (String path, PrintStream out)
throws Exception {
TudeySceneModel model = (TudeySceneModel)new BinaryImporter(
new FileInputStream(_rsrcmgr.getResourceFile(path))).readObject();
model.getConfigManager().init("scene", _cfgmgr);
return model.validateReferences(path, out);
}
}.setVisible(true);
} else {
super.actionPerformed(event);
}
}
@Override
public void shutdown ()
{
if (saveWarning("quit")) {
super.shutdown();
}
}
@Override // documentation inherited
protected JComponent createCanvasContainer ()
{
JPanel ccont = new JPanel(new BorderLayout());
ccont.add(_toolbar = new JToolBar(), BorderLayout.NORTH);
ccont.add(_canvas, BorderLayout.CENTER);
_pane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT, true, ccont, _epanel = GroupLayout.makeVStretchBox(5));
_canvas.setMinimumSize(new Dimension(1, 1));
_canvas.setPreferredSize(new Dimension(1, 1));
_pane.setResizeWeight(1.0);
_pane.setOneTouchExpandable(true);
JComponent bcomp = (_canvas instanceof JComponent) ? ((JComponent)_canvas) : ccont;
bindAction(bcomp, KeyEvent.VK_UP, 0, "raise_grid");
bindAction(bcomp, KeyEvent.VK_DOWN, 0, "lower_grid");
return _pane;
}
@Override // documentation inherited
protected Grid createGrid ()
{
return (_grid = new EditorGrid(this));
}
@Override // documentation inherited
protected CanvasToolPrefs createEditablePrefs ()
{
return new SceneEditorPrefs(_prefs);
}
@Override // documentation inherited
protected CameraHandler createCameraHandler ()
{
// just a placeholder; the scene view has the real camera handler
return new OrbitCameraHandler(this);
}
@Override // documentation inherited
protected void didInit ()
{
super.didInit();
// create the scene view
setView(_view = new TudeySceneView(this) {
@Override public void wasRemoved () {
// do not dispose of the sprites/scene
_ctx.getRoot().removeWindow(_inputWindow);
if (_loadingWindow != null) {
_ctx.getRoot().removeWindow(_loadingWindow);
_loadingWindow = null;
}
if (_ctrl != null) {
_ctrl.wasRemoved();
}
_scene.clearEffects();
}
@Override protected OrbitCameraHandler createCameraHandler () {
// camera target elevation matches grid elevation
OrbitCameraHandler camhand = new OrbitCameraHandler(_ctx) {
public void updatePosition () {
_target.z = _grid.getZ();
super.updatePosition();
}
};
// mouse movement is enabled when the tool allows it or control is held down
new MouseOrbiter(camhand, true) {
public void mouseDragged (MouseEvent event) {
if (mouseCameraEnabled()) {
super.mouseDragged(event);
} else {
super.mouseMoved(event);
}
}
public void mouseWheelMoved (MouseWheelEvent event) {
if (mouseCameraEnabled()) {
super.mouseWheelMoved(event);
}
}
}.addTo(_canvas);
return camhand;
}
@Override protected int getMergeGranularity () {
return 0; // can't merge tiles since they must be individually selectable
}
});
// initialize the tools
for (EditorTool tool : _tools.values()) {
tool.init();
}
// create the origin renderable
_origin = new SimpleTransformable(this, RenderQueue.OPAQUE, 0, false, 2) {
@Override protected void draw () {
float z = _grid.getZ() + 0.01f;
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3f(-1f, 0f, z);
GL11.glVertex3f(+1f, 0f, z);
GL11.glVertex3f(0f, -1f, z);
GL11.glVertex3f(0f, +1f, z);
GL11.glEnd();
}
};
_origin.getStates()[RenderState.COLOR_STATE] = ColorState.getInstance(Color4f.RED);
// attempt to load the scene file specified on the command line if any
// (otherwise, create an empty scene)
if (_initScene != null) {
open(_initScene);
} else {
newScene();
}
}
@Override // documentation inherited
protected void updateView (float elapsed)
{
super.updateView(elapsed);
if (!_testing) {
_activeTool.tick(elapsed);
_grid.tick(elapsed);
}
}
@Override // documentation inherited
protected void compositeView ()
{
super.compositeView();
if (_showGrid.isSelected()) {
_origin.composite();
}
if (!_testing) {
_activeTool.composite();
}
}
/**
* Adds a tool to the tool panel.
*/
protected void addTool (JPanel tpanel, ButtonGroup tgroup, String name, EditorTool tool)
{
JToggleButton button = createToggleButton(name);
tpanel.add(button);
tgroup.add(button);
_tools.put(name, tool);
tool.setButton(button);
}
/**
* Creates an icon button with the specified name.
*/
protected JButton createIconButton (String name)
{
JButton button = new JButton(createIcon(name));
button.setMinimumSize(TOOL_BUTTON_SIZE);
button.setMaximumSize(TOOL_BUTTON_SIZE);
button.setPreferredSize(TOOL_BUTTON_SIZE);
button.setActionCommand(name);
button.addActionListener(this);
return button;
}
/**
* Creates a toggle button with different icons for the unselected and selected states.
*/
protected JToggleButton createToggleButton (String name)
{
JToggleButton button = new JToggleButton(createIcon(name));
button.setSelectedIcon(createIcon(name + "_select"));
button.setMinimumSize(TOOL_BUTTON_SIZE);
button.setMaximumSize(TOOL_BUTTON_SIZE);
button.setPreferredSize(TOOL_BUTTON_SIZE);
button.setActionCommand(name);
button.addActionListener(this);
return button;
}
/**
* Creates the named icon.
*/
protected ImageIcon createIcon (String name)
{
BufferedImage image;
try {
image = _rsrcmgr.getImageResource("media/tudey/" + name + ".png");
} catch (IOException e) {
log.warning("Error loading image.", "name", name, e);
image = ImageUtil.createErrorImage(24, 24);
}
return new ImageIcon(image);
}
/**
* Sets the active tool.
*/
protected void setActiveTool (EditorTool tool)
{
if (_activeTool == tool) {
return;
}
if (_activeTool != null) {
_activeTool.deactivate();
_opanel.remove(_activeTool);
}
if ((_activeTool = tool) != null) {
_opanel.add(_activeTool);
_activeTool.activate();
}
// update whether we are showing or hiding layers
boolean hideLayers = (tool instanceof Notepad);
if (hideLayers) {
if (_layers.isVisible()) {
_layerDividerPos = _layerSplit.getDividerLocation();
_layers.setVisible(false);
}
} else {
_layers.setVisible(true);
if (_layerDividerPos != 0) {
_layerSplit.setDividerLocation(_layerDividerPos);
}
}
boolean forceBase = (tool == _globalEditor) ||
(tool == _tileBrush) || (tool == _groundBrush) || (tool == _wallBrush);
if (forceBase) {
_layers.setSelectedLayer(0);
}
SwingUtil.refresh(_opanel);
}
/**
* Binds a keystroke to an action on the specified component.
*/
protected void bindAction (
final JComponent comp, int keyCode, int modifiers, final String action)
{
comp.getInputMap().put(KeyStroke.getKeyStroke(keyCode, modifiers), action);
comp.getActionMap().put(action, new AbstractAction(action) {
public void actionPerformed (ActionEvent event) {
SceneEditor.this.actionPerformed(new ActionEvent(
comp, ActionEvent.ACTION_PERFORMED, action));
}
});
}
/**
* Determines whether mouse camera control is enabled.
*/
protected boolean mouseCameraEnabled ()
{
return !_testing && (_activeTool.allowsMouseCamera() || isControlDown());
}
/**
* Creates a new scene.
*/
protected void newScene ()
{
setScene(new TudeySceneModel());
setFile(null);
}
/**
* Brings up the open dialog.
*/
protected void open ()
{
if (_chooser.showOpenDialog(_frame) == JFileChooser.APPROVE_OPTION) {
open(_chooser.getSelectedFile());
}
_prefs.put("scene_dir", _chooser.getCurrentDirectory().toString());
}
/**
* Attempts to open the specified scene file.
*/
protected void open (File file)
{
try {
BinaryImporter in = new BinaryImporter(new FileInputStream(file));
setScene((TudeySceneModel)in.readObject());
in.close();
setFile(file);
} catch (IOException e) {
log.warning("Failed to open scene [file=" + file + "].", e);
}
}
/**
* Brings up the save dialog.
*/
protected void save ()
{
if (_chooser.showSaveDialog(_frame) == JFileChooser.APPROVE_OPTION) {
save(_chooser.getSelectedFile());
}
_prefs.put("scene_dir", _chooser.getCurrentDirectory().toString());
}
/**
* Attempts to save to the specified file.
*/
protected void save (File file)
{
try {
BinaryExporter out = new BinaryExporter(new FileOutputStream(file));
out.writeObject(_scene);
out.close();
setFile(file);
_scene.setDirty(false);
} catch (IOException e) {
log.warning("Failed to save scene [file=" + file + "].", e);
}
}
/**
* Brings up the import dialog.
*/
protected void importScene ()
{
if (_exportChooser.showOpenDialog(_frame) == JFileChooser.APPROVE_OPTION) {
File file = _exportChooser.getSelectedFile();
try {
XMLImporter in = new XMLImporter(new FileInputStream(file));
setScene((TudeySceneModel)in.readObject());
in.close();
setFile(null);
} catch (IOException e) {
log.warning("Failed to import scene [file=" + file +"].", e);
}
}
_prefs.put("scene_export_dir", _exportChooser.getCurrentDirectory().toString());
}
/**
* Initializes the scene.
*/
protected void setScene (TudeySceneModel scene)
{
if (_scene != null) {
_scene.removeObserver(this);
}
(_scene = scene).addObserver(this);
_scene.init(_cfgmgr);
// update the view
_view.setSceneModel(_scene);
// notify the tools
for (EditorTool tool : _tools.values()) {
tool.sceneChanged(scene);
}
// clear the selection and undo manager
clearSelection();
_undomgr.discardAllEdits();
updateUndoActions();
}
/**
* Updates the enabled states of the undo and redo actions.
*/
protected void updateUndoActions ()
{
_undo.setEnabled(_undomgr.canUndo());
_redo.setEnabled(_undomgr.canRedo());
}
/**
* Brings up the export dialog.
*/
protected void exportScene ()
{
if (_exportChooser.showSaveDialog(_frame) == JFileChooser.APPROVE_OPTION) {
File file = _exportChooser.getSelectedFile();
try {
XMLExporter out = new XMLExporter(new FileOutputStream(file));
out.writeObject(_scene);
out.close();
} catch (IOException e) {
log.warning("Failed to export scene [file=" + file + "].", e);
}
}
_prefs.put("scene_export_dir", _exportChooser.getCurrentDirectory().toString());
}
/**
* Brings up the selection import dialog.
*/
protected void importSelection ()
{
if (_selectionChooser.showOpenDialog(_frame) == JFileChooser.APPROVE_OPTION) {
File file = _selectionChooser.getSelectedFile();
try {
BinaryImporter in = new BinaryImporter(new FileInputStream(file));
move((Entry[])in.readObject());
in.close();
} catch (IOException e) {
log.warning("Failed to import selection [file=" + file +"].", e);
}
}
_prefs.put("selection_dir", _selectionChooser.getCurrentDirectory().toString());
}
/**
* Brings up the selection export dialog.
*/
protected void exportSelection ()
{
if (_selectionChooser.showSaveDialog(_frame) == JFileChooser.APPROVE_OPTION) {
File file = _selectionChooser.getSelectedFile();
try {
BinaryExporter out = new BinaryExporter(new FileOutputStream(file));
out.writeObject(_selection);
out.close();
} catch (IOException e) {
log.warning("Failed to export selection [file=" + file + "].", e);
}
}
_prefs.put("selection_dir", _selectionChooser.getCurrentDirectory().toString());
}
/**
* Sets the file and updates the revert item and title bar.
*/
protected void setFile (File file)
{
_file = file;
_revert.setEnabled(file != null);
updateTitle();
// update recents
if (file != null) {
String name = file.getPath();
_recentFiles.remove(name);
_recentFiles.add(0, name);
CollectionUtil.limit(_recentFiles, MAX_RECENT_FILES);
_prefs.put("recent_files", Joiner.on('\n').join(_recentFiles));
}
// always update the recent menu
_recents.removeAll();
for (String recent : _recentFiles) {
final File recentFile = new File(recent);
Action action = new AbstractAction(recentFile.getName()) {
public void actionPerformed (ActionEvent e) {
open(recentFile);
}
};
action.putValue(Action.SHORT_DESCRIPTION, recentFile.getPath());
_recents.add(new JMenuItem(action));
}
}
/**
* Updates the title based on the file.
*/
protected void updateTitle ()
{
String title = _msgs.get("m.title");
if (_file != null) {
title = title + ": " + _file;
}
_frame.setTitle(title);
}
/**
* Enters the scene test mode.
*/
protected void testScene ()
{
TudeySceneModel scene = _scene.clone();
// remove non-visibile layers
scene.init(_scene.getConfigManager());
List<Object> toRemove = Lists.newArrayList();
List<Boolean> visibility = _layers.getLayerVisibility();
for (Entry entry : scene.getEntries()) {
Object key = entry.getKey();
if (!visibility.get(scene.getLayer(key))) {
toRemove.add(key);
}
}
for (Object key : toRemove) {
scene.removeEntry(key);
}
// configure the scene repository with a copy of our scene
scene.sceneId = ++_sceneId;
_server.getSceneRepository().setSceneModel(scene);
// request to enter
_scenedir.moveTo(_sceneId);
}
/**
* Deletes the entries under the selected region.
*/
protected void deleteSelection ()
{
incrementEditId();
removeEntries(Arrays.asList(_selection));
}
/**
* Rotates the entries under the selection region by the specified amount.
*/
protected void rotateSelection (int amount)
{
// find the pivot point if not yet computed
if (_selectionPivot == null) {
Rect bounds = new Rect(), ebounds = new Rect();
boolean tiles = false;
for (Entry entry : _selection) {
tiles |= (entry instanceof TileEntry);
entry.getBounds(getConfigManager(), ebounds);
bounds.addLocal(ebounds);
}
Vector2f center = bounds.getCenter();
if (tiles) {
// choose the closer of the nearest intersection and the nearest middle point
Vector2f ci = new Vector2f(Math.round(center.x), Math.round(center.y));
Vector2f cm = new Vector2f(
FloatMath.floor(center.x) + 0.5f, FloatMath.floor(center.y) + 0.5f);
center = center.distance(ci) < center.distance(cm) ? ci : cm;
}
_selectionPivot = center;
}
float rotation = FloatMath.HALF_PI * amount;
Vector2f translation = _selectionPivot.subtract(_selectionPivot.rotate(rotation));
Transform2D xform = new Transform2D(translation, rotation);
// transform the entries (retaining the pivot)
Vector2f opivot = _selectionPivot;
transformSelection(new Transform3D(xform));
_selectionPivot = opivot;
}
/**
* Raises or lowers the entries under the selection region by the specified amount.
*/
protected void raiseSelection (int amount)
{
Transform3D xform = new Transform3D(Transform3D.RIGID);
xform.getTranslation().z = TudeySceneMetrics.getTileZ(amount);
transformSelection(xform);
_grid.setElevation(_grid.getElevation() + amount);
}
/**
* Transforms the selection.
*/
protected void transformSelection (Transform3D xform)
{
incrementEditId();
List<Object> removes = Lists.newArrayList();
List<Entry> updates = Lists.newArrayList();
List<Entry> overwrites = Lists.newArrayList();
Entry[] oselection = _selection;
Entry[] nselection = new Entry[oselection.length];
for (int ii = 0; ii < oselection.length; ii++) {
Entry oentry = oselection[ii];
Entry nentry = nselection[ii] = (Entry)oentry.clone();
nentry.transform(getConfigManager(), xform);
Object okey = oentry.getKey(), nkey = nentry.getKey();
if (!okey.equals(nkey)) {
removes.add(okey);
overwrites.add(nentry);
} else {
updates.add(nentry);
}
}
removeEntries(removes.toArray());
updateEntries(updates.toArray(new Entry[updates.size()]));
overwriteEntries(overwrites.toArray(new Entry[overwrites.size()]));
setSelection(nselection);
}
/**
* Copies the selected entries to the clipboard.
*/
protected void copySelection ()
{
// create a cloned array
Entry[] selection = new Entry[_selection.length];
for (int ii = 0; ii < _selection.length; ii++) {
selection[ii] = (Entry)_selection[ii].clone();
}
Clipboard clipboard = _frame.getToolkit().getSystemClipboard();
clipboard.setContents(new ToolUtil.WrappedTransfer(selection), this);
_paste.setEnabled(true);
}
/**
* Validates the scene's references.
*/
protected void validateReferences ()
{
PrintStreamDialog dialog = new PrintStreamDialog(
_frame, _msgs.get("m.validate_refs"), _msgs.get("m.ok"));
_scene.validateReferences("", dialog.getPrintStream());
dialog.maybeShow();
}
/**
* Deletes all entries whose configurations are null or missing.
*/
protected void deleteErrors ()
{
incrementEditId();
Collection<Entry> toProcess =
(_selection.length > 0) ? Arrays.asList(_selection) : _scene.getEntries();
Predicate<Entry> isInvalid = new Predicate<Entry>() {
public boolean apply (Entry entry) {
return !entry.isValid(getConfigManager());
}
};
removeEntries(Collections2.filter(toProcess, isInvalid));
}
/**
* Returns the index of the specified entry within the selection, or -1 if it is not selected.
*/
protected int getSelectionIndex (Entry entry)
{
Object key = entry.getKey();
for (int ii = 0; ii < _selection.length; ii++) {
if (_selection[ii].getKey().equals(key)) {
return ii;
}
}
return -1;
}
/**
* Clears any paint underneath the specified tile entry.
*/
protected void clearPaint (TileEntry entry)
{
if (entry == null) {
return;
}
TileConfig.Original config = entry.getConfig(getConfigManager());
Rectangle region = new Rectangle();
entry.getRegion(config, region);
setPaint(region, null);
}
/**
* Show a warning if the scene is unsaved. Return true if it's ok to proceed with
* the operation.
*/
protected boolean saveWarning (String message)
{
- if (!_scene.isDirty()) {
+ if ((_scene == null) || !_scene.isDirty()) {
return true;
}
int option = JOptionPane.showOptionDialog(_frame,
"Discard unsaved changes and " + message + "?", "Discard changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
new Object[] { "Cancel", "Save First", "Discard Changes" }, "Cancel");
switch (option) {
default:
return false;
case 1:
if (_file != null) {
save(_file);
return true;
}
save();
return false;
case 2:
return true;
}
}
/**
* The preferences for the scene editor.
*/
@EditorMessageBundle("editor.default")
protected class SceneEditorPrefs extends CanvasToolPrefs
{
/**
* Creates a new preferences object.
*/
public SceneEditorPrefs (Preferences prefs)
{
super(prefs);
}
/**
* Sets the refresh interval.
*/
@Editable(weight=8)
public void setDebugRegions (boolean debug)
{
_prefs.putBoolean("debug_regions", debug);
}
/**
* Returns the refresh interval.
*/
@Editable
public boolean getDebugRegions ()
{
return _prefs.getBoolean("debug_regions", false);
}
}
/** The file to attempt to load on initialization, if any. */
protected File _initScene;
/** The undo manager. */
protected UndoManager _undomgr;
/** The undoable edit support object. */
protected UndoableEditSupport _undoSupport;
/** The current edit id. */
protected int _editId;
/** The revert menu item. */
protected JMenuItem _revert;
/** The selection export menu item. */
protected JMenuItem _exportSelection;
/** The undo and redo actions. */
protected Action _undo, _redo;
/** The edit menu actions. */
protected Action _cut, _copy, _paste, _delete;
/** The recently-opened files. */
protected JMenu _recents;
/** The rotate menu items. */
protected JMenuItem _rotateCW, _rotateCCW;
/** The raise/lower menu items. */
protected JMenuItem _raise, _lower;
/** The save-to-palette menu item. */
protected JMenuItem _saveToPalette;
/** The file chooser for opening and saving scene files. */
protected JFileChooser _chooser;
/** The file chooser for importing and exporting scene files. */
protected JFileChooser _exportChooser;
/** The file chooser for importing and exporting selections. */
protected JFileChooser _selectionChooser;
/** The split pane containing the canvas, toolbar, etc. */
protected JSplitPane _pane;
/** The size of the divider. */
protected int _divsize;
/** Whether or not the compass/grid are enabled. */
protected boolean _compassEnabled, _gridEnabled;
/** Set when we are in test mode. */
protected boolean _testing;
/** The tool bar. */
protected JToolBar _toolbar;
/** Toggle buttons. */
protected JToggleButton _markers, _light, _fog, _sound;
/** The panel that holds the editor bits. */
protected JPanel _epanel;
/** The panel that holds the tool options. */
protected JPanel _opanel;
/** Tools mapped by name. */
protected Map<String, EditorTool> _tools = Maps.newHashMap();
/** The arrow tool. */
protected Arrow _arrow;
/** The selector tool. */
protected Selector _selector;
/** The mover tool. */
protected Mover _mover;
/** The placer tool. */
protected Placer _placer;
/** The path definer tool. */
protected PathDefiner _pathDefiner;
/** The area definer tool. */
protected AreaDefiner _areaDefiner;
/** The global editor tool. */
protected GlobalEditor _globalEditor;
/** The tile brush tool. */
protected TileBrush _tileBrush;
/** The ground brush tool. */
protected GroundBrush _groundBrush;
/** The wall brush tool. */
protected WallBrush _wallBrush;
/** The palette tool. */
protected Palette _palette;
/** The pane splitting layers from the other tools. */
protected JSplitPane _layerSplit;
/** The last position of the layer divider. */
protected int _layerDividerPos;
/** The layer display tool. */
protected Layers _layers;
/** The active tool. */
protected EditorTool _activeTool;
/** The loaded scene file. */
protected File _file;
/** The scene being edited. */
protected TudeySceneModel _scene;
/** The scene view. */
protected TudeySceneView _view;
/** The scene id used for testing. */
protected int _sceneId;
/** Whether or not markers are visible. */
@Scoped
protected boolean _markersVisible = _prefs.getBoolean("markersVisible", true);
/** Whether or not lighting is enabled. */
@Scoped
protected boolean _lightingEnabled = _prefs.getBoolean("lightingEnabled", true);
/** Whether or not fog is enabled. */
@Scoped
protected boolean _fogEnabled = _prefs.getBoolean("fogEnabled", true);
/** Whether or not sound is enabled. */
@Scoped
protected boolean _soundEnabled = _prefs.getBoolean("soundEnabled", true);
/** A casted reference to the editor grid. */
protected EditorGrid _grid;
/** Draws the coordinate system origin. */
protected SimpleTransformable _origin;
/** Whether or not the shift, control, and/or alt keys are being held down. */
protected boolean _shiftDown, _controlDown, _altDown;
/** Whether or not each of the mouse buttons are being held down on the canvas. */
protected boolean _firstButtonDown, _secondButtonDown, _thirdButtonDown;
/** The selected elements. */
protected Entry[] _selection = new Entry[0];
/** The center of rotation for the selection. */
protected Vector2f _selectionPivot;
/** Used for picking. */
protected Ray3D _pick = new Ray3D();
/** Holds the location of the pick result. */
protected Vector3f _pt = new Vector3f();
/** The application preferences. */
protected static Preferences _prefs = Preferences.userNodeForPackage(SceneEditor.class);
/** Recently opened files. */
protected static List<String> _recentFiles = Lists.newArrayList(
Splitter.on('\n').omitEmptyStrings().split(_prefs.get("recent_files", "")));
/** The maximum number of recently opened files to show. */
protected static final int MAX_RECENT_FILES = 6;
/** The size of the tool buttons. */
protected static final Dimension TOOL_BUTTON_SIZE = new Dimension(28, 28);
}
| true | true | protected boolean saveWarning (String message)
{
if (!_scene.isDirty()) {
return true;
}
int option = JOptionPane.showOptionDialog(_frame,
"Discard unsaved changes and " + message + "?", "Discard changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
new Object[] { "Cancel", "Save First", "Discard Changes" }, "Cancel");
switch (option) {
default:
return false;
case 1:
if (_file != null) {
save(_file);
return true;
}
save();
return false;
case 2:
return true;
}
}
/**
* The preferences for the scene editor.
*/
@EditorMessageBundle("editor.default")
protected class SceneEditorPrefs extends CanvasToolPrefs
{
/**
* Creates a new preferences object.
*/
public SceneEditorPrefs (Preferences prefs)
{
super(prefs);
}
/**
* Sets the refresh interval.
*/
@Editable(weight=8)
public void setDebugRegions (boolean debug)
{
_prefs.putBoolean("debug_regions", debug);
}
/**
* Returns the refresh interval.
*/
@Editable
public boolean getDebugRegions ()
{
return _prefs.getBoolean("debug_regions", false);
}
}
/** The file to attempt to load on initialization, if any. */
protected File _initScene;
/** The undo manager. */
protected UndoManager _undomgr;
/** The undoable edit support object. */
protected UndoableEditSupport _undoSupport;
/** The current edit id. */
protected int _editId;
/** The revert menu item. */
protected JMenuItem _revert;
/** The selection export menu item. */
protected JMenuItem _exportSelection;
/** The undo and redo actions. */
protected Action _undo, _redo;
/** The edit menu actions. */
protected Action _cut, _copy, _paste, _delete;
/** The recently-opened files. */
protected JMenu _recents;
/** The rotate menu items. */
protected JMenuItem _rotateCW, _rotateCCW;
/** The raise/lower menu items. */
protected JMenuItem _raise, _lower;
/** The save-to-palette menu item. */
protected JMenuItem _saveToPalette;
/** The file chooser for opening and saving scene files. */
protected JFileChooser _chooser;
/** The file chooser for importing and exporting scene files. */
protected JFileChooser _exportChooser;
/** The file chooser for importing and exporting selections. */
protected JFileChooser _selectionChooser;
/** The split pane containing the canvas, toolbar, etc. */
protected JSplitPane _pane;
/** The size of the divider. */
protected int _divsize;
/** Whether or not the compass/grid are enabled. */
protected boolean _compassEnabled, _gridEnabled;
/** Set when we are in test mode. */
protected boolean _testing;
/** The tool bar. */
protected JToolBar _toolbar;
/** Toggle buttons. */
protected JToggleButton _markers, _light, _fog, _sound;
/** The panel that holds the editor bits. */
protected JPanel _epanel;
/** The panel that holds the tool options. */
protected JPanel _opanel;
/** Tools mapped by name. */
protected Map<String, EditorTool> _tools = Maps.newHashMap();
/** The arrow tool. */
protected Arrow _arrow;
/** The selector tool. */
protected Selector _selector;
/** The mover tool. */
protected Mover _mover;
/** The placer tool. */
protected Placer _placer;
/** The path definer tool. */
protected PathDefiner _pathDefiner;
/** The area definer tool. */
protected AreaDefiner _areaDefiner;
/** The global editor tool. */
protected GlobalEditor _globalEditor;
/** The tile brush tool. */
protected TileBrush _tileBrush;
/** The ground brush tool. */
protected GroundBrush _groundBrush;
/** The wall brush tool. */
protected WallBrush _wallBrush;
/** The palette tool. */
protected Palette _palette;
/** The pane splitting layers from the other tools. */
protected JSplitPane _layerSplit;
/** The last position of the layer divider. */
protected int _layerDividerPos;
/** The layer display tool. */
protected Layers _layers;
/** The active tool. */
protected EditorTool _activeTool;
/** The loaded scene file. */
protected File _file;
/** The scene being edited. */
protected TudeySceneModel _scene;
/** The scene view. */
protected TudeySceneView _view;
/** The scene id used for testing. */
protected int _sceneId;
/** Whether or not markers are visible. */
@Scoped
protected boolean _markersVisible = _prefs.getBoolean("markersVisible", true);
/** Whether or not lighting is enabled. */
@Scoped
protected boolean _lightingEnabled = _prefs.getBoolean("lightingEnabled", true);
/** Whether or not fog is enabled. */
@Scoped
protected boolean _fogEnabled = _prefs.getBoolean("fogEnabled", true);
/** Whether or not sound is enabled. */
@Scoped
protected boolean _soundEnabled = _prefs.getBoolean("soundEnabled", true);
/** A casted reference to the editor grid. */
protected EditorGrid _grid;
/** Draws the coordinate system origin. */
protected SimpleTransformable _origin;
/** Whether or not the shift, control, and/or alt keys are being held down. */
protected boolean _shiftDown, _controlDown, _altDown;
/** Whether or not each of the mouse buttons are being held down on the canvas. */
protected boolean _firstButtonDown, _secondButtonDown, _thirdButtonDown;
/** The selected elements. */
protected Entry[] _selection = new Entry[0];
/** The center of rotation for the selection. */
protected Vector2f _selectionPivot;
/** Used for picking. */
protected Ray3D _pick = new Ray3D();
/** Holds the location of the pick result. */
protected Vector3f _pt = new Vector3f();
/** The application preferences. */
protected static Preferences _prefs = Preferences.userNodeForPackage(SceneEditor.class);
/** Recently opened files. */
protected static List<String> _recentFiles = Lists.newArrayList(
Splitter.on('\n').omitEmptyStrings().split(_prefs.get("recent_files", "")));
/** The maximum number of recently opened files to show. */
protected static final int MAX_RECENT_FILES = 6;
/** The size of the tool buttons. */
protected static final Dimension TOOL_BUTTON_SIZE = new Dimension(28, 28);
}
| protected boolean saveWarning (String message)
{
if ((_scene == null) || !_scene.isDirty()) {
return true;
}
int option = JOptionPane.showOptionDialog(_frame,
"Discard unsaved changes and " + message + "?", "Discard changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
new Object[] { "Cancel", "Save First", "Discard Changes" }, "Cancel");
switch (option) {
default:
return false;
case 1:
if (_file != null) {
save(_file);
return true;
}
save();
return false;
case 2:
return true;
}
}
/**
* The preferences for the scene editor.
*/
@EditorMessageBundle("editor.default")
protected class SceneEditorPrefs extends CanvasToolPrefs
{
/**
* Creates a new preferences object.
*/
public SceneEditorPrefs (Preferences prefs)
{
super(prefs);
}
/**
* Sets the refresh interval.
*/
@Editable(weight=8)
public void setDebugRegions (boolean debug)
{
_prefs.putBoolean("debug_regions", debug);
}
/**
* Returns the refresh interval.
*/
@Editable
public boolean getDebugRegions ()
{
return _prefs.getBoolean("debug_regions", false);
}
}
/** The file to attempt to load on initialization, if any. */
protected File _initScene;
/** The undo manager. */
protected UndoManager _undomgr;
/** The undoable edit support object. */
protected UndoableEditSupport _undoSupport;
/** The current edit id. */
protected int _editId;
/** The revert menu item. */
protected JMenuItem _revert;
/** The selection export menu item. */
protected JMenuItem _exportSelection;
/** The undo and redo actions. */
protected Action _undo, _redo;
/** The edit menu actions. */
protected Action _cut, _copy, _paste, _delete;
/** The recently-opened files. */
protected JMenu _recents;
/** The rotate menu items. */
protected JMenuItem _rotateCW, _rotateCCW;
/** The raise/lower menu items. */
protected JMenuItem _raise, _lower;
/** The save-to-palette menu item. */
protected JMenuItem _saveToPalette;
/** The file chooser for opening and saving scene files. */
protected JFileChooser _chooser;
/** The file chooser for importing and exporting scene files. */
protected JFileChooser _exportChooser;
/** The file chooser for importing and exporting selections. */
protected JFileChooser _selectionChooser;
/** The split pane containing the canvas, toolbar, etc. */
protected JSplitPane _pane;
/** The size of the divider. */
protected int _divsize;
/** Whether or not the compass/grid are enabled. */
protected boolean _compassEnabled, _gridEnabled;
/** Set when we are in test mode. */
protected boolean _testing;
/** The tool bar. */
protected JToolBar _toolbar;
/** Toggle buttons. */
protected JToggleButton _markers, _light, _fog, _sound;
/** The panel that holds the editor bits. */
protected JPanel _epanel;
/** The panel that holds the tool options. */
protected JPanel _opanel;
/** Tools mapped by name. */
protected Map<String, EditorTool> _tools = Maps.newHashMap();
/** The arrow tool. */
protected Arrow _arrow;
/** The selector tool. */
protected Selector _selector;
/** The mover tool. */
protected Mover _mover;
/** The placer tool. */
protected Placer _placer;
/** The path definer tool. */
protected PathDefiner _pathDefiner;
/** The area definer tool. */
protected AreaDefiner _areaDefiner;
/** The global editor tool. */
protected GlobalEditor _globalEditor;
/** The tile brush tool. */
protected TileBrush _tileBrush;
/** The ground brush tool. */
protected GroundBrush _groundBrush;
/** The wall brush tool. */
protected WallBrush _wallBrush;
/** The palette tool. */
protected Palette _palette;
/** The pane splitting layers from the other tools. */
protected JSplitPane _layerSplit;
/** The last position of the layer divider. */
protected int _layerDividerPos;
/** The layer display tool. */
protected Layers _layers;
/** The active tool. */
protected EditorTool _activeTool;
/** The loaded scene file. */
protected File _file;
/** The scene being edited. */
protected TudeySceneModel _scene;
/** The scene view. */
protected TudeySceneView _view;
/** The scene id used for testing. */
protected int _sceneId;
/** Whether or not markers are visible. */
@Scoped
protected boolean _markersVisible = _prefs.getBoolean("markersVisible", true);
/** Whether or not lighting is enabled. */
@Scoped
protected boolean _lightingEnabled = _prefs.getBoolean("lightingEnabled", true);
/** Whether or not fog is enabled. */
@Scoped
protected boolean _fogEnabled = _prefs.getBoolean("fogEnabled", true);
/** Whether or not sound is enabled. */
@Scoped
protected boolean _soundEnabled = _prefs.getBoolean("soundEnabled", true);
/** A casted reference to the editor grid. */
protected EditorGrid _grid;
/** Draws the coordinate system origin. */
protected SimpleTransformable _origin;
/** Whether or not the shift, control, and/or alt keys are being held down. */
protected boolean _shiftDown, _controlDown, _altDown;
/** Whether or not each of the mouse buttons are being held down on the canvas. */
protected boolean _firstButtonDown, _secondButtonDown, _thirdButtonDown;
/** The selected elements. */
protected Entry[] _selection = new Entry[0];
/** The center of rotation for the selection. */
protected Vector2f _selectionPivot;
/** Used for picking. */
protected Ray3D _pick = new Ray3D();
/** Holds the location of the pick result. */
protected Vector3f _pt = new Vector3f();
/** The application preferences. */
protected static Preferences _prefs = Preferences.userNodeForPackage(SceneEditor.class);
/** Recently opened files. */
protected static List<String> _recentFiles = Lists.newArrayList(
Splitter.on('\n').omitEmptyStrings().split(_prefs.get("recent_files", "")));
/** The maximum number of recently opened files to show. */
protected static final int MAX_RECENT_FILES = 6;
/** The size of the tool buttons. */
protected static final Dimension TOOL_BUTTON_SIZE = new Dimension(28, 28);
}
|
diff --git a/spring-datastore-mongo/src/main/groovy/org/springframework/datastore/mapping/mongo/query/MongoQuery.java b/spring-datastore-mongo/src/main/groovy/org/springframework/datastore/mapping/mongo/query/MongoQuery.java
index b3d37b1b..bd4e5498 100644
--- a/spring-datastore-mongo/src/main/groovy/org/springframework/datastore/mapping/mongo/query/MongoQuery.java
+++ b/spring-datastore-mongo/src/main/groovy/org/springframework/datastore/mapping/mongo/query/MongoQuery.java
@@ -1,556 +1,557 @@
/* Copyright (C) 2010 SpringSource
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.mapping.mongo.query;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.data.document.mongodb.DBCallback;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.datastore.mapping.model.PersistentEntity;
import org.springframework.datastore.mapping.model.PersistentProperty;
import org.springframework.datastore.mapping.model.types.Association;
import org.springframework.datastore.mapping.model.types.ToOne;
import org.springframework.datastore.mapping.mongo.MongoSession;
import org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister;
import org.springframework.datastore.mapping.query.Query;
import org.springframework.datastore.mapping.query.Restrictions;
import org.springframework.datastore.mapping.query.projections.ManualProjections;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
/**
* A {@link org.springframework.datastore.mapping.query.Query} implementation for the Mongo document store
*
* @author Graeme Rocher
* @since 1.0
*/
@SuppressWarnings("rawtypes")
public class MongoQuery extends Query{
private static Map<Class, QueryHandler> queryHandlers = new HashMap<Class, QueryHandler>();
private static Map<Class, QueryHandler> negatedHandlers = new HashMap<Class, QueryHandler>();
public static final String MONGO_IN_OPERATOR = "$in";
public static final String MONGO_OR_OPERATOR = "$or";
public static final String MONGO_GTE_OPERATOR = "$gte";
public static final String MONGO_LTE_OPERATOR = "$lte";
public static final String MONGO_GT_OPERATOR = "$gt";
public static final String MONGO_LT_OPERATOR = "$lt";
public static final String MONGO_NE_OPERATOR = "$ne";
public static final String MONGO_NIN_OPERATOR = "$nin";
static {
queryHandlers.put(IdEquals.class, new QueryHandler<IdEquals>() {
@Override
public void handle(PersistentEntity entity, IdEquals criterion,
DBObject query) {
query.put(MongoEntityPersister.MONGO_ID_FIELD, criterion.getValue());
}
});
queryHandlers.put(Equals.class, new QueryHandler<Equals>() {
public void handle(PersistentEntity entity, Equals criterion, DBObject query) {
String propertyName = getPropertyName(entity, criterion);
query.put(propertyName, criterion.getValue());
}
});
queryHandlers.put(NotEquals.class, new QueryHandler<NotEquals>() {
public void handle(PersistentEntity entity, NotEquals criterion, DBObject query) {
DBObject notEqualQuery = new BasicDBObject();
notEqualQuery.put(MONGO_NE_OPERATOR, criterion.getValue());
String propertyName = getPropertyName(entity, criterion);
query.put(propertyName, notEqualQuery);
}
});
queryHandlers.put(Like.class, new QueryHandler<Like>() {
public void handle(PersistentEntity entity, Like like, DBObject query) {
Object value = like.getValue();
if(value == null) value = "null";
String expr = value.toString().replace("%", ".*");
if(!expr.startsWith(".*")) {
expr = '^'+expr;
}
Pattern regex = Pattern.compile(expr);
String propertyName = getPropertyName(entity, like);
query.put(propertyName, regex);
}
});
queryHandlers.put(RLike.class, new QueryHandler<RLike>() {
public void handle(PersistentEntity entity, RLike like, DBObject query) {
Object value = like.getValue();
if (value == null) value = "null";
final String expr = value.toString();
Pattern regex = Pattern.compile(expr);
String propertyName = getPropertyName(entity, like);
query.put(propertyName, regex);
}
});
queryHandlers.put(In.class, new QueryHandler<In>() {
public void handle(PersistentEntity entity, In in, DBObject query) {
DBObject inQuery = new BasicDBObject();
inQuery.put(MONGO_IN_OPERATOR, in.getValues());
String propertyName = getPropertyName(entity, in);
query.put(propertyName, inQuery);
}
});
queryHandlers.put(Between.class, new QueryHandler<Between>() {
public void handle(PersistentEntity entity, Between between, DBObject query) {
DBObject betweenQuery = new BasicDBObject();
betweenQuery.put(MONGO_GTE_OPERATOR, between.getFrom());
betweenQuery.put(MONGO_LTE_OPERATOR, between.getTo());
String propertyName = getPropertyName(entity, between);
query.put(propertyName, betweenQuery);
}
});
queryHandlers.put(GreaterThan.class, new QueryHandler<GreaterThan>() {
public void handle(PersistentEntity entity, GreaterThan criterion, DBObject query) {
DBObject greaterThanQuery = new BasicDBObject();
greaterThanQuery.put(MONGO_GT_OPERATOR, criterion.getValue());
String propertyName = getPropertyName(entity, criterion);
query.put(propertyName, greaterThanQuery);
}
});
queryHandlers.put(GreaterThanEquals.class, new QueryHandler<GreaterThanEquals>() {
public void handle(PersistentEntity entity, GreaterThanEquals criterion, DBObject query) {
DBObject greaterThanQuery = new BasicDBObject();
greaterThanQuery.put(MONGO_GTE_OPERATOR, criterion.getValue());
String propertyName = getPropertyName(entity, criterion);
query.put(propertyName, greaterThanQuery);
}
});
queryHandlers.put(LessThan.class, new QueryHandler<LessThan>() {
public void handle(PersistentEntity entity, LessThan criterion, DBObject query) {
DBObject lessThanQuery = new BasicDBObject();
lessThanQuery.put(MONGO_LT_OPERATOR, criterion.getValue());
String propertyName = getPropertyName(entity, criterion);
query.put(propertyName, lessThanQuery);
}
});
queryHandlers.put(LessThanEquals.class, new QueryHandler<LessThanEquals>() {
public void handle(PersistentEntity entity, LessThanEquals criterion, DBObject query) {
DBObject lessThanQuery = new BasicDBObject();
lessThanQuery.put(MONGO_LTE_OPERATOR, criterion.getValue());
String propertyName = getPropertyName(entity, criterion);
query.put(propertyName, lessThanQuery);
}
});
queryHandlers.put(Conjunction.class, new QueryHandler<Conjunction>() {
public void handle(PersistentEntity entity, Conjunction criterion, DBObject query) {
populateMongoQuery(entity, query, criterion);
}
});
queryHandlers.put(Negation.class, new QueryHandler<Negation>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, Negation criteria, DBObject query) {
for (Criterion criterion : criteria.getCriteria()) {
final QueryHandler queryHandler = negatedHandlers.get(criterion.getClass());
if(queryHandler != null) {
queryHandler.handle(entity, criterion, query);
}
else {
throw new UnsupportedOperationException("Query of type "+criterion.getClass().getSimpleName()+" cannot be negated");
}
}
}
});
queryHandlers.put(Disjunction.class, new QueryHandler<Disjunction>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, Disjunction criterion, DBObject query) {
List orList = new ArrayList();
for (Criterion subCriterion : criterion.getCriteria()) {
final QueryHandler queryHandler = queryHandlers.get(subCriterion.getClass());
if(queryHandler != null) {
DBObject dbo = new BasicDBObject();
queryHandler.handle(entity, subCriterion, dbo);
orList.add(dbo);
}
}
query.put(MONGO_OR_OPERATOR, orList);
}
});
negatedHandlers.put(Equals.class, new QueryHandler<Equals>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, Equals criterion, DBObject query) {
queryHandlers.get(NotEquals.class).handle(entity, Restrictions.ne(criterion.getProperty(), criterion.getValue()), query);
}
});
negatedHandlers.put(NotEquals.class, new QueryHandler<NotEquals>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, NotEquals criterion, DBObject query) {
queryHandlers.get(Equals.class).handle(entity, Restrictions.eq(criterion.getProperty(), criterion.getValue()), query);
}
});
negatedHandlers.put(In.class, new QueryHandler<In>() {
public void handle(PersistentEntity entity, In in, DBObject query) {
DBObject inQuery = new BasicDBObject();
inQuery.put(MONGO_NIN_OPERATOR, in.getValues());
query.put(in.getProperty(), inQuery);
}
});
negatedHandlers.put(Between.class, new QueryHandler<Between>() {
public void handle(PersistentEntity entity, Between between, DBObject query) {
DBObject betweenQuery = new BasicDBObject();
betweenQuery.put(MONGO_LTE_OPERATOR, between.getFrom());
betweenQuery.put(MONGO_GTE_OPERATOR, between.getTo());
query.put(between.getProperty(), betweenQuery);
}
});
negatedHandlers.put(GreaterThan.class, new QueryHandler<GreaterThan>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, GreaterThan criterion, DBObject query) {
queryHandlers.get(LessThan.class).handle(entity, Restrictions.lt(criterion.getProperty(), criterion.getValue()), query);
}
});
negatedHandlers.put(GreaterThanEquals.class, new QueryHandler<GreaterThanEquals>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, GreaterThanEquals criterion, DBObject query) {
queryHandlers.get(LessThanEquals.class).handle(entity, Restrictions.lte(criterion.getProperty(), criterion.getValue()), query);
}
});
negatedHandlers.put(LessThan.class, new QueryHandler<LessThan>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, LessThan criterion, DBObject query) {
queryHandlers.get(GreaterThan.class).handle(entity, Restrictions.gt(criterion.getProperty(), criterion.getValue()), query);
}
});
negatedHandlers.put(LessThanEquals.class, new QueryHandler<LessThanEquals>() {
@SuppressWarnings("unchecked")
public void handle(PersistentEntity entity, LessThanEquals criterion, DBObject query) {
queryHandlers.get(GreaterThanEquals.class).handle(entity, Restrictions.gte(criterion.getProperty(), criterion.getValue()), query);
}
});
}
private MongoSession mongoSession;
private MongoEntityPersister mongoEntityPersister;
private ManualProjections manualProjections;
public MongoQuery(MongoSession session, PersistentEntity entity) {
super(session, entity);
this.mongoSession = session;
this.manualProjections = new ManualProjections(entity);
this.mongoEntityPersister = (MongoEntityPersister) session.getPersister(entity);
}
@Override
protected void flushBeforeQuery() {
// with Mongo we only flush the session if a transaction is not active to allow for session-managed transactions
if(!TransactionSynchronizationManager.isSynchronizationActive()) {
super.flushBeforeQuery();
}
}
/**
* Gets the Mongo query for this query instance
*
* @return The Mongo query
*/
public DBObject getMongoQuery() {
DBObject query = createQueryObject(entity);
populateMongoQuery(entity, query,criteria);
return query;
}
@Override
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
final MongoTemplate template = mongoSession.getMongoTemplate(entity);
return template.execute(new DBCallback<List>() {
@Override
public List doInDB(DB db) throws MongoException,
DataAccessException {
final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
if(uniqueResult) {
final DBObject dbObject;
if(criteria.isEmpty()) {
if(entity.isRoot()) {
dbObject = collection.findOne();
}
else {
DBObject query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD, entity.getDiscriminator());
dbObject = collection.findOne(query);
}
}
else {
DBObject query = getMongoQuery();
dbObject = collection.findOne(query);
}
final Object object = createObjectFromDBObject(dbObject);
return wrapObjectResultInList(object);
}
else {
DBCursor cursor;
DBObject query = createQueryObject(entity);
final List<Projection> projectionList = projections().getProjectionList();
if(projectionList.isEmpty()) {
cursor = executeQuery(entity, criteria, collection, query);
return new MongoResultList(cursor, mongoEntityPersister);
}
else {
List projectedResults = new ArrayList();
for (Projection projection : projectionList) {
if(projection instanceof CountProjection) {
// For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
//projectedResults.add(collection.getCount(query));
cursor = executeQuery(entity, criteria, collection, query);
projectedResults.add(cursor.size());
}
else if(projection instanceof MinProjection) {
cursor = executeQuery(entity, criteria, collection, query);
MinProjection mp = (MinProjection) projection;
MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
projectedResults.add(manualProjections.min((Collection) results.clone(), mp.getPropertyName()));
}
else if(projection instanceof MaxProjection) {
cursor = executeQuery(entity, criteria, collection, query);
MaxProjection mp = (MaxProjection) projection;
MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
projectedResults.add( manualProjections.max((Collection) results.clone(), mp.getPropertyName()) );
}
else if((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) {
final PersistentProperty persistentProperty;
final String propertyName;
if(projection instanceof IdProjection) {
persistentProperty = entity.getIdentity();
propertyName = MongoEntityPersister.MONGO_ID_FIELD;
}
else {
PropertyProjection pp = (PropertyProjection) projection;
persistentProperty = entity.getPropertyByName(pp.getPropertyName());
propertyName = pp.getPropertyName();
}
if(persistentProperty != null) {
+ populateMongoQuery(entity, query, criteria);
List propertyResults = collection.distinct(propertyName, query);
if(persistentProperty instanceof ToOne) {
Association a = (Association) persistentProperty;
propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(), propertyResults);
}
if(projectedResults.size() == 0 && projectionList.size() == 1) {
return propertyResults;
}
else {
projectedResults.add(propertyResults);
}
}
else {
throw new InvalidDataAccessResourceUsageException("Cannot use ["+projection.getClass().getSimpleName()+"] projection on non-existent property: " + propertyName);
}
}
}
return projectedResults;
}
}
}
protected DBCursor executeQuery(final PersistentEntity entity,
final Junction criteria, final DBCollection collection,
DBObject query) {
final DBCursor cursor;
if(criteria.isEmpty()) {
cursor = executeQueryAndApplyPagination(collection, query);
}
else {
populateMongoQuery(entity, query, criteria);
cursor = executeQueryAndApplyPagination(collection,query);
}
return cursor;
}
protected DBCursor executeQueryAndApplyPagination(
final DBCollection collection, DBObject query) {
final DBCursor cursor;
cursor = collection.find(query);
if(offset > 0) {
cursor.skip(offset);
}
if(max > -1) {
cursor.limit(max);
}
for (Order order : orderBy) {
DBObject orderObject = new BasicDBObject();
orderObject.put(order.getProperty(), order.getDirection() == Order.Direction.DESC ? -1 : 1);
cursor.sort(orderObject);
}
return cursor;
}
});
}
private DBObject createQueryObject(PersistentEntity entity) {
DBObject query;
if(entity.isRoot()) {
query = new BasicDBObject();
}
else {
query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD, entity.getDiscriminator());
}
return query;
}
@SuppressWarnings("unchecked")
public static void populateMongoQuery(PersistentEntity entity, DBObject query, Junction criteria) {
List disjunction = null;
if(criteria instanceof Disjunction) {
disjunction = new ArrayList();
query.put(MONGO_OR_OPERATOR,disjunction);
}
for (Criterion criterion : criteria.getCriteria()) {
final QueryHandler queryHandler = queryHandlers.get(criterion.getClass());
if(queryHandler != null) {
DBObject dbo = query;
if(disjunction != null) {
dbo = new BasicDBObject();
disjunction.add(dbo);
}
queryHandler.handle(entity, criterion, dbo);
}
else {
throw new UnsupportedOperationException("Queries of type "+criterion.getClass().getSimpleName()+" are not supported by this implementation");
}
}
}
protected static String getPropertyName(PersistentEntity entity,
PropertyCriterion criterion) {
String propertyName = criterion.getProperty();
if(entity.isIdentityName(propertyName)) {
propertyName = MongoEntityPersister.MONGO_ID_FIELD;
}
return propertyName;
}
private Object createObjectFromDBObject(DBObject dbObject) {
final Object id = dbObject.get(MongoEntityPersister.MONGO_ID_FIELD);
return mongoEntityPersister.createObjectFromNativeEntry(getEntity(), (Serializable) id, dbObject);
}
@SuppressWarnings("unchecked")
private List wrapObjectResultInList(Object object) {
List result = new ArrayList();
result.add(object);
return result;
}
private static interface QueryHandler<T> {
public void handle(PersistentEntity entity, T criterion, DBObject query);
}
public static class MongoResultList extends ArrayList{
private MongoEntityPersister mongoEntityPersister;
@SuppressWarnings("unchecked")
public MongoResultList(DBCursor cursor, MongoEntityPersister mongoEntityPersister) {
super.addAll(cursor.toArray());
this.mongoEntityPersister = mongoEntityPersister;
}
@Override
public Object get(int index) {
Object object = super.get(index);
if(object instanceof DBObject) {
object = convertDBObject(object);
set(index, object);
}
return object;
}
protected Object convertDBObject(Object object) {
final DBObject dbObject = (DBObject) object;
Object id = dbObject.get(MongoEntityPersister.MONGO_ID_FIELD);
object = mongoEntityPersister.createObjectFromNativeEntry(mongoEntityPersister.getPersistentEntity(), (Serializable) id, dbObject);
return object;
}
@Override
public Object clone() {
List arrayList = new ArrayList();
for (Object object : this) {
if(object instanceof DBObject) {
object = convertDBObject(object);
}
arrayList.add(object);
}
return arrayList;
}
}
}
| true | true | protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
final MongoTemplate template = mongoSession.getMongoTemplate(entity);
return template.execute(new DBCallback<List>() {
@Override
public List doInDB(DB db) throws MongoException,
DataAccessException {
final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
if(uniqueResult) {
final DBObject dbObject;
if(criteria.isEmpty()) {
if(entity.isRoot()) {
dbObject = collection.findOne();
}
else {
DBObject query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD, entity.getDiscriminator());
dbObject = collection.findOne(query);
}
}
else {
DBObject query = getMongoQuery();
dbObject = collection.findOne(query);
}
final Object object = createObjectFromDBObject(dbObject);
return wrapObjectResultInList(object);
}
else {
DBCursor cursor;
DBObject query = createQueryObject(entity);
final List<Projection> projectionList = projections().getProjectionList();
if(projectionList.isEmpty()) {
cursor = executeQuery(entity, criteria, collection, query);
return new MongoResultList(cursor, mongoEntityPersister);
}
else {
List projectedResults = new ArrayList();
for (Projection projection : projectionList) {
if(projection instanceof CountProjection) {
// For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
//projectedResults.add(collection.getCount(query));
cursor = executeQuery(entity, criteria, collection, query);
projectedResults.add(cursor.size());
}
else if(projection instanceof MinProjection) {
cursor = executeQuery(entity, criteria, collection, query);
MinProjection mp = (MinProjection) projection;
MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
projectedResults.add(manualProjections.min((Collection) results.clone(), mp.getPropertyName()));
}
else if(projection instanceof MaxProjection) {
cursor = executeQuery(entity, criteria, collection, query);
MaxProjection mp = (MaxProjection) projection;
MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
projectedResults.add( manualProjections.max((Collection) results.clone(), mp.getPropertyName()) );
}
else if((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) {
final PersistentProperty persistentProperty;
final String propertyName;
if(projection instanceof IdProjection) {
persistentProperty = entity.getIdentity();
propertyName = MongoEntityPersister.MONGO_ID_FIELD;
}
else {
PropertyProjection pp = (PropertyProjection) projection;
persistentProperty = entity.getPropertyByName(pp.getPropertyName());
propertyName = pp.getPropertyName();
}
if(persistentProperty != null) {
List propertyResults = collection.distinct(propertyName, query);
if(persistentProperty instanceof ToOne) {
Association a = (Association) persistentProperty;
propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(), propertyResults);
}
if(projectedResults.size() == 0 && projectionList.size() == 1) {
return propertyResults;
}
else {
projectedResults.add(propertyResults);
}
}
else {
throw new InvalidDataAccessResourceUsageException("Cannot use ["+projection.getClass().getSimpleName()+"] projection on non-existent property: " + propertyName);
}
}
}
return projectedResults;
}
}
}
protected DBCursor executeQuery(final PersistentEntity entity,
final Junction criteria, final DBCollection collection,
DBObject query) {
final DBCursor cursor;
if(criteria.isEmpty()) {
cursor = executeQueryAndApplyPagination(collection, query);
}
else {
populateMongoQuery(entity, query, criteria);
cursor = executeQueryAndApplyPagination(collection,query);
}
return cursor;
}
protected DBCursor executeQueryAndApplyPagination(
final DBCollection collection, DBObject query) {
final DBCursor cursor;
cursor = collection.find(query);
if(offset > 0) {
cursor.skip(offset);
}
if(max > -1) {
cursor.limit(max);
}
for (Order order : orderBy) {
DBObject orderObject = new BasicDBObject();
orderObject.put(order.getProperty(), order.getDirection() == Order.Direction.DESC ? -1 : 1);
cursor.sort(orderObject);
}
return cursor;
}
});
}
| protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
final MongoTemplate template = mongoSession.getMongoTemplate(entity);
return template.execute(new DBCallback<List>() {
@Override
public List doInDB(DB db) throws MongoException,
DataAccessException {
final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
if(uniqueResult) {
final DBObject dbObject;
if(criteria.isEmpty()) {
if(entity.isRoot()) {
dbObject = collection.findOne();
}
else {
DBObject query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD, entity.getDiscriminator());
dbObject = collection.findOne(query);
}
}
else {
DBObject query = getMongoQuery();
dbObject = collection.findOne(query);
}
final Object object = createObjectFromDBObject(dbObject);
return wrapObjectResultInList(object);
}
else {
DBCursor cursor;
DBObject query = createQueryObject(entity);
final List<Projection> projectionList = projections().getProjectionList();
if(projectionList.isEmpty()) {
cursor = executeQuery(entity, criteria, collection, query);
return new MongoResultList(cursor, mongoEntityPersister);
}
else {
List projectedResults = new ArrayList();
for (Projection projection : projectionList) {
if(projection instanceof CountProjection) {
// For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
//projectedResults.add(collection.getCount(query));
cursor = executeQuery(entity, criteria, collection, query);
projectedResults.add(cursor.size());
}
else if(projection instanceof MinProjection) {
cursor = executeQuery(entity, criteria, collection, query);
MinProjection mp = (MinProjection) projection;
MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
projectedResults.add(manualProjections.min((Collection) results.clone(), mp.getPropertyName()));
}
else if(projection instanceof MaxProjection) {
cursor = executeQuery(entity, criteria, collection, query);
MaxProjection mp = (MaxProjection) projection;
MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
projectedResults.add( manualProjections.max((Collection) results.clone(), mp.getPropertyName()) );
}
else if((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) {
final PersistentProperty persistentProperty;
final String propertyName;
if(projection instanceof IdProjection) {
persistentProperty = entity.getIdentity();
propertyName = MongoEntityPersister.MONGO_ID_FIELD;
}
else {
PropertyProjection pp = (PropertyProjection) projection;
persistentProperty = entity.getPropertyByName(pp.getPropertyName());
propertyName = pp.getPropertyName();
}
if(persistentProperty != null) {
populateMongoQuery(entity, query, criteria);
List propertyResults = collection.distinct(propertyName, query);
if(persistentProperty instanceof ToOne) {
Association a = (Association) persistentProperty;
propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(), propertyResults);
}
if(projectedResults.size() == 0 && projectionList.size() == 1) {
return propertyResults;
}
else {
projectedResults.add(propertyResults);
}
}
else {
throw new InvalidDataAccessResourceUsageException("Cannot use ["+projection.getClass().getSimpleName()+"] projection on non-existent property: " + propertyName);
}
}
}
return projectedResults;
}
}
}
protected DBCursor executeQuery(final PersistentEntity entity,
final Junction criteria, final DBCollection collection,
DBObject query) {
final DBCursor cursor;
if(criteria.isEmpty()) {
cursor = executeQueryAndApplyPagination(collection, query);
}
else {
populateMongoQuery(entity, query, criteria);
cursor = executeQueryAndApplyPagination(collection,query);
}
return cursor;
}
protected DBCursor executeQueryAndApplyPagination(
final DBCollection collection, DBObject query) {
final DBCursor cursor;
cursor = collection.find(query);
if(offset > 0) {
cursor.skip(offset);
}
if(max > -1) {
cursor.limit(max);
}
for (Order order : orderBy) {
DBObject orderObject = new BasicDBObject();
orderObject.put(order.getProperty(), order.getDirection() == Order.Direction.DESC ? -1 : 1);
cursor.sort(orderObject);
}
return cursor;
}
});
}
|
diff --git a/java/src/com/android/inputmethod/latin/CandidateView.java b/java/src/com/android/inputmethod/latin/CandidateView.java
index 6fb80adf..11d021cb 100644
--- a/java/src/com/android/inputmethod/latin/CandidateView.java
+++ b/java/src/com/android/inputmethod/latin/CandidateView.java
@@ -1,359 +1,359 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CandidateView extends LinearLayout implements OnClickListener, OnLongClickListener {
private static final CharacterStyle BOLD_SPAN = new StyleSpan(Typeface.BOLD);
private static final CharacterStyle UNDERLINE_SPAN = new UnderlineSpan();
private static final int MAX_SUGGESTIONS = 16;
private static final boolean DBG = LatinImeLogger.sDBG;
private final ArrayList<View> mWords = new ArrayList<View>();
private final boolean mConfigCandidateHighlightFontColorEnabled;
private final CharacterStyle mInvertedForegroundColorSpan;
private final CharacterStyle mInvertedBackgroundColorSpan;
private final int mColorNormal;
private final int mColorRecommended;
private final int mColorOther;
private final PopupWindow mPreviewPopup;
private final TextView mPreviewText;
private LatinIME mService;
private SuggestedWords mSuggestions = SuggestedWords.EMPTY;
private boolean mShowingAutoCorrectionInverted;
private boolean mShowingAddToDictionary;
private final UiHandler mHandler = new UiHandler();
private class UiHandler extends Handler {
private static final int MSG_HIDE_PREVIEW = 0;
private static final int MSG_UPDATE_SUGGESTION = 1;
private static final long DELAY_HIDE_PREVIEW = 1000;
private static final long DELAY_UPDATE_SUGGESTION = 300;
@Override
public void dispatchMessage(Message msg) {
switch (msg.what) {
case MSG_HIDE_PREVIEW:
hidePreview();
break;
case MSG_UPDATE_SUGGESTION:
updateSuggestions();
break;
}
}
public void postHidePreview() {
cancelHidePreview();
sendMessageDelayed(obtainMessage(MSG_HIDE_PREVIEW), DELAY_HIDE_PREVIEW);
}
public void cancelHidePreview() {
removeMessages(MSG_HIDE_PREVIEW);
}
public void postUpdateSuggestions() {
cancelUpdateSuggestions();
sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION),
DELAY_UPDATE_SUGGESTION);
}
public void cancelUpdateSuggestions() {
removeMessages(MSG_UPDATE_SUGGESTION);
}
public void cancelAllMessages() {
cancelHidePreview();
cancelUpdateSuggestions();
}
}
/**
* Construct a CandidateView for showing suggested words for completion.
* @param context
* @param attrs
*/
public CandidateView(Context context, AttributeSet attrs) {
super(context, attrs);
Resources res = context.getResources();
mPreviewPopup = new PopupWindow(context);
LayoutInflater inflater = LayoutInflater.from(context);
mPreviewText = (TextView) inflater.inflate(R.layout.candidate_preview, null);
mPreviewPopup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
mConfigCandidateHighlightFontColorEnabled =
res.getBoolean(R.bool.config_candidate_highlight_font_color_enabled);
mColorNormal = res.getColor(R.color.candidate_normal);
mColorRecommended = res.getColor(R.color.candidate_recommended);
mColorOther = res.getColor(R.color.candidate_other);
mInvertedForegroundColorSpan = new ForegroundColorSpan(mColorNormal ^ 0x00ffffff);
mInvertedBackgroundColorSpan = new BackgroundColorSpan(mColorNormal);
for (int i = 0; i < MAX_SUGGESTIONS; i++) {
View v = inflater.inflate(R.layout.candidate, null);
TextView tv = (TextView)v.findViewById(R.id.candidate_word);
tv.setTag(i);
tv.setOnClickListener(this);
if (i == 0)
tv.setOnLongClickListener(this);
ImageView divider = (ImageView)v.findViewById(R.id.candidate_divider);
// Do not display divider of first candidate.
divider.setVisibility(i == 0 ? GONE : VISIBLE);
mWords.add(v);
}
scrollTo(0, getScrollY());
}
/**
* A connection back to the service to communicate with the text field
* @param listener
*/
public void setService(LatinIME listener) {
mService = listener;
}
public void setSuggestions(SuggestedWords suggestions) {
if (suggestions == null)
return;
mSuggestions = suggestions;
if (mShowingAutoCorrectionInverted) {
mHandler.postUpdateSuggestions();
} else {
updateSuggestions();
}
}
private void updateSuggestions() {
final SuggestedWords suggestions = mSuggestions;
clear();
- final int count = suggestions.size();
+ final int count = Math.min(mWords.size(), suggestions.size());
for (int i = 0; i < count; i++) {
CharSequence word = suggestions.getWord(i);
if (word == null) continue;
final int wordLength = word.length();
final List<SuggestedWordInfo> suggestedWordInfoList =
suggestions.mSuggestedWordInfoList;
final View v = mWords.get(i);
final TextView tv = (TextView)v.findViewById(R.id.candidate_word);
final TextView dv = (TextView)v.findViewById(R.id.candidate_debug_info);
tv.setTextColor(mColorNormal);
// TODO: Needs safety net?
if (suggestions.mHasMinimalSuggestion
&& ((i == 1 && !suggestions.mTypedWordValid)
|| (i == 0 && suggestions.mTypedWordValid))) {
final CharacterStyle style;
if (mConfigCandidateHighlightFontColorEnabled) {
style = BOLD_SPAN;
tv.setTextColor(mColorRecommended);
} else {
style = UNDERLINE_SPAN;
}
final Spannable spannedWord = new SpannableString(word);
spannedWord.setSpan(style, 0, wordLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
word = spannedWord;
} else if (i != 0 || (wordLength == 1 && count > 1)) {
// HACK: even if i == 0, we use mColorOther when this
// suggestion's length is 1
// and there are multiple suggestions, such as the default
// punctuation list.
if (mConfigCandidateHighlightFontColorEnabled)
tv.setTextColor(mColorOther);
}
tv.setText(word);
tv.setClickable(true);
if (suggestedWordInfoList != null && suggestedWordInfoList.get(i) != null) {
final SuggestedWordInfo info = suggestedWordInfoList.get(i);
if (info.isPreviousSuggestedWord()) {
int color = tv.getCurrentTextColor();
tv.setTextColor(Color.argb((int)(Color.alpha(color) * 0.5f), Color.red(color),
Color.green(color), Color.blue(color)));
}
final String debugString = info.getDebugString();
if (DBG) {
if (TextUtils.isEmpty(debugString)) {
dv.setVisibility(GONE);
} else {
dv.setText(debugString);
dv.setVisibility(VISIBLE);
}
} else {
dv.setVisibility(GONE);
}
} else {
dv.setVisibility(GONE);
}
addView(v);
}
scrollTo(0, getScrollY());
requestLayout();
}
public void onAutoCorrectionInverted(CharSequence autoCorrectedWord) {
// Displaying auto corrected word as inverted is enabled only when highlighting candidate
// with color is disabled.
if (mConfigCandidateHighlightFontColorEnabled)
return;
final TextView tv = (TextView)mWords.get(1).findViewById(R.id.candidate_word);
final Spannable word = new SpannableString(autoCorrectedWord);
final int wordLength = word.length();
word.setSpan(mInvertedBackgroundColorSpan, 0, wordLength,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
word.setSpan(mInvertedForegroundColorSpan, 0, wordLength,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.setText(word);
mShowingAutoCorrectionInverted = true;
}
public boolean isConfigCandidateHighlightFontColorEnabled() {
return mConfigCandidateHighlightFontColorEnabled;
}
public boolean isShowingAddToDictionaryHint() {
return mShowingAddToDictionary;
}
public void showAddToDictionaryHint(CharSequence word) {
SuggestedWords.Builder builder = new SuggestedWords.Builder()
.addWord(word)
.addWord(getContext().getText(R.string.hint_add_to_dictionary));
setSuggestions(builder.build());
mShowingAddToDictionary = true;
// Disable R.string.hint_add_to_dictionary button
TextView tv = (TextView)getChildAt(1).findViewById(R.id.candidate_word);
tv.setClickable(false);
}
public boolean dismissAddToDictionaryHint() {
if (!mShowingAddToDictionary) return false;
clear();
return true;
}
public SuggestedWords getSuggestions() {
return mSuggestions;
}
public void clear() {
mShowingAddToDictionary = false;
mShowingAutoCorrectionInverted = false;
removeAllViews();
}
private void hidePreview() {
mPreviewPopup.dismiss();
}
private void showPreview(int index, CharSequence word) {
if (TextUtils.isEmpty(word))
return;
final TextView previewText = mPreviewText;
previewText.setTextColor(mColorNormal);
previewText.setText(word);
previewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
View v = getChildAt(index);
final int[] offsetInWindow = new int[2];
v.getLocationInWindow(offsetInWindow);
final int posX = offsetInWindow[0];
final int posY = offsetInWindow[1] - previewText.getMeasuredHeight();
final PopupWindow previewPopup = mPreviewPopup;
if (previewPopup.isShowing()) {
previewPopup.update(posX, posY, previewPopup.getWidth(), previewPopup.getHeight());
} else {
previewPopup.showAtLocation(this, Gravity.NO_GRAVITY, posX, posY);
}
previewText.setVisibility(VISIBLE);
mHandler.postHidePreview();
}
private void addToDictionary(CharSequence word) {
if (mService.addWordToDictionary(word.toString())) {
showPreview(0, getContext().getString(R.string.added_word, word));
}
}
@Override
public boolean onLongClick(View view) {
int index = (Integer) view.getTag();
CharSequence word = mSuggestions.getWord(index);
if (word.length() < 2)
return false;
addToDictionary(word);
return true;
}
@Override
public void onClick(View view) {
int index = (Integer) view.getTag();
CharSequence word = mSuggestions.getWord(index);
if (mShowingAddToDictionary && index == 0) {
addToDictionary(word);
} else {
mService.pickSuggestionManually(index, word);
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.cancelAllMessages();
hidePreview();
}
}
| true | true | private void updateSuggestions() {
final SuggestedWords suggestions = mSuggestions;
clear();
final int count = suggestions.size();
for (int i = 0; i < count; i++) {
CharSequence word = suggestions.getWord(i);
if (word == null) continue;
final int wordLength = word.length();
final List<SuggestedWordInfo> suggestedWordInfoList =
suggestions.mSuggestedWordInfoList;
final View v = mWords.get(i);
final TextView tv = (TextView)v.findViewById(R.id.candidate_word);
final TextView dv = (TextView)v.findViewById(R.id.candidate_debug_info);
tv.setTextColor(mColorNormal);
// TODO: Needs safety net?
if (suggestions.mHasMinimalSuggestion
&& ((i == 1 && !suggestions.mTypedWordValid)
|| (i == 0 && suggestions.mTypedWordValid))) {
final CharacterStyle style;
if (mConfigCandidateHighlightFontColorEnabled) {
style = BOLD_SPAN;
tv.setTextColor(mColorRecommended);
} else {
style = UNDERLINE_SPAN;
}
final Spannable spannedWord = new SpannableString(word);
spannedWord.setSpan(style, 0, wordLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
word = spannedWord;
} else if (i != 0 || (wordLength == 1 && count > 1)) {
// HACK: even if i == 0, we use mColorOther when this
// suggestion's length is 1
// and there are multiple suggestions, such as the default
// punctuation list.
if (mConfigCandidateHighlightFontColorEnabled)
tv.setTextColor(mColorOther);
}
tv.setText(word);
tv.setClickable(true);
if (suggestedWordInfoList != null && suggestedWordInfoList.get(i) != null) {
final SuggestedWordInfo info = suggestedWordInfoList.get(i);
if (info.isPreviousSuggestedWord()) {
int color = tv.getCurrentTextColor();
tv.setTextColor(Color.argb((int)(Color.alpha(color) * 0.5f), Color.red(color),
Color.green(color), Color.blue(color)));
}
final String debugString = info.getDebugString();
if (DBG) {
if (TextUtils.isEmpty(debugString)) {
dv.setVisibility(GONE);
} else {
dv.setText(debugString);
dv.setVisibility(VISIBLE);
}
} else {
dv.setVisibility(GONE);
}
} else {
dv.setVisibility(GONE);
}
addView(v);
}
scrollTo(0, getScrollY());
requestLayout();
}
| private void updateSuggestions() {
final SuggestedWords suggestions = mSuggestions;
clear();
final int count = Math.min(mWords.size(), suggestions.size());
for (int i = 0; i < count; i++) {
CharSequence word = suggestions.getWord(i);
if (word == null) continue;
final int wordLength = word.length();
final List<SuggestedWordInfo> suggestedWordInfoList =
suggestions.mSuggestedWordInfoList;
final View v = mWords.get(i);
final TextView tv = (TextView)v.findViewById(R.id.candidate_word);
final TextView dv = (TextView)v.findViewById(R.id.candidate_debug_info);
tv.setTextColor(mColorNormal);
// TODO: Needs safety net?
if (suggestions.mHasMinimalSuggestion
&& ((i == 1 && !suggestions.mTypedWordValid)
|| (i == 0 && suggestions.mTypedWordValid))) {
final CharacterStyle style;
if (mConfigCandidateHighlightFontColorEnabled) {
style = BOLD_SPAN;
tv.setTextColor(mColorRecommended);
} else {
style = UNDERLINE_SPAN;
}
final Spannable spannedWord = new SpannableString(word);
spannedWord.setSpan(style, 0, wordLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
word = spannedWord;
} else if (i != 0 || (wordLength == 1 && count > 1)) {
// HACK: even if i == 0, we use mColorOther when this
// suggestion's length is 1
// and there are multiple suggestions, such as the default
// punctuation list.
if (mConfigCandidateHighlightFontColorEnabled)
tv.setTextColor(mColorOther);
}
tv.setText(word);
tv.setClickable(true);
if (suggestedWordInfoList != null && suggestedWordInfoList.get(i) != null) {
final SuggestedWordInfo info = suggestedWordInfoList.get(i);
if (info.isPreviousSuggestedWord()) {
int color = tv.getCurrentTextColor();
tv.setTextColor(Color.argb((int)(Color.alpha(color) * 0.5f), Color.red(color),
Color.green(color), Color.blue(color)));
}
final String debugString = info.getDebugString();
if (DBG) {
if (TextUtils.isEmpty(debugString)) {
dv.setVisibility(GONE);
} else {
dv.setText(debugString);
dv.setVisibility(VISIBLE);
}
} else {
dv.setVisibility(GONE);
}
} else {
dv.setVisibility(GONE);
}
addView(v);
}
scrollTo(0, getScrollY());
requestLayout();
}
|
diff --git a/src/icd3/CyclicDate.java b/src/icd3/CyclicDate.java
index 1a2098f..74d273e 100755
--- a/src/icd3/CyclicDate.java
+++ b/src/icd3/CyclicDate.java
@@ -1,79 +1,79 @@
/**
*
*/
package icd3;
/**
* A date representation that repeats in a regular modular cycle
*/
public abstract class CyclicDate<T extends CyclicDate<T>> implements MayanDate<T>
{
/**
* The integer representation of this date
*/
private int m_value;
/**
* Instantiates a new cyclic date.
*
* @param value The integer value corresponding to this cyclic date's equivalence class
*/
public CyclicDate(int value)
{
int cycle = this.cycle();
// Ensure that value is within the positive equivalence class (mod cycle)
m_value = (value % cycle + cycle) % cycle;
}
/**
* Give the number of date representations possible in this date type.
*
* @return The number of equivalence classes represented by this cyclic date.
*/
public abstract int cycle();
/*
* (non-Javadoc)
*
* @see icd3.MayanDate#minus(java.lang.Object)
*/
@Override
public int minus(T other)
{
if (null == other)
{
- throw new NullPointerException("Cannot subtract a null Haab Date");
+ throw new NullPointerException("Cannot subtract a null MayanDate");
}
// Subtract the integer representations
int difference = this.toInt() - other.toInt();
int cycle = this.cycle();
// Ensure that difference is within the positive equivalence class (mod cycle)
return (difference % cycle + cycle) % cycle;
}
/*
* (non-Javadoc)
*
* @see icd3.MayanDate#toInt()
*/
@Override
public int toInt()
{
return m_value;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o)
{
// Must be non-null, also a HaabDate, and have the same integer representation
return o != null && this.getClass().equals(o.getClass()) && this.toInt() == ((CyclicDate<?>) o).toInt();
}
}
| true | true | public int minus(T other)
{
if (null == other)
{
throw new NullPointerException("Cannot subtract a null Haab Date");
}
// Subtract the integer representations
int difference = this.toInt() - other.toInt();
int cycle = this.cycle();
// Ensure that difference is within the positive equivalence class (mod cycle)
return (difference % cycle + cycle) % cycle;
}
| public int minus(T other)
{
if (null == other)
{
throw new NullPointerException("Cannot subtract a null MayanDate");
}
// Subtract the integer representations
int difference = this.toInt() - other.toInt();
int cycle = this.cycle();
// Ensure that difference is within the positive equivalence class (mod cycle)
return (difference % cycle + cycle) % cycle;
}
|
diff --git a/src/main/java/org/apache/maven/plugin/pmd/CpdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugin/pmd/CpdViolationCheckMojo.java
index 6a37472..5a9410b 100644
--- a/src/main/java/org/apache/maven/plugin/pmd/CpdViolationCheckMojo.java
+++ b/src/main/java/org/apache/maven/plugin/pmd/CpdViolationCheckMojo.java
@@ -1,140 +1,138 @@
package org.apache.maven.plugin.pmd;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.xml.pull.XmlPullParser;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
/**
* Fail the build if there were any CPD violations in the source code.
*
* @since 2.0
* @version $Id$
* @goal cpd-check
* @phase verify
* @execute goal="cpd"
* @threadSafe
*/
public class CpdViolationCheckMojo
extends AbstractPmdViolationCheckMojo
{
/**
* Skip the CPD violation checks. Most useful on the command line
* via "-Dcpd.skip=true".
*
* @parameter expression="${cpd.skip}" default-value="false"
*/
private boolean skip;
/** {@inheritDoc} */
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( !skip )
{
executeCheck( "cpd.xml", "duplication", "CPD duplication", 10 );
}
}
/** {@inheritDoc} */
protected void printError( Map item, String severity )
{
String lines = (String) item.get( "lines" );
StringBuffer buff = new StringBuffer( 100 );
buff.append( "CPD " + severity + ": Found " );
buff.append( lines ).append( " lines of duplicated code at locations:" );
this.getLog().info( buff.toString() );
buff.setLength( 0 );
buff.append( " " );
Map file = (Map) item.get( "file" );
buff.append( file.get( "path" ) );
buff.append( " line " ).append( file.get( "line" ) );
this.getLog().info( buff.toString() );
buff.setLength( 0 );
buff.append( " " );
file = (Map) item.get( "file1" );
buff.append( file.get( "path" ) );
buff.append( " line " ).append( file.get( "line" ) );
this.getLog().info( buff.toString() );
Map codefrag = (Map) item.get( "codefragment" );
String codefragstr = (String) codefrag.get( "text" );
this.getLog().debug( "CPD " + severity + ": Code Fragment " );
this.getLog().debug( codefragstr );
}
/** {@inheritDoc} */
protected Map getErrorDetails( XmlPullParser xpp )
throws XmlPullParserException, IOException
{
int index = 0;
int attributeCount = 0;
HashMap msgs = new HashMap();
attributeCount = xpp.getAttributeCount();
while ( index < attributeCount )
{
msgs.put( xpp.getAttributeName( index ), xpp.getAttributeValue( index ) );
index++;
}
int tp = xpp.next();
while ( tp != XmlPullParser.END_TAG )
{
// get the tag's text
switch ( tp )
{
case XmlPullParser.TEXT:
msgs.put( "text", xpp.getText().trim() );
break;
case XmlPullParser.START_TAG:
+ String nm = xpp.getName();
+ if ( msgs.containsKey( nm ) )
{
- String nm = xpp.getName();
- if ( msgs.containsKey( nm ) )
+ int cnt = 1;
+ while ( msgs.containsKey( nm + cnt ) )
{
- int cnt = 1;
- while ( msgs.containsKey( nm + cnt ) )
- {
- ++cnt;
- }
- nm = nm + cnt;
+ ++cnt;
}
- msgs.put( nm, getErrorDetails( xpp ) );
- break;
+ nm = nm + cnt;
}
+ msgs.put( nm, getErrorDetails( xpp ) );
+ break;
default:
}
tp = xpp.next();
}
return msgs;
}
}
| false | true | protected Map getErrorDetails( XmlPullParser xpp )
throws XmlPullParserException, IOException
{
int index = 0;
int attributeCount = 0;
HashMap msgs = new HashMap();
attributeCount = xpp.getAttributeCount();
while ( index < attributeCount )
{
msgs.put( xpp.getAttributeName( index ), xpp.getAttributeValue( index ) );
index++;
}
int tp = xpp.next();
while ( tp != XmlPullParser.END_TAG )
{
// get the tag's text
switch ( tp )
{
case XmlPullParser.TEXT:
msgs.put( "text", xpp.getText().trim() );
break;
case XmlPullParser.START_TAG:
{
String nm = xpp.getName();
if ( msgs.containsKey( nm ) )
{
int cnt = 1;
while ( msgs.containsKey( nm + cnt ) )
{
++cnt;
}
nm = nm + cnt;
}
msgs.put( nm, getErrorDetails( xpp ) );
break;
}
default:
}
tp = xpp.next();
}
return msgs;
}
| protected Map getErrorDetails( XmlPullParser xpp )
throws XmlPullParserException, IOException
{
int index = 0;
int attributeCount = 0;
HashMap msgs = new HashMap();
attributeCount = xpp.getAttributeCount();
while ( index < attributeCount )
{
msgs.put( xpp.getAttributeName( index ), xpp.getAttributeValue( index ) );
index++;
}
int tp = xpp.next();
while ( tp != XmlPullParser.END_TAG )
{
// get the tag's text
switch ( tp )
{
case XmlPullParser.TEXT:
msgs.put( "text", xpp.getText().trim() );
break;
case XmlPullParser.START_TAG:
String nm = xpp.getName();
if ( msgs.containsKey( nm ) )
{
int cnt = 1;
while ( msgs.containsKey( nm + cnt ) )
{
++cnt;
}
nm = nm + cnt;
}
msgs.put( nm, getErrorDetails( xpp ) );
break;
default:
}
tp = xpp.next();
}
return msgs;
}
|
diff --git a/org/python/modules/cPickle.java b/org/python/modules/cPickle.java
index 145dcf72..0fe1273c 100644
--- a/org/python/modules/cPickle.java
+++ b/org/python/modules/cPickle.java
@@ -1,2075 +1,2075 @@
/*
* Copyright 1998 Finn Bock.
*
* This program contains material copyrighted by:
* Copyright � 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
* The Netherlands.
*/
/* note about impl:
instanceof vs. CPython type(.) is .
*/
package org.python.modules;
import java.util.*;
import org.python.core.*;
import org.python.core.imp;
/**
*
* From the python documentation:
* <p>
* The <tt>cPickle.java</tt> module implements a basic but powerful algorithm
* for ``pickling'' (a.k.a. serializing, marshalling or flattening) nearly
* arbitrary Python objects. This is the act of converting objects to a
* stream of bytes (and back: ``unpickling'').
* This is a more primitive notion than
* persistency -- although <tt>cPickle.java</tt> reads and writes file
* objects, it does not handle the issue of naming persistent objects, nor
* the (even more complicated) area of concurrent access to persistent
* objects. The <tt>cPickle.java</tt> module can transform a complex object
* into a byte stream and it can transform the byte stream into an object
* with the same internal structure. The most obvious thing to do with these
* byte streams is to write them onto a file, but it is also conceivable
* to send them across a network or store them in a database. The module
* <tt>shelve</tt> provides a simple interface to pickle and unpickle
* objects on ``dbm''-style database files.
* <P>
* <b>Note:</b> The <tt>cPickle.java</tt> have the same interface as the
* standard module <tt>pickle</tt>except that <tt>Pickler</tt> and
* <tt>Unpickler</tt> are factory functions, not classes (so they cannot be
* used as base classes for inheritance).
* This limitation is similar for the original cPickle.c version.
*
* <P>
* Unlike the built-in module <tt>marshal</tt>, <tt>cPickle.java</tt> handles
* the following correctly:
* <P>
*
* <UL><LI>recursive objects (objects containing references to themselves)
*
* <P>
*
* <LI>object sharing (references to the same object in different places)
*
* <P>
*
* <LI>user-defined classes and their instances
*
* <P>
*
* </UL>
*
* <P>
* The data format used by <tt>cPickle.java</tt> is Python-specific. This has
* the advantage that there are no restrictions imposed by external
* standards such as XDR (which can't represent pointer sharing); however
* it means that non-Python programs may not be able to reconstruct
* pickled Python objects.
*
* <P>
* By default, the <tt>cPickle.java</tt> data format uses a printable ASCII
* representation. This is slightly more voluminous than a binary
* representation. The big advantage of using printable ASCII (and of
* some other characteristics of <tt>cPickle.java</tt>'s representation) is
* that for debugging or recovery purposes it is possible for a human to read
* the pickled file with a standard text editor.
*
* <P>
* A binary format, which is slightly more efficient, can be chosen by
* specifying a nonzero (true) value for the <i>bin</i> argument to the
* <tt>Pickler</tt> constructor or the <tt>dump()</tt> and <tt>dumps()</tt>
* functions. The binary format is not the default because of backwards
* compatibility with the Python 1.4 pickle module. In a future version,
* the default may change to binary.
*
* <P>
* The <tt>cPickle.java</tt> module doesn't handle code objects.
* <P>
* For the benefit of persistency modules written using <tt>cPickle.java</tt>,
* it supports the notion of a reference to an object outside the pickled
* data stream. Such objects are referenced by a name, which is an
* arbitrary string of printable ASCII characters. The resolution of
* such names is not defined by the <tt>cPickle.java</tt> module -- the
* persistent object module will have to implement a method
* <tt>persistent_load()</tt>. To write references to persistent objects,
* the persistent module must define a method <tt>persistent_id()</tt> which
* returns either <tt>None</tt> or the persistent ID of the object.
*
* <P>
* There are some restrictions on the pickling of class instances.
*
* <P>
* First of all, the class must be defined at the top level in a module.
* Furthermore, all its instance variables must be picklable.
*
* <P>
*
* <P>
* When a pickled class instance is unpickled, its <tt>__init__()</tt> method
* is normally <i>not</i> invoked. <b>Note:</b> This is a deviation
* from previous versions of this module; the change was introduced in
* Python 1.5b2. The reason for the change is that in many cases it is
* desirable to have a constructor that requires arguments; it is a
* (minor) nuisance to have to provide a <tt>__getinitargs__()</tt> method.
*
* <P>
* If it is desirable that the <tt>__init__()</tt> method be called on
* unpickling, a class can define a method <tt>__getinitargs__()</tt>,
* which should return a <i>tuple</i> containing the arguments to be
* passed to the class constructor (<tt>__init__()</tt>). This method is
* called at pickle time; the tuple it returns is incorporated in the
* pickle for the instance.
* <P>
* Classes can further influence how their instances are pickled -- if the
* class defines the method <tt>__getstate__()</tt>, it is called and the
* return state is pickled as the contents for the instance, and if the class
* defines the method <tt>__setstate__()</tt>, it is called with the
* unpickled state. (Note that these methods can also be used to
* implement copying class instances.) If there is no
* <tt>__getstate__()</tt> method, the instance's <tt>__dict__</tt> is
* pickled. If there is no <tt>__setstate__()</tt> method, the pickled
* object must be a dictionary and its items are assigned to the new
* instance's dictionary. (If a class defines both <tt>__getstate__()</tt>
* and <tt>__setstate__()</tt>, the state object needn't be a dictionary
* -- these methods can do what they want.) This protocol is also used
* by the shallow and deep copying operations defined in the <tt>copy</tt>
* module.
* <P>
* Note that when class instances are pickled, their class's code and
* data are not pickled along with them. Only the instance data are
* pickled. This is done on purpose, so you can fix bugs in a class or
* add methods and still load objects that were created with an earlier
* version of the class. If you plan to have long-lived objects that
* will see many versions of a class, it may be worthwhile to put a version
* number in the objects so that suitable conversions can be made by the
* class's <tt>__setstate__()</tt> method.
*
* <P>
* When a class itself is pickled, only its name is pickled -- the class
* definition is not pickled, but re-imported by the unpickling process.
* Therefore, the restriction that the class must be defined at the top
* level in a module applies to pickled classes as well.
*
* <P>
*
* <P>
* The interface can be summarized as follows.
*
* <P>
* To pickle an object <tt>x</tt> onto a file <tt>f</tt>, open for writing:
*
* <P>
* <dl><dd><pre>
* p = pickle.Pickler(f)
* p.dump(x)
* </pre></dl>
*
* <P>
* A shorthand for this is:
*
* <P>
* <dl><dd><pre>
* pickle.dump(x, f)
* </pre></dl>
*
* <P>
* To unpickle an object <tt>x</tt> from a file <tt>f</tt>, open for reading:
*
* <P>
* <dl><dd><pre>
* u = pickle.Unpickler(f)
* x = u.load()
* </pre></dl>
*
* <P>
* A shorthand is:
*
* <P>
* <dl><dd><pre>
* x = pickle.load(f)
* </pre></dl>
*
* <P>
* The <tt>Pickler</tt> class only calls the method <tt>f.write()</tt> with a
* string argument. The <tt>Unpickler</tt> calls the methods
* <tt>f.read()</tt> (with an integer argument) and <tt>f.readline()</tt>
* (without argument), both returning a string. It is explicitly allowed to
* pass non-file objects here, as long as they have the right methods.
*
* <P>
* The constructor for the <tt>Pickler</tt> class has an optional second
* argument, <i>bin</i>. If this is present and nonzero, the binary
* pickle format is used; if it is zero or absent, the (less efficient,
* but backwards compatible) text pickle format is used. The
* <tt>Unpickler</tt> class does not have an argument to distinguish
* between binary and text pickle formats; it accepts either format.
*
* <P>
* The following types can be pickled:
*
* <UL><LI><tt>None</tt>
*
* <P>
*
* <LI>integers, long integers, floating point numbers
*
* <P>
*
* <LI>strings
*
* <P>
*
* <LI>tuples, lists and dictionaries containing only picklable objects
*
* <P>
*
* <LI>classes that are defined at the top level in a module
*
* <P>
*
* <LI>instances of such classes whose <tt>__dict__</tt> or
* <tt>__setstate__()</tt> is picklable
*
* <P>
*
* </UL>
*
* <P>
* Attempts to pickle unpicklable objects will raise the
* <tt>PicklingError</tt> exception; when this happens, an unspecified
* number of bytes may have been written to the file.
*
* <P>
* It is possible to make multiple calls to the <tt>dump()</tt> method of
* the same <tt>Pickler</tt> instance. These must then be matched to the
* same number of calls to the <tt>load()</tt> method of the
* corresponding <tt>Unpickler</tt> instance. If the same object is
* pickled by multiple <tt>dump()</tt> calls, the <tt>load()</tt> will all
* yield references to the same object. <i>Warning</i>: this is intended
* for pickling multiple objects without intervening modifications to the
* objects or their parts. If you modify an object and then pickle it
* again using the same <tt>Pickler</tt> instance, the object is not
* pickled again -- a reference to it is pickled and the
* <tt>Unpickler</tt> will return the old value, not the modified one.
* (There are two problems here: (a) detecting changes, and (b)
* marshalling a minimal set of changes. I have no answers. Garbage
* Collection may also become a problem here.)
*
* <P>
* Apart from the <tt>Pickler</tt> and <tt>Unpickler</tt> classes, the
* module defines the following functions, and an exception:
*
* <P>
* <dl><dt><b><tt>dump</tt></a></b> (<var>object, file</var><big>[</big><var>,
* bin</var><big>]</big>)
* <dd>
* Write a pickled representation of <i>obect</i> to the open file object
* <i>file</i>. This is equivalent to
* "<tt>Pickler(<i>file</i>, <i>bin</i>).dump(<i>object</i>)</tt>".
* If the optional <i>bin</i> argument is present and nonzero, the binary
* pickle format is used; if it is zero or absent, the (less efficient)
* text pickle format is used.
* </dl>
*
* <P>
* <dl><dt><b><tt>load</tt></a></b> (<var>file</var>)
* <dd>
* Read a pickled object from the open file object <i>file</i>. This is
* equivalent to "<tt>Unpickler(<i>file</i>).load()</tt>".
* </dl>
*
* <P>
* <dl><dt><b><tt>dumps</tt></a></b> (<var>object</var><big>[</big><var>,
* bin</var><big>]</big>)
* <dd>
* Return the pickled representation of the object as a string, instead
* of writing it to a file. If the optional <i>bin</i> argument is
* present and nonzero, the binary pickle format is used; if it is zero
* or absent, the (less efficient) text pickle format is used.
* </dl>
*
* <P>
* <dl><dt><b><tt>loads</tt></a></b> (<var>string</var>)
* <dd>
* Read a pickled object from a string instead of a file. Characters in
* the string past the pickled object's representation are ignored.
* </dl>
*
* <P>
* <dl><dt><b><a name="l2h-3763"><tt>PicklingError</tt></a></b>
* <dd>
* This exception is raised when an unpicklable object is passed to
* <tt>Pickler.dump()</tt>.
* </dl>
*
*
* <p>
* For the complete documentation on the pickle module, please see the
* "Python Library Reference"
* <p><hr><p>
*
* The module is based on both original pickle.py and the cPickle.c
* version, except that all mistakes and errors are my own.
* <p>
* @author Finn Bock, [email protected]
* @version cPickle.java,v 1.30 1999/05/15 17:40:12 fb Exp
*/
public class cPickle implements ClassDictInit {
/**
* The doc string
*/
public static String __doc__ =
"Java implementation and optimization of the Python pickle module\n" +
"\n" +
"$Id$\n";
/**
* The program version.
*/
public static String __version__ = "1.30";
/**
* File format version we write.
*/
public static final String format_version = "1.3";
/**
* Old format versions we can read.
*/
public static final String[] compatible_formats =
new String[] { "1.0", "1.1", "1.2" };
public static String[] __depends__ = new String[] {
"copy_reg",
};
public static PyObject PickleError;
public static PyObject PicklingError;
public static PyObject UnpickleableError;
public static PyObject UnpicklingError;
public static final PyString BadPickleGet =
new PyString("cPickle.BadPickleGet");
final static char MARK = '(';
final static char STOP = '.';
final static char POP = '0';
final static char POP_MARK = '1';
final static char DUP = '2';
final static char FLOAT = 'F';
final static char INT = 'I';
final static char BININT = 'J';
final static char BININT1 = 'K';
final static char LONG = 'L';
final static char BININT2 = 'M';
final static char NONE = 'N';
final static char PERSID = 'P';
final static char BINPERSID = 'Q';
final static char REDUCE = 'R';
final static char STRING = 'S';
final static char BINSTRING = 'T';
final static char SHORT_BINSTRING = 'U';
final static char UNICODE = 'V';
final static char BINUNICODE = 'X';
final static char APPEND = 'a';
final static char BUILD = 'b';
final static char GLOBAL = 'c';
final static char DICT = 'd';
final static char EMPTY_DICT = '}';
final static char APPENDS = 'e';
final static char GET = 'g';
final static char BINGET = 'h';
final static char INST = 'i';
final static char LONG_BINGET = 'j';
final static char LIST = 'l';
final static char EMPTY_LIST = ']';
final static char OBJ = 'o';
final static char PUT = 'p';
final static char BINPUT = 'q';
final static char LONG_BINPUT = 'r';
final static char SETITEM = 's';
final static char TUPLE = 't';
final static char EMPTY_TUPLE = ')';
final static char SETITEMS = 'u';
final static char BINFLOAT = 'G';
private static PyDictionary dispatch_table = null;
private static PyDictionary safe_constructors = null;
private static PyClass BuiltinFunctionType =
PyJavaClass.lookup(PyReflectedFunction.class);
private static PyClass BuiltinMethodType =
PyJavaClass.lookup(PyMethod.class);
private static PyClass ClassType =
PyJavaClass.lookup(PyClass.class);
private static PyClass DictionaryType =
PyJavaClass.lookup(PyDictionary.class);
private static PyClass StringMapType =
PyJavaClass.lookup(PyStringMap.class);
private static PyClass FloatType =
PyJavaClass.lookup(PyFloat.class);
private static PyClass FunctionType =
PyJavaClass.lookup(PyFunction.class);
private static PyClass InstanceType =
PyJavaClass.lookup(PyInstance.class);
private static PyClass IntType =
PyJavaClass.lookup(PyInteger.class);
private static PyClass ListType =
PyJavaClass.lookup(PyList.class);
private static PyClass LongType =
PyJavaClass.lookup(PyLong.class);
private static PyClass NoneType =
PyJavaClass.lookup(PyNone.class);
private static PyClass StringType =
PyJavaClass.lookup(PyString.class);
private static PyClass TupleType =
PyJavaClass.lookup(PyTuple.class);
private static PyClass FileType =
PyJavaClass.lookup(PyFile.class);
private static PyObject dict;
/**
* Initialization when module is imported.
*/
public static void classDictInit(PyObject dict) {
cPickle.dict = dict;
// XXX: Hack for JPython 1.0.1. By default __builtin__ is not in
// sys.modules.
imp.importName("__builtin__", true);
PyModule copyreg = (PyModule)importModule("copy_reg");
dispatch_table = (PyDictionary)copyreg.__getattr__("dispatch_table");
safe_constructors = (PyDictionary)
copyreg.__getattr__("safe_constructors");
PickleError = buildClass("PickleError", Py.Exception,
"_PickleError", "");
PicklingError = buildClass("PicklingError", PickleError,
"_empty__init__", "");
UnpickleableError = buildClass("UnpickleableError", PicklingError,
"_UnpickleableError", "");
UnpicklingError = buildClass("UnpicklingError", PickleError,
"_empty__init__", "");
}
// An empty __init__ method
public static PyObject _empty__init__(PyObject[] arg, String[] kws) {
PyObject dict = new PyStringMap();
dict.__setitem__("__module__", new PyString("cPickle"));
return dict;
}
public static PyObject _PickleError(PyObject[] arg, String[] kws) {
PyObject dict = _empty__init__(arg, kws);
dict.__setitem__("__init__", getJavaFunc("_PickleError__init__"));
dict.__setitem__("__str__", getJavaFunc("_PickleError__str__"));
return dict;
}
public static void _PickleError__init__(PyObject[] arg, String[] kws) {
ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
PyObject self = ap.getPyObject(0);
PyObject args = ap.getList(1);
self.__setattr__("args", args);
}
public static PyString _PickleError__str__(PyObject[] arg, String[] kws) {
ArgParser ap = new ArgParser("__str__", arg, kws, "self");
PyObject self = ap.getPyObject(0);
PyObject args = self.__getattr__("args");
if (args.__len__() > 0 && args.__getitem__(0).__len__() > 0)
return args.__getitem__(0).__str__();
else
return new PyString("(what)");
}
public static PyObject _UnpickleableError(PyObject[] arg, String[] kws) {
PyObject dict = _empty__init__(arg, kws);
dict.__setitem__("__init__", getJavaFunc("_UnpickleableError__init__"));
dict.__setitem__("__str__", getJavaFunc("_UnpickleableError__str__"));
return dict;
}
public static void _UnpickleableError__init__(PyObject[] arg, String[] kws) {
ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
PyObject self = ap.getPyObject(0);
PyObject args = ap.getList(1);
self.__setattr__("args", args);
}
public static PyString _UnpickleableError__str__(PyObject[] arg, String[] kws) {
ArgParser ap = new ArgParser("__str__", arg, kws, "self");
PyObject self = ap.getPyObject(0);
PyObject args = self.__getattr__("args");
PyObject a = args.__len__() > 0 ? args.__getitem__(0) :
new PyString("(what)");
return new PyString("Cannot pickle %s objects").__mod__(a).__str__();
}
public cPickle() {
}
/**
* Returns a pickler instance.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method. The data will be written as text.
* @returns a new Pickler instance.
*/
public static Pickler Pickler(PyObject file) {
return new Pickler(file, false);
}
/**
* Returns a pickler instance.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method.
* @param bin when true, the output will be written as binary data.
* @returns a new Pickler instance.
*/
public static Pickler Pickler(PyObject file, boolean bin) {
return new Pickler(file, bin);
}
/**
* Returns a unpickler instance.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>read</i> and <i>readline</i> method.
* @returns a new Unpickler instance.
*/
public static Unpickler Unpickler(PyObject file) {
return new Unpickler(file);
}
/**
* Shorthand function which pickles the object on the file.
* @param object a data object which should be pickled.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method. The data will be written as
* text.
* @returns a new Unpickler instance.
*/
public static void dump(PyObject object, PyObject file) {
dump(object, file, false);
}
/**
* Shorthand function which pickles the object on the file.
* @param object a data object which should be pickled.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method.
* @param bin when true, the output will be written as binary data.
* @returns a new Unpickler instance.
*/
public static void dump(PyObject object, PyObject file, boolean bin) {
new Pickler(file, bin).dump(object);
}
/**
* Shorthand function which pickles and returns the string representation.
* @param object a data object which should be pickled.
* @returns a string representing the pickled object.
*/
public static String dumps(PyObject object) {
return dumps(object, false);
}
/**
* Shorthand function which pickles and returns the string representation.
* @param object a data object which should be pickled.
* @param bin when true, the output will be written as binary data.
* @returns a string representing the pickled object.
*/
public static String dumps(PyObject object, boolean bin) {
cStringIO.StringIO file = cStringIO.StringIO();
dump(object, file, bin);
return file.getvalue();
}
/**
* Shorthand function which unpickles a object from the file and returns
* the new object.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>read</i> and <i>readline</i> method.
* @returns a new object.
*/
public static Object load(PyObject file) {
return new Unpickler(file).load();
}
/**
* Shorthand function which unpickles a object from the string and
* returns the new object.
* @param str a strings which must contain a pickled object
* representation.
* @returns a new object.
*/
public static Object loads(PyObject str) {
cStringIO.StringIO file = cStringIO.StringIO(str.toString());
return new Unpickler(file).load();
}
// Factory for creating IOFile representation.
private static IOFile createIOFile(PyObject file) {
Object f = file.__tojava__(cStringIO.StringIO.class);
if (f != Py.NoConversion)
return new cStringIOFile((cStringIO.StringIO)file);
else if (__builtin__.isinstance(file, FileType))
return new FileIOFile(file);
else
return new ObjectIOFile(file);
}
// IOFiles encapsulates and optimise access to the different file
// representation.
interface IOFile {
public abstract void write(String str);
// Usefull optimization since most data written are chars.
public abstract void write(char str);
public abstract void flush();
public abstract String read(int len);
// Usefull optimization since all readlines removes the
// trainling newline.
public abstract String readlineNoNl();
}
// Use a cStringIO as a file.
static class cStringIOFile implements IOFile {
cStringIO.StringIO file;
cStringIOFile(PyObject file) {
this.file = (cStringIO.StringIO)file.__tojava__(Object.class);
}
public void write(String str) {
file.write(str);
}
public void write(char ch) {
file.writeChar(ch);
}
public void flush() {}
public String read(int len) {
return file.read(len);
}
public String readlineNoNl() {
return file.readlineNoNl();
}
}
// Use a PyFile as a file.
static class FileIOFile implements IOFile {
PyFile file;
FileIOFile(PyObject file) {
this.file = (PyFile)file.__tojava__(PyFile.class);
if (this.file.closed)
throw Py.ValueError("I/O operation on closed file");
}
public void write(String str) {
file.write(str);
}
public void write(char ch) {
file.write(cStringIO.getString(ch));
}
public void flush() {}
public String read(int len) {
return file.read(len).toString();
}
public String readlineNoNl() {
String line = file.readline().toString();
return line.substring(0, line.length()-1);
}
}
// Use any python object as a file.
static class ObjectIOFile implements IOFile {
char[] charr = new char[1];
StringBuffer buff = new StringBuffer();
PyObject write;
PyObject read;
PyObject readline;
final int BUF_SIZE = 256;
ObjectIOFile(PyObject file) {
// this.file = file;
write = file.__findattr__("write");
read = file.__findattr__("read");
readline = file.__findattr__("readline");
}
public void write(String str) {
buff.append(str);
if (buff.length() > BUF_SIZE)
flush();
}
public void write(char ch) {
buff.append(ch);
if (buff.length() > BUF_SIZE)
flush();
}
public void flush() {
write.__call__(new PyString(buff.toString()));
buff.setLength(0);
}
public String read(int len) {
return read.__call__(new PyInteger(len)).toString();
}
public String readlineNoNl() {
String line = readline.__call__().toString();
return line.substring(0, line.length()-1);
}
}
/**
* The Pickler object
* @see cPickle#Pickler(PyObject)
* @see cPickle#Pickler(PyObject,boolean)
*/
static public class Pickler {
private IOFile file;
private boolean bin;
/**
* Hmm, not documented, perhaps it shouldn't be public? XXX: fixme.
*/
private PickleMemo memo = new PickleMemo();
/**
* To write references to persistent objects, the persistent module
* must assign a method to persistent_id which returns either None
* or the persistent ID of the object.
* For the benefit of persistency modules written using pickle,
* it supports the notion of a reference to an object outside
* the pickled data stream.
* Such objects are referenced by a name, which is an arbitrary
* string of printable ASCII characters.
*/
public PyObject persistent_id = null;
/**
* Hmm, not documented, perhaps it shouldn't be public? XXX: fixme.
*/
public PyObject inst_persistent_id = null;
public Pickler(PyObject file, boolean bin) {
this.file = createIOFile(file);
this.bin = bin;
}
/**
* Write a pickled representation of the object.
* @param object The object which will be pickled.
*/
public void dump(PyObject object) {
save(object);
file.write(STOP);
file.flush();
}
// Save name as in pickle.py but semantics are slightly changed.
private void put(int i) {
if (bin) {
if (i < 256) {
file.write(BINPUT);
file.write((char)i);
return;
}
file.write(LONG_BINPUT);
file.write((char)( i & 0xFF));
file.write((char)((i >>> 8) & 0xFF));
file.write((char)((i >>> 16) & 0xFF));
file.write((char)((i >>> 24) & 0xFF));
return;
}
file.write(PUT);
file.write(String.valueOf(i));
file.write("\n");
}
// Same name as in pickle.py but semantics are slightly changed.
private void get(int i) {
if (bin) {
if (i < 256) {
file.write(BINGET);
file.write((char)i);
return;
}
file.write(LONG_BINGET);
file.write((char)( i & 0xFF));
file.write((char)((i >>> 8) & 0xFF));
file.write((char)((i >>> 16) & 0xFF));
file.write((char)((i >>> 24) & 0xFF));
return;
}
file.write(GET);
file.write(String.valueOf(i));
file.write("\n");
}
private void save(PyObject object) {
save(object, false);
}
private void save(PyObject object, boolean pers_save) {
if (!pers_save) {
if (persistent_id != null) {
PyObject pid = persistent_id.__call__(object);
if (pid != Py.None) {
save_pers(pid);
return;
}
}
}
int d = Py.id(object);
PyClass t = __builtin__.type(object);
if (t == TupleType && object.__len__() == 0) {
if (bin)
save_empty_tuple(object);
else
save_tuple(object);
return;
}
int m = getMemoPosition(d, object);
if (m >= 0) {
get(m);
return;
}
if (save_type(object, t))
return;
if (inst_persistent_id != null) {
PyObject pid = inst_persistent_id.__call__(object);
if (pid != Py.None) {
save_pers(pid);
return;
}
}
PyObject tup = null;
PyObject reduce = dispatch_table.__finditem__(t);
if (reduce == null) {
reduce = object.__findattr__("__reduce__");
if (reduce == null)
throw new PyException(UnpickleableError, object);
tup = reduce.__call__();
} else {
tup = reduce.__call__(object);
}
- if (tup instanceof PyString) {
+ if (tup instanceof PyString) {
save_global(object, tup);
return;
}
if (!(tup instanceof PyTuple)) {
throw new PyException(PicklingError,
"Value returned by " + reduce.__repr__() +
" must be a tuple");
}
int l = tup.__len__();
if (l != 2 && l != 3) {
throw new PyException(PicklingError,
"tuple returned by " + reduce.__repr__() +
" must contain only two or three elements");
}
PyObject callable = tup.__finditem__(0);
PyObject arg_tup = tup.__finditem__(1);
PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None;
if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) {
throw new PyException(PicklingError,
"Second element of tupe returned by " +
reduce.__repr__() + " must be a tuple");
}
save_reduce(callable, arg_tup, state);
put(putMemo(d, object));
}
final private void save_pers(PyObject pid) {
if (!bin) {
file.write(PERSID);
file.write(pid.toString());
file.write("\n");
} else {
save(pid, true);
file.write(BINPERSID);
}
}
final private void save_reduce(PyObject callable, PyObject arg_tup,
PyObject state)
{
save(callable);
save(arg_tup);
file.write(REDUCE);
if (state != Py.None) {
save(state);
file.write(BUILD);
}
}
final private boolean save_type(PyObject object, PyClass cls) {
//System.out.println("save_type " + object + " " + cls);
if (cls == NoneType)
save_none(object);
else if (cls == StringType)
save_string(object);
else if (cls == IntType)
save_int(object);
else if (cls == LongType)
save_long(object);
else if (cls == FloatType)
save_float(object);
else if (cls == TupleType)
save_tuple(object);
else if (cls == ListType)
save_list(object);
else if (cls == DictionaryType || cls == StringMapType)
save_dict(object);
else if (cls == InstanceType)
save_inst((PyInstance)object);
else if (cls == ClassType)
save_global(object);
else if (cls == FunctionType)
save_global(object);
else if (cls == BuiltinFunctionType)
save_global(object);
else
return false;
return true;
}
final private void save_none(PyObject object) {
file.write(NONE);
}
final private void save_int(PyObject object) {
if (bin) {
int l = ((PyInteger)object).getValue();
char i1 = (char)( l & 0xFF);
char i2 = (char)((l >>> 8 ) & 0xFF);
char i3 = (char)((l >>> 16) & 0xFF);
char i4 = (char)((l >>> 24) & 0xFF);
if (i3 == '\0' && i4 == '\0') {
if (i2 == '\0') {
file.write(BININT1);
file.write(i1);
return;
}
file.write(BININT2);
file.write(i1);
file.write(i2);
return;
}
file.write(BININT);
file.write(i1);
file.write(i2);
file.write(i3);
file.write(i4);
} else {
file.write(INT);
file.write(object.toString());
file.write("\n");
}
}
final private void save_long(PyObject object) {
file.write(LONG);
file.write(object.toString());
file.write("\n");
}
final private void save_float(PyObject object) {
if (bin) {
file.write(BINFLOAT);
double value= ((PyFloat) object).getValue();
// It seems that struct.pack('>d', ..) and doubleToLongBits
// are the same. Good for me :-)
long bits = Double.doubleToLongBits(value);
file.write((char)((bits >>> 56) & 0xFF));
file.write((char)((bits >>> 48) & 0xFF));
file.write((char)((bits >>> 40) & 0xFF));
file.write((char)((bits >>> 32) & 0xFF));
file.write((char)((bits >>> 24) & 0xFF));
file.write((char)((bits >>> 16) & 0xFF));
file.write((char)((bits >>> 8) & 0xFF));
file.write((char)((bits >>> 0) & 0xFF));
} else {
file.write(FLOAT);
file.write(object.toString());
file.write("\n");
}
}
final private void save_string(PyObject object) {
boolean unicode = ((PyString) object).isunicode();
String str = object.toString();
if (bin) {
if (unicode)
str = codecs.PyUnicode_EncodeUTF8(str, "struct");
int l = str.length();
if (l < 256 && !unicode) {
file.write(SHORT_BINSTRING);
file.write((char)l);
} else {
if (unicode)
file.write(BINUNICODE);
else
file.write(BINSTRING);
file.write((char)( l & 0xFF));
file.write((char)((l >>> 8 ) & 0xFF));
file.write((char)((l >>> 16) & 0xFF));
file.write((char)((l >>> 24) & 0xFF));
}
file.write(str);
} else {
if (unicode) {
file.write(UNICODE);
file.write(codecs.PyUnicode_EncodeRawUnicodeEscape(str,
"strict", true));
} else {
file.write(STRING);
file.write(object.__repr__().toString());
}
file.write("\n");
}
put(putMemo(Py.id(object), object));
}
final private void save_tuple(PyObject object) {
int d = Py.id(object);
file.write(MARK);
int len = object.__len__();
for (int i = 0; i < len; i++)
save(object.__finditem__(i));
if (len > 0) {
int m = getMemoPosition(d, object);
if (m >= 0) {
if (bin) {
file.write(POP_MARK);
get(m);
return;
}
for (int i = 0; i < len+1; i++)
file.write(POP);
get(m);
return;
}
}
file.write(TUPLE);
put(putMemo(d, object));
}
final private void save_empty_tuple(PyObject object) {
file.write(EMPTY_TUPLE);
}
final private void save_list(PyObject object) {
if (bin)
file.write(EMPTY_LIST);
else {
file.write(MARK);
file.write(LIST);
}
put(putMemo(Py.id(object), object));
int len = object.__len__();
boolean using_appends = bin && len > 1;
if (using_appends)
file.write(MARK);
for (int i = 0; i < len; i++) {
save(object.__finditem__(i));
if (!using_appends)
file.write(APPEND);
}
if (using_appends)
file.write(APPENDS);
}
final private void save_dict(PyObject object) {
if (bin)
file.write(EMPTY_DICT);
else {
file.write(MARK);
file.write(DICT);
}
put(putMemo(Py.id(object), object));
PyObject list = object.invoke("keys");
int len = list.__len__();
boolean using_setitems = (bin && len > 1);
if (using_setitems)
file.write(MARK);
for (int i = 0; i < len; i++) {
PyObject key = list.__finditem__(i);
PyObject value = object.__finditem__(key);
save(key);
save(value);
if (!using_setitems)
file.write(SETITEM);
}
if (using_setitems)
file.write(SETITEMS);
}
final private void save_inst(PyInstance object) {
if (object instanceof PyJavaInstance)
throw new PyException(PicklingError,
"Unable to pickle java objects.");
PyClass cls = object.__class__;
PySequence args = null;
PyObject getinitargs = object.__findattr__("__getinitargs__");
if (getinitargs != null) {
args = (PySequence)getinitargs.__call__();
// XXX Assert it's a sequence
keep_alive(args);
}
file.write(MARK);
if (bin)
save(cls);
if (args != null) {
int len = args.__len__();
for (int i = 0; i < len; i++)
save(args.__finditem__(i));
}
int mid = putMemo(Py.id(object), object);
if (bin) {
file.write(OBJ);
put(mid);
} else {
file.write(INST);
file.write(cls.__findattr__("__module__").toString());
file.write("\n");
file.write(cls.__name__);
file.write("\n");
put(mid);
}
PyObject stuff = null;
PyObject getstate = object.__findattr__("__getstate__");
if (getstate == null) {
stuff = object.__dict__;
} else {
stuff = getstate.__call__();
keep_alive(stuff);
}
save(stuff);
file.write(BUILD);
}
final private void save_global(PyObject object) {
save_global(object, null);
}
final private void save_global(PyObject object, PyObject name) {
if (name == null)
name = object.__findattr__("__name__");
PyObject module = object.__findattr__("__module__");
if (module == null || module == Py.None)
module = whichmodule(object, name);
file.write(GLOBAL);
file.write(module.toString());
file.write("\n");
file.write(name.toString());
file.write("\n");
put(putMemo(Py.id(object), object));
}
final private int getMemoPosition(int id, Object o) {
return memo.findPosition(id, o);
}
final private int putMemo(int id, PyObject object) {
int memo_len = memo.size();
memo.put(id, memo_len, object);
return memo_len;
}
/**
* Keeps a reference to the object x in the memo.
*
* Because we remember objects by their id, we have
* to assure that possibly temporary objects are kept
* alive by referencing them.
* We store a reference at the id of the memo, which should
* normally not be used unless someone tries to deepcopy
* the memo itself...
*/
final private void keep_alive(PyObject obj) {
int id = System.identityHashCode(memo);
PyList list = (PyList) memo.findValue(id, memo);
if (list == null) {
list = new PyList();
memo.put(id, -1, list);
}
list.append(obj);
}
}
private static Hashtable classmap = new Hashtable();
final private static PyObject whichmodule(PyObject cls,
PyObject clsname)
{
PyObject name = (PyObject)classmap.get(cls);
if (name != null)
return name;
name = new PyString("__main__");
// For use with JPython1.0.x
//PyObject modules = sys.modules;
// For use with JPython1.1.x
//PyObject modules = Py.getSystemState().modules;
PyObject sys = imp.importName("sys", true);
PyObject modules = sys.__findattr__("modules");
PyObject keylist = modules.invoke("keys");
int len = keylist.__len__();
for (int i = 0; i < len; i++) {
PyObject key = keylist.__finditem__(i);
PyObject value = modules.__finditem__(key);
if (!key.equals("__main__") &&
value.__findattr__(clsname.toString().intern()) == cls) {
name = key;
break;
}
}
classmap.put(cls, name);
//System.out.println(name);
return name;
}
/*
* A very specialized and simplified version of PyStringMap. It can
* only use integers as keys and stores both an integer and an object
* as value. It is very private!
*/
static private class PickleMemo {
//Table of primes to cycle through
private final int[] primes = {
13, 61, 251, 1021, 4093,
5987, 9551, 15683, 19609, 31397,
65521, 131071, 262139, 524287, 1048573, 2097143,
4194301, 8388593, 16777213, 33554393, 67108859,
134217689, 268435399, 536870909, 1073741789,};
private transient int[] keys;
private transient int[] position;
private transient Object[] values;
private int size;
private transient int filled;
private transient int prime;
// Not actually used, since there is no delete methods.
private String DELETEDKEY = "<deleted key>";
public PickleMemo(int capacity) {
prime = 0;
keys = null;
values = null;
resize(capacity);
}
public PickleMemo() {
this(4);
}
public synchronized int size() {
return size;
}
private int findIndex(int key, Object value) {
int[] table = keys;
int maxindex = table.length;
int index = (key & 0x7fffffff) % maxindex;
// Fairly aribtrary choice for stepsize...
int stepsize = maxindex / 5;
// Cycle through possible positions for the key;
//int collisions = 0;
while (true) {
int tkey = table[index];
if (tkey == key && value == values[index]) {
return index;
}
if (values[index] == null) return -1;
index = (index+stepsize) % maxindex;
}
}
public int findPosition(int key, Object value) {
int idx = findIndex(key, value);
if (idx < 0) return -1;
return position[idx];
}
public Object findValue(int key, Object value) {
int idx = findIndex(key, value);
if (idx < 0) return null;
return values[idx];
}
private final void insertkey(int key, int pos, Object value) {
int[] table = keys;
int maxindex = table.length;
int index = (key & 0x7fffffff) % maxindex;
// Fairly aribtrary choice for stepsize...
int stepsize = maxindex / 5;
// Cycle through possible positions for the key;
while (true) {
int tkey = table[index];
if (values[index] == null) {
table[index] = key;
position[index] = pos;
values[index] = value;
filled++;
size++;
break;
} else if (tkey == key && values[index] == value) {
position[index] = pos;
break;
} else if (values[index] == DELETEDKEY) {
table[index] = key;
position[index] = pos;
values[index] = value;
size++;
break;
}
index = (index+stepsize) % maxindex;
}
}
private synchronized final void resize(int capacity) {
int p = prime;
for(; p<primes.length; p++) {
if (primes[p] >= capacity) break;
}
if (primes[p] < capacity) {
throw Py.ValueError("can't make hashtable of size: " +
capacity);
}
capacity = primes[p];
prime = p;
int[] oldKeys = keys;
int[] oldPositions = position;
Object[] oldValues = values;
keys = new int[capacity];
position = new int[capacity];
values = new Object[capacity];
size = 0;
filled = 0;
if (oldValues != null) {
int n = oldValues.length;
for(int i=0; i<n; i++) {
Object value = oldValues[i];
if (value == null || value == DELETEDKEY) continue;
insertkey(oldKeys[i], oldPositions[i], value);
}
}
}
public void put(int key, int pos, Object value) {
if (2*filled > keys.length) resize(keys.length+1);
insertkey(key, pos, value);
}
}
/**
* The Unpickler object. Unpickler instances are create by the factory
* methods Unpickler.
* @see cPickle#Unpickler(PyObject)
*/
static public class Unpickler {
private IOFile file;
public Hashtable memo = new Hashtable();
/**
* For the benefit of persistency modules written using pickle,
* it supports the notion of a reference to an object outside
* the pickled data stream.
* Such objects are referenced by a name, which is an arbitrary
* string of printable ASCII characters.
* The resolution of such names is not defined by the pickle module
* -- the persistent object module will have to add a method
* persistent_load().
*/
public PyObject persistent_load = null;
private PyObject mark = new PyString("spam");
private int stackTop;
private PyObject[] stack;
Unpickler(PyObject file) {
this.file = createIOFile(file);
}
/**
* Unpickle and return an instance of the object represented by
* the file.
*/
public PyObject load() {
stackTop = 0;
stack = new PyObject[10];
while (true) {
String s = file.read(1);
// System.out.println("load:" + s);
// for (int i = 0; i < stackTop; i++)
// System.out.println(" " + stack[i]);
if (s.length() < 1)
load_eof();
char key = s.charAt(0);
switch (key) {
case PERSID: load_persid(); break;
case BINPERSID: load_binpersid(); break;
case NONE: load_none(); break;
case INT: load_int(); break;
case BININT: load_binint(); break;
case BININT1: load_binint1(); break;
case BININT2: load_binint2(); break;
case LONG: load_long(); break;
case FLOAT: load_float(); break;
case BINFLOAT: load_binfloat(); break;
case STRING: load_string(); break;
case BINSTRING: load_binstring(); break;
case SHORT_BINSTRING: load_short_binstring(); break;
case UNICODE: load_unicode(); break;
case BINUNICODE: load_binunicode(); break;
case TUPLE: load_tuple(); break;
case EMPTY_TUPLE: load_empty_tuple(); break;
case EMPTY_LIST: load_empty_list(); break;
case EMPTY_DICT: load_empty_dictionary(); break;
case LIST: load_list(); break;
case DICT: load_dict(); break;
case INST: load_inst(); break;
case OBJ: load_obj(); break;
case GLOBAL: load_global(); break;
case REDUCE: load_reduce(); break;
case POP: load_pop(); break;
case POP_MARK: load_pop_mark(); break;
case DUP: load_dup(); break;
case GET: load_get(); break;
case BINGET: load_binget(); break;
case LONG_BINGET: load_long_binget(); break;
case PUT: load_put(); break;
case BINPUT: load_binput(); break;
case LONG_BINPUT: load_long_binput(); break;
case APPEND: load_append(); break;
case APPENDS: load_appends(); break;
case SETITEM: load_setitem(); break;
case SETITEMS: load_setitems(); break;
case BUILD: load_build(); break;
case MARK: load_mark(); break;
case STOP:
return load_stop();
}
}
}
final private int marker() {
for (int k = stackTop-1; k >= 0; k--)
if (stack[k] == mark)
return stackTop-k-1;
throw new PyException(UnpicklingError,
"Inputstream corrupt, marker not found");
}
final private void load_eof() {
throw new PyException(Py.EOFError);
}
final private void load_persid() {
String pid = file.readlineNoNl();
push(persistent_load.__call__(new PyString(pid)));
}
final private void load_binpersid() {
PyObject pid = pop();
push(persistent_load.__call__(pid));
}
final private void load_none() {
push(Py.None);
}
final private void load_int() {
String line = file.readlineNoNl();
// XXX: use strop instead?
push(new PyInteger(Integer.parseInt(line)));
}
final private void load_binint() {
String s = file.read(4);
int x = s.charAt(0) |
(s.charAt(1)<<8) |
(s.charAt(2)<<16) |
(s.charAt(3)<<24);
push(new PyInteger(x));
}
final private void load_binint1() {
int val = (int)file.read(1).charAt(0);
push(new PyInteger(val));
}
final private void load_binint2() {
String s = file.read(2);
int val = ((int)s.charAt(1)) << 8 | ((int)s.charAt(0));
push(new PyInteger(val));
}
final private void load_long() {
String line = file.readlineNoNl();
push(new PyLong(line.substring(0, line.length()-1)));
}
final private void load_float() {
String line = file.readlineNoNl();
push(new PyFloat(Double.valueOf(line).doubleValue()));
}
final private void load_binfloat() {
String s = file.read(8);
long bits = (long)s.charAt(7) |
((long)s.charAt(6) << 8) |
((long)s.charAt(5) << 16) |
((long)s.charAt(4) << 24) |
((long)s.charAt(3) << 32) |
((long)s.charAt(2) << 40) |
((long)s.charAt(1) << 48) |
((long)s.charAt(0) << 56);
push(new PyFloat(Double.longBitsToDouble(bits)));
}
final private void load_string() {
String line = file.readlineNoNl();
String value;
char quote = line.charAt(0);
if (quote != '"' && quote != '\'')
throw Py.ValueError("insecure string pickle");
int nslash = 0;
int i;
char ch = '\0';
int n = line.length();
for (i = 1; i < n; i++) {
ch = line.charAt(i);
if (ch == quote && nslash % 2 == 0)
break;
if (ch == '\\')
nslash++;
else
nslash = 0;
}
if (ch != quote)
throw Py.ValueError("insecure string pickle");
for (i++ ; i < line.length(); i++) {
if (line.charAt(i) > ' ')
throw Py.ValueError("insecure string pickle " + i);
}
value = PyString.decode_UnicodeEscape(line, 1, n-1,
"strict", false);
push(new PyString(value));
}
final private void load_binstring() {
String d = file.read(4);
int len = d.charAt(0) |
(d.charAt(1)<<8) |
(d.charAt(2)<<16) |
(d.charAt(3)<<24);
push(new PyString(file.read(len)));
}
final private void load_short_binstring() {
int len = (int)file.read(1).charAt(0);
push(new PyString(file.read(len)));
}
final private void load_unicode() {
String line = file.readlineNoNl();
int n = line.length();
String value = codecs.PyUnicode_DecodeRawUnicodeEscape(line,
"strict");
push(new PyString(value));
}
final private void load_binunicode() {
String d = file.read(4);
int len = d.charAt(0) |
(d.charAt(1)<<8) |
(d.charAt(2)<<16) |
(d.charAt(3)<<24);
String line = file.read(len);
push(new PyString(codecs.PyUnicode_DecodeUTF8(line, "strict")));
}
final private void load_tuple() {
PyObject[] arr = new PyObject[marker()];
pop(arr);
pop();
push(new PyTuple(arr));
}
final private void load_empty_tuple() {
push(new PyTuple(Py.EmptyObjects));
}
final private void load_empty_list() {
push(new PyList(Py.EmptyObjects));
}
final private void load_empty_dictionary() {
push(new PyDictionary());
}
final private void load_list() {
PyObject[] arr = new PyObject[marker()];
pop(arr);
pop();
push(new PyList(arr));
}
final private void load_dict() {
int k = marker();
PyDictionary d = new PyDictionary();
for (int i = 0; i < k; i += 2) {
PyObject value = pop();
PyObject key = pop();
d.__setitem__(key, value);
}
pop();
push(d);
}
final private void load_inst() {
PyObject[] args = new PyObject[marker()];
pop(args);
pop();
String module = file.readlineNoNl();
String name = file.readlineNoNl();
PyObject klass = find_class(module, name);
PyObject value = null;
if (args.length == 0 && klass instanceof PyClass &&
klass.__findattr__("__getinitargs__") == null) {
value = new PyInstance((PyClass)klass);
} else {
value = klass.__call__(args);
}
push(value);
}
final private void load_obj() {
PyObject[] args = new PyObject[marker()-1];
pop(args);
PyObject klass = pop();
pop();
PyObject value = null;
if (args.length == 0 && klass instanceof PyClass &&
klass.__findattr__("__getinitargs__") == null) {
value = new PyInstance((PyClass)klass);
} else {
value = klass.__call__(args);
}
push(value);
}
final private void load_global() {
String module = file.readlineNoNl();
String name = file.readlineNoNl();
PyObject klass = find_class(module, name);
push(klass);
}
final private PyObject find_class(String module, String name) {
PyObject fc = dict.__finditem__("find_global");
if (fc != null) {
if (fc == Py.None)
throw new PyException(UnpicklingError,
"Global and instance pickles are not supported.");
return fc.__call__(new PyString(module), new PyString(name));
}
PyObject modules = Py.getSystemState().modules;
PyObject mod = modules.__finditem__(module.intern());
if (mod == null) {
mod = importModule(module);
}
PyObject global = mod.__findattr__(name.intern());
if (global == null) {
throw new PyException(Py.SystemError,
"Failed to import class " + name + " from module " +
module);
}
return global;
}
final private void load_reduce() {
PyObject arg_tup = pop();
PyObject callable = pop();
if (!(callable instanceof PyClass)) {
if (safe_constructors.__finditem__(callable) == null) {
if (callable.__findattr__("__safe_for_unpickling__")
== null)
throw new PyException(UnpicklingError,
callable + " is not safe for unpickling");
}
}
PyObject value = null;
if (arg_tup == Py.None) {
// XXX __basicnew__ ?
value = callable.__findattr__("__basicnew__").__call__();
} else {
value = callable.__call__(make_array(arg_tup));
}
push(value);
}
final private PyObject[] make_array(PyObject seq) {
int n = seq.__len__();
PyObject[] objs= new PyObject[n];
for(int i=0; i<n; i++)
objs[i] = seq.__finditem__(i);
return objs;
}
final private void load_pop() {
pop();
}
final private void load_pop_mark() {
pop(marker());
}
final private void load_dup() {
push(peek());
}
final private void load_get() {
String py_str = file.readlineNoNl();
PyObject value = (PyObject)memo.get(py_str);
if (value == null)
throw new PyException(BadPickleGet, py_str);
push(value);
}
final private void load_binget() {
String py_key = String.valueOf((int)file.read(1).charAt(0));
PyObject value = (PyObject)memo.get(py_key);
if (value == null)
throw new PyException(BadPickleGet, py_key);
push(value);
}
final private void load_long_binget() {
String d = file.read(4);
int i = d.charAt(0) |
(d.charAt(1)<<8) |
(d.charAt(2)<<16) |
(d.charAt(3)<<24);
String py_key = String.valueOf(i);
PyObject value = (PyObject)memo.get(py_key);
if (value == null)
throw new PyException(BadPickleGet, py_key);
push(value);
}
final private void load_put() {
memo.put(file.readlineNoNl(), peek());
}
final private void load_binput() {
int i = (int)file.read(1).charAt(0);
memo.put(String.valueOf(i), peek());
}
final private void load_long_binput() {
String d = file.read(4);
int i = d.charAt(0) |
(d.charAt(1)<<8) |
(d.charAt(2)<<16) |
(d.charAt(3)<<24);
memo.put(String.valueOf(i), peek());
}
final private void load_append() {
PyObject value = pop();
PyList list = (PyList)peek();
list.append(value);
}
final private void load_appends() {
int mark = marker();
PyList list = (PyList)peek(mark+1);
for (int i = mark-1; i >= 0; i--)
list.append(peek(i));
pop(mark+1);
}
final private void load_setitem() {
PyObject value = pop();
PyObject key = pop();
PyDictionary dict = (PyDictionary)peek();
dict.__setitem__(key, value);
}
final private void load_setitems() {
int mark = marker();
PyDictionary dict = (PyDictionary)peek(mark+1);
for (int i = 0; i < mark; i += 2) {
PyObject key = peek(i+1);
PyObject value = peek(i);
dict.__setitem__(key, value);
}
pop(mark+1);
}
final private void load_build() {
PyObject value = pop();
PyInstance inst = (PyInstance)peek();
PyObject setstate = inst.__findattr__("__setstate__");
if (setstate == null) {
inst.__dict__.__findattr__("update").__call__(value);
} else {
setstate.__call__(value);
}
}
final private void load_mark() {
push(mark);
}
final private PyObject load_stop() {
return pop();
}
final private PyObject peek() {
return stack[stackTop-1];
}
final private PyObject peek(int count) {
return stack[stackTop-count-1];
}
final private PyObject pop() {
PyObject val = stack[--stackTop];
stack[stackTop] = null;
return val;
}
final private void pop(int count) {
for (int i = 0; i < count; i++)
stack[--stackTop] = null;
}
final private void pop(PyObject[] arr) {
int len = arr.length;
System.arraycopy(stack, stackTop - len, arr, 0, len);
stackTop -= len;
}
final private void push(PyObject val) {
if (stackTop >= stack.length) {
PyObject[] newStack = new PyObject[(stackTop+1) * 2];
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
stack[stackTop++] = val;
}
}
private static PyObject importModule(String name) {
PyObject silly_list = new PyTuple(new PyString[] {
Py.newString("__doc__"),
});
return __builtin__.__import__(name, null, null, silly_list);
}
private static PyObject getJavaFunc(String name) {
return Py.newJavaFunc(cPickle.class, name);
}
private static PyObject buildClass(String classname,
PyObject superclass,
String classCodeName,
String doc) {
PyObject[] sclass = Py.EmptyObjects;
if (superclass != null)
sclass = new PyObject[] { superclass };
PyObject cls = Py.makeClass(
classname, sclass,
Py.newJavaCode(cPickle.class, classCodeName),
new PyString(doc));
return cls;
}
}
| true | true | private void save(PyObject object, boolean pers_save) {
if (!pers_save) {
if (persistent_id != null) {
PyObject pid = persistent_id.__call__(object);
if (pid != Py.None) {
save_pers(pid);
return;
}
}
}
int d = Py.id(object);
PyClass t = __builtin__.type(object);
if (t == TupleType && object.__len__() == 0) {
if (bin)
save_empty_tuple(object);
else
save_tuple(object);
return;
}
int m = getMemoPosition(d, object);
if (m >= 0) {
get(m);
return;
}
if (save_type(object, t))
return;
if (inst_persistent_id != null) {
PyObject pid = inst_persistent_id.__call__(object);
if (pid != Py.None) {
save_pers(pid);
return;
}
}
PyObject tup = null;
PyObject reduce = dispatch_table.__finditem__(t);
if (reduce == null) {
reduce = object.__findattr__("__reduce__");
if (reduce == null)
throw new PyException(UnpickleableError, object);
tup = reduce.__call__();
} else {
tup = reduce.__call__(object);
}
if (tup instanceof PyString) {
save_global(object, tup);
return;
}
if (!(tup instanceof PyTuple)) {
throw new PyException(PicklingError,
"Value returned by " + reduce.__repr__() +
" must be a tuple");
}
int l = tup.__len__();
if (l != 2 && l != 3) {
throw new PyException(PicklingError,
"tuple returned by " + reduce.__repr__() +
" must contain only two or three elements");
}
PyObject callable = tup.__finditem__(0);
PyObject arg_tup = tup.__finditem__(1);
PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None;
if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) {
throw new PyException(PicklingError,
"Second element of tupe returned by " +
reduce.__repr__() + " must be a tuple");
}
save_reduce(callable, arg_tup, state);
put(putMemo(d, object));
}
| private void save(PyObject object, boolean pers_save) {
if (!pers_save) {
if (persistent_id != null) {
PyObject pid = persistent_id.__call__(object);
if (pid != Py.None) {
save_pers(pid);
return;
}
}
}
int d = Py.id(object);
PyClass t = __builtin__.type(object);
if (t == TupleType && object.__len__() == 0) {
if (bin)
save_empty_tuple(object);
else
save_tuple(object);
return;
}
int m = getMemoPosition(d, object);
if (m >= 0) {
get(m);
return;
}
if (save_type(object, t))
return;
if (inst_persistent_id != null) {
PyObject pid = inst_persistent_id.__call__(object);
if (pid != Py.None) {
save_pers(pid);
return;
}
}
PyObject tup = null;
PyObject reduce = dispatch_table.__finditem__(t);
if (reduce == null) {
reduce = object.__findattr__("__reduce__");
if (reduce == null)
throw new PyException(UnpickleableError, object);
tup = reduce.__call__();
} else {
tup = reduce.__call__(object);
}
if (tup instanceof PyString) {
save_global(object, tup);
return;
}
if (!(tup instanceof PyTuple)) {
throw new PyException(PicklingError,
"Value returned by " + reduce.__repr__() +
" must be a tuple");
}
int l = tup.__len__();
if (l != 2 && l != 3) {
throw new PyException(PicklingError,
"tuple returned by " + reduce.__repr__() +
" must contain only two or three elements");
}
PyObject callable = tup.__finditem__(0);
PyObject arg_tup = tup.__finditem__(1);
PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None;
if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) {
throw new PyException(PicklingError,
"Second element of tupe returned by " +
reduce.__repr__() + " must be a tuple");
}
save_reduce(callable, arg_tup, state);
put(putMemo(d, object));
}
|
diff --git a/StorySense/src/webEncoder/CompleteStoryLoader.java b/StorySense/src/webEncoder/CompleteStoryLoader.java
index d621e2c..9f10478 100644
--- a/StorySense/src/webEncoder/CompleteStoryLoader.java
+++ b/StorySense/src/webEncoder/CompleteStoryLoader.java
@@ -1,231 +1,231 @@
package webEncoder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import javax.servlet.jsp.JspWriter;
import dao.AcomplishmentDAO;
import dao.DAOFactory;
import dao.LikedStoryDAO;
import dao.UserDAO;
import model.Story;
import serializableObjects.StoryFileAccess;
import entity.Acomplishment;
import entity.User;
/**
* This loads the stories from the server to be returned to the browser
* The AJAXscripts must be loaded from the html file for full functionality
* @author nickleus`
*
*/
public class CompleteStoryLoader {
private User SessionUser;
public CompleteStoryLoader(){}
public CompleteStoryLoader(User u){
SessionUser=u;
}
/*Methods*/
public String previewStory(StoryFileAccess StoryF)
{
Story Story=StoryF.getMyStory();
String story_preview = Story.getsStory();
for (int i=0; i<StoryF.getAnswers().size(); i++)
{
/*revised story writer format
*
*/
story_preview = story_preview.replaceFirst("<input type='text' width='15' name='answer"+(i+1)+
"' id='answer"+(i+1)+"'/>.",
StoryF.getAnswers().get(i)+" ");
story_preview = story_preview.replaceFirst("<input type='text' width='15' name='answer"+(i+1)+"' />.",
StoryF.getAnswers().get(i)+" ");
}
return story_preview;
}
/**
* Loads a story given the file entered
*/
public String loadStory(String fileUrl){
FileInputStream fileIn;
try {
fileIn = new FileInputStream(fileUrl);
ObjectInputStream oi = new ObjectInputStream(fileIn);
StoryFileAccess storyFile=(StoryFileAccess)oi.readObject();
fileIn.close();
return previewStory(storyFile);
} catch(IOException ioEx){
return "File path problems D:";
}
catch(Exception ex){
//out.println("Error in getting the story\n"+ex.getMessage());
}
return "Error";
}
/**
* Shows the stories requires the AjaxScripts
* @param out
*/
public void showStories(JspWriter out){
DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
AcomplishmentDAO myAcomDAO=myDAOFactory.createAcomplishmentDAO();
ArrayList<Acomplishment> Stories=(ArrayList<Acomplishment>)myAcomDAO.getAllStories();
UserDAO myUserDao=myDAOFactory.createUserDAO();
User myUser;
try{
//out.write("<p>");
out.write("<table id=\"tableBorderfeed2\" bgcolor=\"white\">");
out.write("<tr><td id='1st'></td></tr>");
/*loop that displays the stories*/
for(int ctr=0;ctr<Stories.size();ctr++){
out.write("<tr class=\"storyHead\">");
myUser=myUserDao.getUser(Stories.get(ctr).getAccountID());
out.write("<th>Title:</th><td> "+Stories.get(ctr).getName()+"</td> <th>Made by </th>" +
"<td>"+myUser.getName()+"</td></tr>");
if(SessionUser!=null)
out.write(generateLikeRow(Stories.get(ctr))+"</tr>");
out.write("<tr><td colspan=\"4\">");
out.println("<br/>"+loadStory(Stories.get(ctr).getFileURL()));
out.write("<hr/></td></tr>");
}/*End of Loop*/
out.write("</table>");
//out.write("</p>");
}catch(IOException ie){}
}
/**This generates an HTML code to be
* Placed in an HTML table
* The row generated shows the number of people who liked
* the story
*/
private String generateLikeRow(Acomplishment myStory){
//User myUser=(User)request.getSession().getAttribute("user");
DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
LikedStoryDAO myLikeDAO=myDAOFactory.createLikeDAO();
String storyID="story"+myStory.getID();
String val="<tr><th>Likes</th><td id=\""+storyID+"\"" +
">"+myLikeDAO.countStoryLikes(myStory.getID())+"</td>";
String btElemName="btStory" +storyID,btIDElemName="id=\""+btElemName+"\"";
if(myLikeDAO.didUserLike(SessionUser.getAccountID(), myStory.getID())){
val=val.concat("<td><button "+btIDElemName+" onclick=\"showNumberOfLikes('"+storyID+"'," +myStory.getID()+","+
"'----','"+btElemName+"')\">" +"Unlike</button></td>");
}
else val=val.concat("<td><button "+btIDElemName+
" onclick=\"showNumberOfLikes('"+storyID+"'," +myStory.getID()+","+"'like','"+btElemName+"')\">" +
"Like</button></td>");
val=val.concat("</tr>");
return val;
}
/**
* Show description of stories made by the user
*/
public void showUserStoryPreviews(User myUser,JspWriter out){
DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
AcomplishmentDAO myAcomDAO=myDAOFactory.createAcomplishmentDAO();
ArrayList<Acomplishment> Stories=(ArrayList<Acomplishment>)myAcomDAO.getAllStoriesOfUser(myUser.getAccountID());
try{
out.write("<table><caption>your stories</caption>");
/*Table header*/
out.write("<tr>");
out.write("<th> Title </th>");
out.write("<th> Time Finished </th>");
out.write("<td>Link</td>");
out.write("</tr>");
/*Loop that shows the story Links*/
for(int ctr=0;ctr<Stories.size();ctr++){
out.write("<tr>");
out.write("<td>"+Stories.get(ctr).getName()+"</td>");
out.write("<td>"+Stories.get(ctr).getFinishTime()+"</td>");
out.write("<td>"+createStoryLink(Stories.get(ctr).getID(), "storyStage")+"</td>");
//out.write("<td>See Story</td>");
out.write("</tr>");
}/*End of Loop*/
out.write("</table>");
}catch(IOException ie){}
}
/**
* Show description of stories made by the user
*/
public void PreviewUserStories(User myUser,JspWriter out){
DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
AcomplishmentDAO myAcomDAO=myDAOFactory.createAcomplishmentDAO();
LikedStoryDAO myLikeDAO=myDAOFactory.createLikeDAO();
ArrayList<Acomplishment> Stories=(ArrayList<Acomplishment>)myAcomDAO.getAllStoriesOfUser(myUser.getAccountID());
String stageID;
try{
/*Loop that shows the story Links*/
for(int ctr=0;ctr<Stories.size();ctr++){
myLikeDAO.countStoryLikes(Stories.get(ctr).getID());
stageID="stage"+Stories.get(ctr).getID();
/*Generate HTML code*/
out.write("<tr align=\"center\">");
out.write("<td>"+Stories.get(ctr).getName()+"</td>");
out.write("<td>50</td>");
out.write("<td>"+Stories.get(ctr).getFinishTime()+"</td>");
out.write("<td>"+myLikeDAO.countStoryLikes(Stories.get(ctr).getID())+"</td>");
out.write("<td>"+createStoryLink(Stories.get(ctr).getID(), stageID)+"</td>");
out.write("</tr>" +
- "<tr><td class=\"hiddenElem\" id=\""+stageID+"\"></td>");
+ "<tr><td class=\"hiddenElem\" id=\""+stageID+"\" colspan='5'></td>");
out.write("</tr>");
}/*End of Loop*/
//out.write("</table>");
}catch(IOException ie){}
}
/**
* Creates a HTML element to Asynchronously get the Story from the server
* @param storyID : The ID of the Accomplishment
* @param stageID : Where the story will be written
* @return
*/
public String createStoryLink(int storyID,String stageID){
String link="<button onclick=\"showStory('"+stageID+"',"+storyID+")\">";
return link.concat("See Story</button>");
}
/*For demo purpose*/
public String loadSampleStory(){
FileInputStream fileIn;
try {
fileIn = new FileInputStream("The introduction of Simba522066365Simba.story");
ObjectInputStream oi = new ObjectInputStream(fileIn);
StoryFileAccess storyFile=(StoryFileAccess)oi.readObject();
fileIn.close();
return previewStory(storyFile);
} catch(IOException ioEx){
return "File path problems D:";
}
catch(Exception ex){
//out.println("Error in getting the story\n"+ex.getMessage());
}
return "Error";
}
}
| true | true | public void PreviewUserStories(User myUser,JspWriter out){
DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
AcomplishmentDAO myAcomDAO=myDAOFactory.createAcomplishmentDAO();
LikedStoryDAO myLikeDAO=myDAOFactory.createLikeDAO();
ArrayList<Acomplishment> Stories=(ArrayList<Acomplishment>)myAcomDAO.getAllStoriesOfUser(myUser.getAccountID());
String stageID;
try{
/*Loop that shows the story Links*/
for(int ctr=0;ctr<Stories.size();ctr++){
myLikeDAO.countStoryLikes(Stories.get(ctr).getID());
stageID="stage"+Stories.get(ctr).getID();
/*Generate HTML code*/
out.write("<tr align=\"center\">");
out.write("<td>"+Stories.get(ctr).getName()+"</td>");
out.write("<td>50</td>");
out.write("<td>"+Stories.get(ctr).getFinishTime()+"</td>");
out.write("<td>"+myLikeDAO.countStoryLikes(Stories.get(ctr).getID())+"</td>");
out.write("<td>"+createStoryLink(Stories.get(ctr).getID(), stageID)+"</td>");
out.write("</tr>" +
"<tr><td class=\"hiddenElem\" id=\""+stageID+"\"></td>");
out.write("</tr>");
}/*End of Loop*/
//out.write("</table>");
}catch(IOException ie){}
}
| public void PreviewUserStories(User myUser,JspWriter out){
DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
AcomplishmentDAO myAcomDAO=myDAOFactory.createAcomplishmentDAO();
LikedStoryDAO myLikeDAO=myDAOFactory.createLikeDAO();
ArrayList<Acomplishment> Stories=(ArrayList<Acomplishment>)myAcomDAO.getAllStoriesOfUser(myUser.getAccountID());
String stageID;
try{
/*Loop that shows the story Links*/
for(int ctr=0;ctr<Stories.size();ctr++){
myLikeDAO.countStoryLikes(Stories.get(ctr).getID());
stageID="stage"+Stories.get(ctr).getID();
/*Generate HTML code*/
out.write("<tr align=\"center\">");
out.write("<td>"+Stories.get(ctr).getName()+"</td>");
out.write("<td>50</td>");
out.write("<td>"+Stories.get(ctr).getFinishTime()+"</td>");
out.write("<td>"+myLikeDAO.countStoryLikes(Stories.get(ctr).getID())+"</td>");
out.write("<td>"+createStoryLink(Stories.get(ctr).getID(), stageID)+"</td>");
out.write("</tr>" +
"<tr><td class=\"hiddenElem\" id=\""+stageID+"\" colspan='5'></td>");
out.write("</tr>");
}/*End of Loop*/
//out.write("</table>");
}catch(IOException ie){}
}
|
diff --git a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java
index 5d71179b..6af514ba 100644
--- a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java
+++ b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java
@@ -1,138 +1,142 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*******************************************************************************/
package org.richfaces.tests.metamer.ftest;
import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guard;
import static org.jboss.test.selenium.locator.LocatorFactory.jq;
import static org.jboss.test.selenium.locator.reference.ReferencedLocator.referenceInferred;
import static org.richfaces.tests.metamer.ftest.AbstractMetamerTest.pjq;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.jboss.test.selenium.dom.Event;
import org.jboss.test.selenium.framework.AjaxSelenium;
import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.Attribute;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.locator.ExtendedLocator;
import org.jboss.test.selenium.locator.JQueryLocator;
import org.jboss.test.selenium.locator.option.OptionValueLocator;
import org.jboss.test.selenium.locator.reference.LocatorReference;
import org.jboss.test.selenium.locator.reference.ReferencedLocator;
import org.jboss.test.selenium.request.RequestType;
/**
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
public class AbstractComponentAttributes {
protected AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
LocatorReference<ExtendedLocator<JQueryLocator>> root = new LocatorReference<ExtendedLocator<JQueryLocator>>(
pjq(""));
ReferencedLocator<JQueryLocator> propertyLocator = referenceInferred(root, "*[id*={0}Input]{1}");
RequestType requestType = RequestType.HTTP;
public AbstractComponentAttributes() {
}
public <T extends ExtendedLocator<JQueryLocator>> AbstractComponentAttributes(T root) {
this.root.setLocator(root);
}
protected String getProperty(String propertyName) {
final ElementLocator<?> locator = propertyLocator.format(propertyName, "");
return selenium.getValue(locator);
}
protected void setProperty(String propertyName, Object value) {
ExtendedLocator<JQueryLocator> locator = propertyLocator.format(propertyName);
final AttributeLocator<?> typeLocator = locator.getAttribute(Attribute.TYPE);
final ExtendedLocator<JQueryLocator> optionLocator = locator.getChild(jq("option"));
String inputType = null;
if (selenium.getCount(propertyLocator.format(propertyName)) > 1) {
inputType = "radio";
} else if (selenium.getCount(optionLocator) > 1) {
inputType = "select";
} else {
inputType = selenium.getAttribute(typeLocator);
}
if (value == null) {
value = "";
}
String valueAsString = value.toString();
if (value.getClass().isEnum()) {
valueAsString = valueAsString.toLowerCase();
valueAsString = WordUtils.capitalizeFully(valueAsString, new char[] { '_' });
valueAsString = valueAsString.replace("_", "");
valueAsString = StringUtils.uncapitalize(valueAsString);
}
if ("text".equals(inputType)) {
applyText(locator, valueAsString);
} else if ("checkbox".equals(inputType)) {
boolean checked = Boolean.valueOf(valueAsString);
applyCheckbox(locator, checked);
} else if ("radio".equals(inputType)) {
locator = propertyLocator.format(propertyName, "[value="
+ ("".equals(valueAsString) ? "null" : valueAsString) + "]");
if (!selenium.isChecked(locator)) {
applyRadio(locator);
}
} else if ("select".equals(inputType)) {
+ String curValue = selenium.getValue(locator);
+ if (valueAsString.equals(curValue)) {
+ return;
+ }
applySelect(locator, valueAsString);
}
}
public void setRequestType(RequestType requestType) {
this.requestType = requestType;
}
public RequestType getRequestType() {
return requestType;
}
protected void applyText(ElementLocator<?> locator, String value) {
guard(selenium, requestType).type(locator, value);
}
protected void applyCheckbox(ElementLocator<?> locator, boolean checked) {
selenium.check(locator, checked);
guard(selenium, requestType).fireEvent(locator, Event.CHANGE);
}
protected void applyRadio(ElementLocator<?> locator) {
guard(selenium, requestType).click(locator);
}
protected void applySelect(ElementLocator<?> locator, String value) {
OptionValueLocator optionLocator = new OptionValueLocator(value);
guard(selenium, requestType).select(locator, optionLocator);
}
}
| true | true | protected void setProperty(String propertyName, Object value) {
ExtendedLocator<JQueryLocator> locator = propertyLocator.format(propertyName);
final AttributeLocator<?> typeLocator = locator.getAttribute(Attribute.TYPE);
final ExtendedLocator<JQueryLocator> optionLocator = locator.getChild(jq("option"));
String inputType = null;
if (selenium.getCount(propertyLocator.format(propertyName)) > 1) {
inputType = "radio";
} else if (selenium.getCount(optionLocator) > 1) {
inputType = "select";
} else {
inputType = selenium.getAttribute(typeLocator);
}
if (value == null) {
value = "";
}
String valueAsString = value.toString();
if (value.getClass().isEnum()) {
valueAsString = valueAsString.toLowerCase();
valueAsString = WordUtils.capitalizeFully(valueAsString, new char[] { '_' });
valueAsString = valueAsString.replace("_", "");
valueAsString = StringUtils.uncapitalize(valueAsString);
}
if ("text".equals(inputType)) {
applyText(locator, valueAsString);
} else if ("checkbox".equals(inputType)) {
boolean checked = Boolean.valueOf(valueAsString);
applyCheckbox(locator, checked);
} else if ("radio".equals(inputType)) {
locator = propertyLocator.format(propertyName, "[value="
+ ("".equals(valueAsString) ? "null" : valueAsString) + "]");
if (!selenium.isChecked(locator)) {
applyRadio(locator);
}
} else if ("select".equals(inputType)) {
applySelect(locator, valueAsString);
}
}
| protected void setProperty(String propertyName, Object value) {
ExtendedLocator<JQueryLocator> locator = propertyLocator.format(propertyName);
final AttributeLocator<?> typeLocator = locator.getAttribute(Attribute.TYPE);
final ExtendedLocator<JQueryLocator> optionLocator = locator.getChild(jq("option"));
String inputType = null;
if (selenium.getCount(propertyLocator.format(propertyName)) > 1) {
inputType = "radio";
} else if (selenium.getCount(optionLocator) > 1) {
inputType = "select";
} else {
inputType = selenium.getAttribute(typeLocator);
}
if (value == null) {
value = "";
}
String valueAsString = value.toString();
if (value.getClass().isEnum()) {
valueAsString = valueAsString.toLowerCase();
valueAsString = WordUtils.capitalizeFully(valueAsString, new char[] { '_' });
valueAsString = valueAsString.replace("_", "");
valueAsString = StringUtils.uncapitalize(valueAsString);
}
if ("text".equals(inputType)) {
applyText(locator, valueAsString);
} else if ("checkbox".equals(inputType)) {
boolean checked = Boolean.valueOf(valueAsString);
applyCheckbox(locator, checked);
} else if ("radio".equals(inputType)) {
locator = propertyLocator.format(propertyName, "[value="
+ ("".equals(valueAsString) ? "null" : valueAsString) + "]");
if (!selenium.isChecked(locator)) {
applyRadio(locator);
}
} else if ("select".equals(inputType)) {
String curValue = selenium.getValue(locator);
if (valueAsString.equals(curValue)) {
return;
}
applySelect(locator, valueAsString);
}
}
|
diff --git a/src/main/java/net/trajano/gasprices/GasPricesWidgetProvider.java b/src/main/java/net/trajano/gasprices/GasPricesWidgetProvider.java
index 133dd26..326cac6 100644
--- a/src/main/java/net/trajano/gasprices/GasPricesWidgetProvider.java
+++ b/src/main/java/net/trajano/gasprices/GasPricesWidgetProvider.java
@@ -1,153 +1,153 @@
package net.trajano.gasprices;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.widget.RemoteViews;
public class GasPricesWidgetProvider extends AppWidgetProvider {
private static Intent getLaunchIntent(final Context context,
final int appWidgetId) {
final PackageManager manager = context.getPackageManager();
final Intent intent = manager
.getLaunchIntentForPackage("net.trajano.gasprices");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setData(new Uri.Builder().path(String.valueOf(appWidgetId))
.build());
return intent;
}
private static void setBlue(final RemoteViews remoteViews) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
remoteViews.setInt(R.id.thelayout, "setBackgroundResource",
R.drawable.myshape);
}
}
private static void setGreen(final RemoteViews remoteViews) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
remoteViews.setInt(R.id.thelayout, "setBackgroundResource",
R.drawable.myshape_green);
}
}
private static void setRed(final RemoteViews remoteViews) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
remoteViews.setInt(R.id.thelayout, "setBackgroundResource",
R.drawable.myshape_red);
}
}
/**
* This will update the app widgets provided that an update is not needed.
* Because if an update is neded then there isn't a point of changing the UI
* until the updates have been completed.
*
* @param context
* @param appWidgetManager
* @param appWidgetId
* @param preferences
* @param remoteViews
*/
public static void updateAppWidget(final Context context,
final AppWidgetManager appWidgetManager, final int appWidgetId,
final PreferenceAdaptor preferences, final RemoteViews remoteViews) {
- if (!preferences.isUpdateNeeded()) {
+ if (preferences.isUpdateNeeded()) {
return;
}
final CityInfo city = preferences.getWidgetCityInfo(appWidgetId);
remoteViews.setTextViewText(R.id.widget_city, city.getName());
remoteViews.setTextViewText(
R.id.widget_price,
context.getResources().getString(R.string.widget_price_format,
city.getCurrentGasPrice()));
setBlue(remoteViews);
if (city.isTomorrowsGasPriceAvailable()) {
if (city.isTomorrowsGasPriceUp()) {
setRed(remoteViews);
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_change_up_format,
city.getPriceDifferenceAbsoluteValue()));
} else if (city.isTomorrowsGasPriceDown()) {
setGreen(remoteViews);
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_change_down_format,
city.getPriceDifferenceAbsoluteValue()));
} else {
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_unchanged));
}
} else {
remoteViews.setTextViewText(R.id.widget_price_change, null);
}
final PendingIntent pendingIntent = PendingIntent.getActivity(context,
appWidgetId, getLaunchIntent(context, appWidgetId), 0);
remoteViews.setOnClickPendingIntent(R.id.thelayout, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
/**
* This will remove all the preferences along with all the
* {@link PendingIntent} associated with the widget.
*/
@Override
public void onDeleted(final Context context, final int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
final PreferenceAdaptor preferences = new PreferenceAdaptor(context);
final PreferenceAdaptorEditor editor = preferences.edit();
editor.removeWidgetCityId(appWidgetIds);
editor.apply();
for (final int appWidgetId : appWidgetIds) {
final PendingIntent pendingIntent = PendingIntent.getActivity(
context, appWidgetId,
getLaunchIntent(context, appWidgetId),
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
pendingIntent.cancel();
}
}
}
@Override
public void onEnabled(final Context context) {
GasPricesUpdateService.scheduleUpdate(context);
}
@Override
public void onUpdate(final Context context,
final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
final RemoteViews remoteViews = new RemoteViews(
context.getPackageName(), R.layout.widget_layout);
final PreferenceAdaptor preferences = new PreferenceAdaptor(context);
for (final int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId,
preferences, remoteViews);
}
if (preferences.isUpdateNeeded()) {
// Build the intent to call the service
final Intent intent = new Intent(context.getApplicationContext(),
GasPricesUpdateService.class);
context.startService(intent);
}
}
}
| true | true | public static void updateAppWidget(final Context context,
final AppWidgetManager appWidgetManager, final int appWidgetId,
final PreferenceAdaptor preferences, final RemoteViews remoteViews) {
if (!preferences.isUpdateNeeded()) {
return;
}
final CityInfo city = preferences.getWidgetCityInfo(appWidgetId);
remoteViews.setTextViewText(R.id.widget_city, city.getName());
remoteViews.setTextViewText(
R.id.widget_price,
context.getResources().getString(R.string.widget_price_format,
city.getCurrentGasPrice()));
setBlue(remoteViews);
if (city.isTomorrowsGasPriceAvailable()) {
if (city.isTomorrowsGasPriceUp()) {
setRed(remoteViews);
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_change_up_format,
city.getPriceDifferenceAbsoluteValue()));
} else if (city.isTomorrowsGasPriceDown()) {
setGreen(remoteViews);
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_change_down_format,
city.getPriceDifferenceAbsoluteValue()));
} else {
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_unchanged));
}
} else {
remoteViews.setTextViewText(R.id.widget_price_change, null);
}
final PendingIntent pendingIntent = PendingIntent.getActivity(context,
appWidgetId, getLaunchIntent(context, appWidgetId), 0);
remoteViews.setOnClickPendingIntent(R.id.thelayout, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
| public static void updateAppWidget(final Context context,
final AppWidgetManager appWidgetManager, final int appWidgetId,
final PreferenceAdaptor preferences, final RemoteViews remoteViews) {
if (preferences.isUpdateNeeded()) {
return;
}
final CityInfo city = preferences.getWidgetCityInfo(appWidgetId);
remoteViews.setTextViewText(R.id.widget_city, city.getName());
remoteViews.setTextViewText(
R.id.widget_price,
context.getResources().getString(R.string.widget_price_format,
city.getCurrentGasPrice()));
setBlue(remoteViews);
if (city.isTomorrowsGasPriceAvailable()) {
if (city.isTomorrowsGasPriceUp()) {
setRed(remoteViews);
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_change_up_format,
city.getPriceDifferenceAbsoluteValue()));
} else if (city.isTomorrowsGasPriceDown()) {
setGreen(remoteViews);
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_change_down_format,
city.getPriceDifferenceAbsoluteValue()));
} else {
remoteViews.setTextViewText(
R.id.widget_price_change,
context.getResources().getString(
R.string.widget_price_unchanged));
}
} else {
remoteViews.setTextViewText(R.id.widget_price_change, null);
}
final PendingIntent pendingIntent = PendingIntent.getActivity(context,
appWidgetId, getLaunchIntent(context, appWidgetId), 0);
remoteViews.setOnClickPendingIntent(R.id.thelayout, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
|
diff --git a/src/research/com/sun/speech/engine/recognition/RuleParser.java b/src/research/com/sun/speech/engine/recognition/RuleParser.java
index 9990eb93..d91fb682 100644
--- a/src/research/com/sun/speech/engine/recognition/RuleParser.java
+++ b/src/research/com/sun/speech/engine/recognition/RuleParser.java
@@ -1,426 +1,424 @@
/**
* Copyright 1998-2003 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*/
package com.sun.speech.engine.recognition;
import javax.speech.recognition.*;
import java.util.*;
/**
* Implementation of the parse method(s) on javax.speech.recognition.RuleGrammar.
*
* @version 1.5 10/27/99 16:33:49
*/
public class RuleParser {
private Recognizer theRec;
/*
* parse a text string against a particular rule from a particluar grammar
* returning a RuleParse data structure is successful and null otherwise
*/
public static RuleParse parse(String text, Recognizer R, RuleGrammar G, String ruleName) {
String inputTokens[] = tokenize(text);
return parse(inputTokens, R, G, ruleName);
}
public static RuleParse parse(String inputTokens[], Recognizer R, RuleGrammar G, String ruleName) {
List<RuleParse> list = mparse(inputTokens, R, G, ruleName);
return list == null ? null : list.get(0);
}
public static List<RuleParse> mparse(String text, Recognizer R, RuleGrammar G, String ruleName) {
String inputTokens[] = tokenize(text);
return mparse(inputTokens, R, G, ruleName);
}
public static List<RuleParse> mparse(String inputTokens[], Recognizer R, RuleGrammar G, String ruleName) {
RuleParser rp = new RuleParser();
rp.theRec = R;
List<RuleParse> res = new ArrayList<RuleParse>();
String[] rNames = ruleName == null ? G.listRuleNames() : new String[] { ruleName };
for (String rName : rNames) {
if (ruleName == null && !G.isEnabled(rName)) {
continue;
}
Rule startRule = G.getRule(rName);
if (startRule == null) {
System.out.println("BAD RULENAME " + rName);
continue;
}
List<tokenPos> p = rp.parse(G, startRule, inputTokens, 0);
if (p != null && !p.isEmpty()) {
for (tokenPos tp : p) {
if (tp.getPos() == inputTokens.length) {
res.add(new RuleParse(new RuleName(rName), (Rule)tp));
}
}
}
}
return res.isEmpty() ? null : res;
}
/*
* parse routine called recursively while traversing the Rule structure
* in a depth first manner. Returns a list of valid parses.
*/
private List<tokenPos> parse(RuleGrammar grammar, Rule r, String[] input, int pos) {
//System.out.println("PARSE " + r.getClass().getName() + ' ' + pos + ' ' + r);
if (r instanceof RuleName)
return parse(grammar, (RuleName)r, input, pos);
if (r instanceof RuleToken)
return parse(grammar, (RuleToken)r, input, pos);
if (r instanceof RuleCount)
return parse(grammar, (RuleCount)r, input, pos);
if (r instanceof RuleTag)
return parse(grammar, (RuleTag)r, input, pos);
if (r instanceof RuleSequence)
return parse(grammar, (RuleSequence)r, input, pos);
if (r instanceof RuleAlternatives)
return parse(grammar, (RuleAlternatives)r, input, pos);
System.out.println("ERROR UNKNOWN OBJECT " + r);
return null;
}
/*
* RULE REFERENCES
*/
private List<tokenPos> parse(RuleGrammar grammar, RuleName rn, String[] input, int pos) {
if (rn.getFullGrammarName() == null) {
rn.setRuleName(grammar.getName() + '.' + rn.getSimpleRuleName());
}
String simpleName = rn.getSimpleRuleName();
if (simpleName.equals("VOID")) return null;
if (simpleName.equals("NULL")) {
List<tokenPos> res = new ArrayList<tokenPos>();
res.add(new jsgfRuleParse(rn, RuleName.NULL, pos));
return res;
}
Rule ruleref = grammar.getRule(simpleName);
if (rn.getFullGrammarName() != grammar.getName()) {
ruleref = null;
}
if (ruleref == null) {
String gname = rn.getFullGrammarName();
//System.out.println("gname=" + gname);
if (gname != null && !gname.isEmpty()) {
RuleGrammar RG1 = theRec.getRuleGrammar(gname);
if (RG1 != null) {
//System.out.println("simpleName=" + simpleName);
ruleref = RG1.getRule(simpleName);
//System.out.println("ruleRef=" + ruleref);
grammar = RG1;
} else {
System.out.println("ERROR: UNKNOWN GRAMMAR " + gname);
//Thread.dumpStack();
}
}
if (ruleref == null) {
System.out.println("ERROR: UNKNOWN RULE NAME " + rn.getRuleName() + ' ' + rn);
//Thread.dumpStack();
return null;
}
}
List<tokenPos> p = parse(grammar, ruleref, input, pos);
if (p == null) {
return null;
}
List<tokenPos> res = new ArrayList<tokenPos>();
for (tokenPos tp : p) {
if (tp instanceof emptyToken) {
res.add(tp);
continue;
}
try {
res.add(new jsgfRuleParse(rn, (Rule)tp, tp.getPos()));
} catch (IllegalArgumentException e) {
System.out.println("ERROR " + e);
}
}
return res;
}
/*
* LITERAL TOKENS
*/
private List<tokenPos> parse(RuleGrammar grammar, RuleToken rt, String[] input, int pos) {
if (pos >= input.length) {
return null;
}
//System.out.println(rt.getText() + " ?= " + input[pos]);
// TODO: what about case sensitivity ??????
String tText = rt.getText().toLowerCase();
if (tText.equals(input[pos]) || (input[pos].equals("%")) || (input[pos].equals("*"))) {
List<tokenPos> res = new ArrayList<tokenPos>();
res.add(new jsgfRuleToken(rt.getText(), pos + 1));
if (input[pos].equals("*")) {
res.add(new jsgfRuleToken(rt.getText(), pos));
}
return res;
} else {
if (tText.indexOf(' ') < 0) {
return null;
}
if (!tText.startsWith(input[pos])) {
return null;
}
String ta[] = tokenize(tText);
int j = 0;
while (true) {
if (j >= ta.length) {
break;
}
if (pos >= input.length) {
return null;
}
if (!ta[j].equals(input[pos])) {
return null;
}
pos++;
j++;
}
List<tokenPos> res = new ArrayList<tokenPos>();
res.add(new jsgfRuleToken(rt.getText(), pos));
return res;
}
}
/*
* ALTERNATIVES
*/
private List<tokenPos> parse(RuleGrammar grammar, RuleAlternatives ra, String[] input, int pos) {
List<tokenPos> res = new ArrayList<tokenPos>();
for (Rule rule : ra.getRules()) {
List<tokenPos> p = parse(grammar, rule, input, pos);
if (p != null)
res.addAll(p);
}
return res;
}
/*
* RULESEQUENCE
*/
private List<tokenPos> parse(RuleGrammar grammar, RuleSequence rs, String[] input, int pos) {
Rule[] rarry = rs.getRules();
if (rarry == null || rarry.length == 0) {
return null;
}
List<tokenPos> p = parse(grammar, rarry[0], input, pos);
if (p == null) {
return null;
}
List<tokenPos> res = new ArrayList<tokenPos>();
//System.out.println("seq sz" + p.size());
for (tokenPos tp : p) {
//System.out.println("seq " + p.get(j));
- Rule rule0 = (Rule)tp;
int nPos = tp.getPos();
if (rarry.length == 1) {
- if (rule0 instanceof emptyToken) {
- res.add((emptyToken)rule0);
+ if (tp instanceof emptyToken) {
+ res.add(tp);
continue;
}
try {
- res.add(new jsgfRuleSequence(new Rule[] { rule0 }, tp.getPos()));
+ res.add(new jsgfRuleSequence(new Rule[] { (Rule)tp }, tp.getPos()));
} catch (IllegalArgumentException e) {
System.out.println(e);
}
continue;
}
Rule[] nra = Arrays.copyOfRange(rarry, 1, rarry.length);
RuleSequence nrs = new RuleSequence(nra);
//System.out.println("2parse " + nPos + nrs);
List<tokenPos> q = parse(grammar, nrs, input, nPos);
if (q == null) {
continue;
}
//System.out.println("2 seq sz " + p.size());
for (tokenPos tp1 : q) {
//System.out.println("2 seq " + q.get(k));
- Rule r1 = (Rule)tp1;
- //System.out.println("rule0 " + rule0);
- //System.out.println("r1 " + r1);
- if (r1 instanceof emptyToken) {
- res.add((emptyToken)rule0);
+ //System.out.println("tp " + tp);
+ //System.out.println("tp1 " + tp1);
+ if (tp1 instanceof emptyToken) {
+ res.add(tp);
continue;
}
- if (rule0 instanceof emptyToken) {
- res.add((emptyToken)r1);
+ if (tp instanceof emptyToken) {
+ res.add(tp1);
continue;
}
Rule[] ra;
- if (r1 instanceof RuleSequence) {
- RuleSequence r2 = (RuleSequence)r1;
+ if (tp1 instanceof RuleSequence) {
+ RuleSequence r2 = (RuleSequence)tp1;
Rule[] r2r = r2.getRules();
ra = new Rule[r2r.length + 1];
- ra[0] = rule0;
+ ra[0] = (Rule)tp;
System.arraycopy(r2r, 0, ra, 1, r2r.length);
} else {
- ra = new Rule[] { rule0, r1 };
+ ra = new Rule[] { (Rule)tp, (Rule)tp1 };
}
try {
res.add(new jsgfRuleSequence(ra, tp1.getPos()));
} catch (IllegalArgumentException e) {
System.out.println(e);
}
}
}
return res;
}
/*
* TAGS
*/
private List<tokenPos> parse(RuleGrammar grammar, RuleTag rtag, String[] input, int pos) {
String theTag = rtag.getTag();
//System.out.println("tag="+theTag);
List<tokenPos> p = parse(grammar, rtag.getRule(), input, pos);
if (p == null) {
return null;
}
List<tokenPos> res = new ArrayList<tokenPos>();
for (tokenPos tp : p) {
if (tp instanceof emptyToken) {
res.add(tp);
continue;
}
res.add(new jsgfRuleTag((Rule)tp, theTag, tp.getPos()));
}
return res;
}
//
// RULECOUNT (e.g. [], *, or + )
//
private List<tokenPos> parse(RuleGrammar grammar, RuleCount rc, String[] input, int pos) {
int rcount = rc.getCount();
emptyToken empty = new emptyToken(pos);
List<tokenPos> p = parse(grammar, rc.getRule(), input, pos);
if (p == null) {
if (rcount == RuleCount.ONCE_OR_MORE) return null;
List<tokenPos> res = new ArrayList<tokenPos>();
res.add(empty);
return res;
}
if (rcount != RuleCount.ONCE_OR_MORE) {
p.add(empty);
}
if (rcount == RuleCount.OPTIONAL) {
return p;
}
for (int m = 2; m <= input.length - pos; m++) {
Rule[] ar = new Rule[m];
Arrays.fill(ar, rc.getRule());
List<tokenPos> q = parse(grammar, new RuleSequence(ar), input, pos);
if (q == null) {
return p;
}
p.addAll(q);
}
return p;
}
/*
* tokenize a string
*/
static String[] tokenize(String text) {
StringTokenizer st = new StringTokenizer(text);
int size = st.countTokens();
String res[] = new String[size];
int i = 0;
while (st.hasMoreTokens()) {
res[i++] = st.nextToken().toLowerCase();
}
return res;
}
/* interface for keeping track of where a token occurs in the
* tokenized input string
*/
interface tokenPos {
public int getPos();
}
/* extension of RuleToken with tokenPos interface */
class jsgfRuleToken extends RuleToken implements tokenPos {
int pos;
public jsgfRuleToken(String x, int pos) {
super(x);
this.pos = pos;
}
public int getPos() {
return pos;
}
}
class emptyToken extends jsgfRuleToken {
public emptyToken(int pos) {
super("EMPTY", pos);
}
}
/* extension of RuleTag with tokenPos interface */
class jsgfRuleTag extends RuleTag implements tokenPos {
int pos;
public jsgfRuleTag(Rule r, String x, int pos) {
super(r, x);
this.pos = pos;
}
public int getPos() {
return pos;
}
}
/* extension of RuleSequence with tokenPos interface */
class jsgfRuleSequence extends RuleSequence implements tokenPos {
int pos;
public jsgfRuleSequence(Rule rules[], int pos) {
super(rules);
this.pos = pos;
}
public int getPos() {
return pos;
}
}
/* extension of RuleParse with tokenPos interface */
class jsgfRuleParse extends RuleParse implements tokenPos {
int pos;
public jsgfRuleParse(RuleName rn, Rule r, int pos) throws IllegalArgumentException {
super(rn, r);
this.pos = pos;
}
public int getPos() {
return pos;
}
}
}
| false | true | private List<tokenPos> parse(RuleGrammar grammar, RuleSequence rs, String[] input, int pos) {
Rule[] rarry = rs.getRules();
if (rarry == null || rarry.length == 0) {
return null;
}
List<tokenPos> p = parse(grammar, rarry[0], input, pos);
if (p == null) {
return null;
}
List<tokenPos> res = new ArrayList<tokenPos>();
//System.out.println("seq sz" + p.size());
for (tokenPos tp : p) {
//System.out.println("seq " + p.get(j));
Rule rule0 = (Rule)tp;
int nPos = tp.getPos();
if (rarry.length == 1) {
if (rule0 instanceof emptyToken) {
res.add((emptyToken)rule0);
continue;
}
try {
res.add(new jsgfRuleSequence(new Rule[] { rule0 }, tp.getPos()));
} catch (IllegalArgumentException e) {
System.out.println(e);
}
continue;
}
Rule[] nra = Arrays.copyOfRange(rarry, 1, rarry.length);
RuleSequence nrs = new RuleSequence(nra);
//System.out.println("2parse " + nPos + nrs);
List<tokenPos> q = parse(grammar, nrs, input, nPos);
if (q == null) {
continue;
}
//System.out.println("2 seq sz " + p.size());
for (tokenPos tp1 : q) {
//System.out.println("2 seq " + q.get(k));
Rule r1 = (Rule)tp1;
//System.out.println("rule0 " + rule0);
//System.out.println("r1 " + r1);
if (r1 instanceof emptyToken) {
res.add((emptyToken)rule0);
continue;
}
if (rule0 instanceof emptyToken) {
res.add((emptyToken)r1);
continue;
}
Rule[] ra;
if (r1 instanceof RuleSequence) {
RuleSequence r2 = (RuleSequence)r1;
Rule[] r2r = r2.getRules();
ra = new Rule[r2r.length + 1];
ra[0] = rule0;
System.arraycopy(r2r, 0, ra, 1, r2r.length);
} else {
ra = new Rule[] { rule0, r1 };
}
try {
res.add(new jsgfRuleSequence(ra, tp1.getPos()));
} catch (IllegalArgumentException e) {
System.out.println(e);
}
}
}
return res;
}
| private List<tokenPos> parse(RuleGrammar grammar, RuleSequence rs, String[] input, int pos) {
Rule[] rarry = rs.getRules();
if (rarry == null || rarry.length == 0) {
return null;
}
List<tokenPos> p = parse(grammar, rarry[0], input, pos);
if (p == null) {
return null;
}
List<tokenPos> res = new ArrayList<tokenPos>();
//System.out.println("seq sz" + p.size());
for (tokenPos tp : p) {
//System.out.println("seq " + p.get(j));
int nPos = tp.getPos();
if (rarry.length == 1) {
if (tp instanceof emptyToken) {
res.add(tp);
continue;
}
try {
res.add(new jsgfRuleSequence(new Rule[] { (Rule)tp }, tp.getPos()));
} catch (IllegalArgumentException e) {
System.out.println(e);
}
continue;
}
Rule[] nra = Arrays.copyOfRange(rarry, 1, rarry.length);
RuleSequence nrs = new RuleSequence(nra);
//System.out.println("2parse " + nPos + nrs);
List<tokenPos> q = parse(grammar, nrs, input, nPos);
if (q == null) {
continue;
}
//System.out.println("2 seq sz " + p.size());
for (tokenPos tp1 : q) {
//System.out.println("2 seq " + q.get(k));
//System.out.println("tp " + tp);
//System.out.println("tp1 " + tp1);
if (tp1 instanceof emptyToken) {
res.add(tp);
continue;
}
if (tp instanceof emptyToken) {
res.add(tp1);
continue;
}
Rule[] ra;
if (tp1 instanceof RuleSequence) {
RuleSequence r2 = (RuleSequence)tp1;
Rule[] r2r = r2.getRules();
ra = new Rule[r2r.length + 1];
ra[0] = (Rule)tp;
System.arraycopy(r2r, 0, ra, 1, r2r.length);
} else {
ra = new Rule[] { (Rule)tp, (Rule)tp1 };
}
try {
res.add(new jsgfRuleSequence(ra, tp1.getPos()));
} catch (IllegalArgumentException e) {
System.out.println(e);
}
}
}
return res;
}
|
diff --git a/src/org/digitalcampus/oppia/utils/HTTPConnectionUtils.java b/src/org/digitalcampus/oppia/utils/HTTPConnectionUtils.java
index 7742cebf..f531fa29 100644
--- a/src/org/digitalcampus/oppia/utils/HTTPConnectionUtils.java
+++ b/src/org/digitalcampus/oppia/utils/HTTPConnectionUtils.java
@@ -1,65 +1,65 @@
package org.digitalcampus.oppia.utils;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.digitalcampus.mobile.learning.R;
import org.digitalcampus.oppia.application.MobileLearning;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;
public class HTTPConnectionUtils extends DefaultHttpClient {
private HttpParams httpParameters;
public HTTPConnectionUtils(Context ctx){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(
httpParameters,
Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
- ctx.getString(R.string.prefServerTimeoutConnection))));
+ ctx.getString(R.string.prefServerTimeoutConnectionDefault))));
HttpConnectionParams.setSoTimeout(
httpParameters,
Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
ctx.getString(R.string.prefServerTimeoutResponseDefault))));
// add user agent
String v = "0";
try {
v = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
super.setParams(httpParameters);
super.getParams().setParameter(CoreProtocolPNames.USER_AGENT, MobileLearning.USER_AGENT + v);
}
public static String createUrlWithCredentials(Context ctx, SharedPreferences prefs, String baseUrl, boolean addServer){
if(addServer){
baseUrl = prefs.getString(ctx.getString(R.string.prefs_server), ctx.getString(R.string.prefServerDefault)) + baseUrl;
}
List<NameValuePair> pairs = new LinkedList<NameValuePair>();
pairs.add(new BasicNameValuePair("username", prefs.getString(ctx.getString(R.string.prefs_username), "")));
pairs.add(new BasicNameValuePair("api_key", prefs.getString(ctx.getString(R.string.prefs_api_key), "")));
pairs.add(new BasicNameValuePair("format", "json"));
String paramString = URLEncodedUtils.format(pairs, "utf-8");
if(!baseUrl.endsWith("?"))
baseUrl += "?";
baseUrl += paramString;
return baseUrl;
}
}
| true | true | public HTTPConnectionUtils(Context ctx){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(
httpParameters,
Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
ctx.getString(R.string.prefServerTimeoutConnection))));
HttpConnectionParams.setSoTimeout(
httpParameters,
Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
ctx.getString(R.string.prefServerTimeoutResponseDefault))));
// add user agent
String v = "0";
try {
v = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
super.setParams(httpParameters);
super.getParams().setParameter(CoreProtocolPNames.USER_AGENT, MobileLearning.USER_AGENT + v);
}
| public HTTPConnectionUtils(Context ctx){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(
httpParameters,
Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
ctx.getString(R.string.prefServerTimeoutConnectionDefault))));
HttpConnectionParams.setSoTimeout(
httpParameters,
Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
ctx.getString(R.string.prefServerTimeoutResponseDefault))));
// add user agent
String v = "0";
try {
v = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
super.setParams(httpParameters);
super.getParams().setParameter(CoreProtocolPNames.USER_AGENT, MobileLearning.USER_AGENT + v);
}
|
diff --git a/lilith/src/main/java/de/huxhorn/lilith/consumers/FileSplitterEventConsumer.java b/lilith/src/main/java/de/huxhorn/lilith/consumers/FileSplitterEventConsumer.java
index eed260c0..213ee9ea 100644
--- a/lilith/src/main/java/de/huxhorn/lilith/consumers/FileSplitterEventConsumer.java
+++ b/lilith/src/main/java/de/huxhorn/lilith/consumers/FileSplitterEventConsumer.java
@@ -1,121 +1,135 @@
/*
* Lilith - a log event viewer.
* Copyright (C) 2007-2009 Joern Huxhorn
*
* 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 de.huxhorn.lilith.consumers;
import de.huxhorn.lilith.data.eventsource.EventWrapper;
import de.huxhorn.lilith.data.eventsource.SourceIdentifier;
import de.huxhorn.lilith.engine.EventConsumer;
import de.huxhorn.lilith.engine.FileBufferFactory;
import de.huxhorn.lilith.engine.SourceManager;
import de.huxhorn.lilith.engine.impl.EventSourceImpl;
import de.huxhorn.sulky.buffers.FileBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class FileSplitterEventConsumer<T extends Serializable>
implements EventConsumer<T>
{
private final Logger logger = LoggerFactory.getLogger(FileSplitterEventConsumer.class);
private FileBufferFactory<T> fileBufferFactory;
private ConcurrentMap<SourceIdentifier, FileBuffer<EventWrapper<T>>> fileBuffers;
private SourceManager<T> sourceManager;
public FileSplitterEventConsumer(FileBufferFactory<T> fileBufferFactory, SourceManager<T> sourceManager)
{
this.fileBufferFactory = fileBufferFactory;
fileBuffers = new ConcurrentHashMap<SourceIdentifier, FileBuffer<EventWrapper<T>>>();
this.sourceManager = sourceManager;
}
public void consume(List<EventWrapper<T>> events)
{
if(events != null && events.size() > 0)
{
Map<SourceIdentifier, List<EventWrapper<T>>> splittedEvents = new HashMap<SourceIdentifier, List<EventWrapper<T>>>();
for(EventWrapper<T> wrapper : events)
{
SourceIdentifier si = wrapper.getSourceIdentifier();
List<EventWrapper<T>> sourceList = splittedEvents.get(si);
if(sourceList == null)
{
sourceList = new ArrayList<EventWrapper<T>>();
splittedEvents.put(si, sourceList);
}
sourceList.add(wrapper);
}
if(logger.isInfoEnabled())
{
logger.info("Split {} events to {} sources.", events.size(), splittedEvents.size());
}
for(Map.Entry<SourceIdentifier, List<EventWrapper<T>>> entry : splittedEvents.entrySet())
{
SourceIdentifier si = entry.getKey();
List<EventWrapper<T>> value = entry.getValue();
int valueCount = value.size();
- // we know that valueCount is > 0 because otherwise it wouldn' exist.
+ // we know that valueCount is > 0 because otherwise it wouldn't exist.
EventWrapper<T> lastEvent = value.get(valueCount - 1);
+ boolean close=false;
+ boolean dontOpen=false;
+ if(lastEvent.getEvent() == null)
+ {
+ close=true;
+ if(valueCount == 1)
+ {
+ dontOpen=true;
+ }
+ }
// only create view/add if valid
- FileBuffer<EventWrapper<T>> buffer = resolveBuffer(si);
- buffer.addAll(value);
- if(logger.isInfoEnabled()) logger.info("Wrote {} events for source '{}'.", valueCount, si);
+ if(!dontOpen)
+ {
+ // resolveBuffer is also creating the view
+ FileBuffer<EventWrapper<T>> buffer = resolveBuffer(si);
+ buffer.addAll(value);
+ if(logger.isInfoEnabled()) logger.info("Wrote {} events for source '{}'.", valueCount, si);
+ }
- if(lastEvent.getEvent() == null)
+ if(close)
{
if(sourceManager != null)
{
sourceManager.removeSource(si);
}
File activeFile = fileBufferFactory.getLogFileFactory().getActiveFile(si);
activeFile.delete();
fileBuffers.remove(si);
}
}
}
}
private FileBuffer<EventWrapper<T>> resolveBuffer(SourceIdentifier si)
{
FileBuffer<EventWrapper<T>> result = fileBuffers.get(si);
if(result == null)
{
result = fileBufferFactory.createActiveBuffer(si);
FileBuffer<EventWrapper<T>> contained = fileBuffers.putIfAbsent(si, result);
if(contained != null)
{
result = contained;
}
else if(sourceManager != null)
{
sourceManager.addSource(new EventSourceImpl<T>(si, result, false));
}
}
return result;
}
}
| false | true | public void consume(List<EventWrapper<T>> events)
{
if(events != null && events.size() > 0)
{
Map<SourceIdentifier, List<EventWrapper<T>>> splittedEvents = new HashMap<SourceIdentifier, List<EventWrapper<T>>>();
for(EventWrapper<T> wrapper : events)
{
SourceIdentifier si = wrapper.getSourceIdentifier();
List<EventWrapper<T>> sourceList = splittedEvents.get(si);
if(sourceList == null)
{
sourceList = new ArrayList<EventWrapper<T>>();
splittedEvents.put(si, sourceList);
}
sourceList.add(wrapper);
}
if(logger.isInfoEnabled())
{
logger.info("Split {} events to {} sources.", events.size(), splittedEvents.size());
}
for(Map.Entry<SourceIdentifier, List<EventWrapper<T>>> entry : splittedEvents.entrySet())
{
SourceIdentifier si = entry.getKey();
List<EventWrapper<T>> value = entry.getValue();
int valueCount = value.size();
// we know that valueCount is > 0 because otherwise it wouldn' exist.
EventWrapper<T> lastEvent = value.get(valueCount - 1);
// only create view/add if valid
FileBuffer<EventWrapper<T>> buffer = resolveBuffer(si);
buffer.addAll(value);
if(logger.isInfoEnabled()) logger.info("Wrote {} events for source '{}'.", valueCount, si);
if(lastEvent.getEvent() == null)
{
if(sourceManager != null)
{
sourceManager.removeSource(si);
}
File activeFile = fileBufferFactory.getLogFileFactory().getActiveFile(si);
activeFile.delete();
fileBuffers.remove(si);
}
}
}
}
| public void consume(List<EventWrapper<T>> events)
{
if(events != null && events.size() > 0)
{
Map<SourceIdentifier, List<EventWrapper<T>>> splittedEvents = new HashMap<SourceIdentifier, List<EventWrapper<T>>>();
for(EventWrapper<T> wrapper : events)
{
SourceIdentifier si = wrapper.getSourceIdentifier();
List<EventWrapper<T>> sourceList = splittedEvents.get(si);
if(sourceList == null)
{
sourceList = new ArrayList<EventWrapper<T>>();
splittedEvents.put(si, sourceList);
}
sourceList.add(wrapper);
}
if(logger.isInfoEnabled())
{
logger.info("Split {} events to {} sources.", events.size(), splittedEvents.size());
}
for(Map.Entry<SourceIdentifier, List<EventWrapper<T>>> entry : splittedEvents.entrySet())
{
SourceIdentifier si = entry.getKey();
List<EventWrapper<T>> value = entry.getValue();
int valueCount = value.size();
// we know that valueCount is > 0 because otherwise it wouldn't exist.
EventWrapper<T> lastEvent = value.get(valueCount - 1);
boolean close=false;
boolean dontOpen=false;
if(lastEvent.getEvent() == null)
{
close=true;
if(valueCount == 1)
{
dontOpen=true;
}
}
// only create view/add if valid
if(!dontOpen)
{
// resolveBuffer is also creating the view
FileBuffer<EventWrapper<T>> buffer = resolveBuffer(si);
buffer.addAll(value);
if(logger.isInfoEnabled()) logger.info("Wrote {} events for source '{}'.", valueCount, si);
}
if(close)
{
if(sourceManager != null)
{
sourceManager.removeSource(si);
}
File activeFile = fileBufferFactory.getLogFileFactory().getActiveFile(si);
activeFile.delete();
fileBuffers.remove(si);
}
}
}
}
|
diff --git a/src/main/java/net/preoccupied/bukkit/want/WantPlugin.java b/src/main/java/net/preoccupied/bukkit/want/WantPlugin.java
index 1fe9725..a378007 100644
--- a/src/main/java/net/preoccupied/bukkit/want/WantPlugin.java
+++ b/src/main/java/net/preoccupied/bukkit/want/WantPlugin.java
@@ -1,299 +1,298 @@
package net.preoccupied.bukkit.want;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.TreeMap;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import org.bukkit.util.config.ConfigurationNode;
import net.preoccupied.bukkit.ItemUtils;
import net.preoccupied.bukkit.PluginConfiguration;
import net.preoccupied.bukkit.permissions.PermissionCheck;
import net.preoccupied.bukkit.permissions.PermissionCommand;
public class WantPlugin extends JavaPlugin {
private Map<String,ItemData> items;
private Map<String,PackData> packs;
private Map<Integer,List<ItemData>> items_by_id;
public void onEnable() {
setupCommands();
}
public void onDisable() {
;
}
public void onLoad() {
/* item data */
this.items = new HashMap<String,ItemData>();
this.items_by_id = new TreeMap<Integer,List<ItemData>>();
Configuration conf = null;
try {
conf = PluginConfiguration.load(this, this.getFile(), "items.yml");
} catch(IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
return;
}
for(ConfigurationNode node : conf.getNodeList("items", null)) {
int id = node.getInt("id", 0);
List<ItemData> idata = loadItemData(id, node);
this.items_by_id.put(id, idata);
for(ItemData item : idata) {
for(String alias : item.aliases) {
alias = alias_transform(alias);
- System.out.println(" alias: " + alias);
this.items.put(alias, item);
}
}
}
/* we aren't going to bother storing groups, we'll just attach
it as auxillary data to items in their membership */
for(ConfigurationNode node: conf.getNodeList("groups", null)) {
String name = node.getString("name", "undefined");
int stack = node.getInt("stack", 1);
for(int id : node.getIntList("items", null)) {
List<ItemData> found = items_by_id.get(id);
if(found == null)
continue;
for(ItemData i : found) {
i.group = name;
i.stack = stack;
}
}
}
System.out.println("loaded " + this.items_by_id.size() + " item IDs for Want");
System.out.println("loaded " + this.items.size() + " item aliases for Want");
/* pack data */
this.packs = new HashMap<String,PackData>();
try {
conf = PluginConfiguration.load(this, this.getFile(), "packs.yml");
} catch(IOException ioe) {
System.out.println(ioe);
return;
}
for(ConfigurationNode node : conf.getNodeList("packs", null)) {
String name = node.getString("name", null);
PackData pack = new PackData(name);
pack.title = node.getString("title", name);
pack.message = node.getString("message", null);
for(ConfigurationNode itemnode : node.getNodeList("items", null)) {
int id = itemnode.getInt("id", 0);
int type = itemnode.getInt("type", 0);
int count = itemnode.getInt("count", 1);
if(id > 0 && count > 0) {
pack.addItem(id, type, count);
}
}
this.packs.put(name, pack);
}
System.out.println("loaded " + this.packs.size() + " packs for Want");
}
private static String alias_transform(String alias) {
alias = alias.replaceAll("\\s", "");
alias = alias.toLowerCase();
return alias;
}
private static List<ItemData> loadItemData(int id, ConfigurationNode node) {
List<String> names = node.getStringList("name", null);
if(id == 0 || names == null || names.isEmpty()) {
return Collections.emptyList();
}
List<ItemData> items = new ArrayList<ItemData>(1);
ItemData zerotype = new ItemData(id, names);
items.add(zerotype);
for(ConfigurationNode typenode : node.getNodeList("types", null)) {
int typeid = typenode.getInt("type", 0);
names = typenode.getStringList("name", null);
if(names == null || names.isEmpty())
continue;
if(typeid == 0) {
zerotype.aliases.addAll(names);
} else {
ItemData ti = new ItemData(id, names);
ti.type = typeid;
items.add(ti);
}
}
return items;
}
public ItemData getItem(String by_name) {
if(by_name == null) return null;
return this.items.get(alias_transform(by_name));
}
public ItemData getItem(int by_id, int and_type) {
List<ItemData> items = this.items_by_id.get(by_id);
if(items == null) return null;
for(ItemData i : items) {
if(i.type == and_type) {
return i;
}
}
return null;
}
public ItemData getItem(int by_id) {
return getItem(by_id, 0);
}
public PackData getPack(String by_name) {
return packs.get(by_name);
}
private void setupCommands() {
new PermissionCommand(this, "want") {
public boolean run(Player player, String itemname) {
ItemData item = getItem(itemname);
if(item == null) {
msg(player, "I don't know what that is: " + itemname);
return true;
}
if(! item.permitted(player)) {
msg(player, "You are not permitted to spawn that: " + itemname);
return true;
}
ItemUtils.spawnItem(player, item.id, (short) item.type, item.stack);
return true;
}
};
new PermissionCommand(this, "grant") {
public boolean run(Player player, String recipient, String itemname) {
ItemData item = getItem(itemname);
if(item == null) {
msg(player, "Unknown item: " + itemname);
return true;
}
if(! item.permitted(player)) {
msg(player, "You are not permitted to spawn that: " + itemname);
return true;
}
Player friend = Bukkit.getServer().getPlayer(recipient);
if(friend == null || ! friend.isOnline()) {
msg(player, "Your friend is not online: " + recipient);
return true;
}
ItemUtils.spawnItem(friend, item.id, (short) item.type, item.stack);
return true;
}
};
new PermissionCommand(this, "pack") {
public boolean run(Player player, String recipient, String packname) {
PackData pack = getPack(packname);
if(pack == null) {
msg(player, "Unknown pack: " + packname);
return true;
}
Player friend;
if(recipient.equals("me")) {
friend = player;
} else {
friend = Bukkit.getServer().getPlayer(recipient);
}
if(friend == null || ! friend.isOnline()) {
msg(player, "Your friend is not online: " + recipient);
return true;
}
for(PackData.PackItem i : pack.items) {
ItemUtils.spawnItem(friend, i.id, (short) i.type, i.count);
}
if(pack.message != null) {
msg(friend, pack.message);
} else {
msg(friend, "You've received " + pack.title);
}
return true;
}
};
}
}
/* The end. */
| true | true | public void onLoad() {
/* item data */
this.items = new HashMap<String,ItemData>();
this.items_by_id = new TreeMap<Integer,List<ItemData>>();
Configuration conf = null;
try {
conf = PluginConfiguration.load(this, this.getFile(), "items.yml");
} catch(IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
return;
}
for(ConfigurationNode node : conf.getNodeList("items", null)) {
int id = node.getInt("id", 0);
List<ItemData> idata = loadItemData(id, node);
this.items_by_id.put(id, idata);
for(ItemData item : idata) {
for(String alias : item.aliases) {
alias = alias_transform(alias);
System.out.println(" alias: " + alias);
this.items.put(alias, item);
}
}
}
/* we aren't going to bother storing groups, we'll just attach
it as auxillary data to items in their membership */
for(ConfigurationNode node: conf.getNodeList("groups", null)) {
String name = node.getString("name", "undefined");
int stack = node.getInt("stack", 1);
for(int id : node.getIntList("items", null)) {
List<ItemData> found = items_by_id.get(id);
if(found == null)
continue;
for(ItemData i : found) {
i.group = name;
i.stack = stack;
}
}
}
System.out.println("loaded " + this.items_by_id.size() + " item IDs for Want");
System.out.println("loaded " + this.items.size() + " item aliases for Want");
/* pack data */
this.packs = new HashMap<String,PackData>();
try {
conf = PluginConfiguration.load(this, this.getFile(), "packs.yml");
} catch(IOException ioe) {
System.out.println(ioe);
return;
}
for(ConfigurationNode node : conf.getNodeList("packs", null)) {
String name = node.getString("name", null);
PackData pack = new PackData(name);
pack.title = node.getString("title", name);
pack.message = node.getString("message", null);
for(ConfigurationNode itemnode : node.getNodeList("items", null)) {
int id = itemnode.getInt("id", 0);
int type = itemnode.getInt("type", 0);
int count = itemnode.getInt("count", 1);
if(id > 0 && count > 0) {
pack.addItem(id, type, count);
}
}
this.packs.put(name, pack);
}
System.out.println("loaded " + this.packs.size() + " packs for Want");
}
| public void onLoad() {
/* item data */
this.items = new HashMap<String,ItemData>();
this.items_by_id = new TreeMap<Integer,List<ItemData>>();
Configuration conf = null;
try {
conf = PluginConfiguration.load(this, this.getFile(), "items.yml");
} catch(IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
return;
}
for(ConfigurationNode node : conf.getNodeList("items", null)) {
int id = node.getInt("id", 0);
List<ItemData> idata = loadItemData(id, node);
this.items_by_id.put(id, idata);
for(ItemData item : idata) {
for(String alias : item.aliases) {
alias = alias_transform(alias);
this.items.put(alias, item);
}
}
}
/* we aren't going to bother storing groups, we'll just attach
it as auxillary data to items in their membership */
for(ConfigurationNode node: conf.getNodeList("groups", null)) {
String name = node.getString("name", "undefined");
int stack = node.getInt("stack", 1);
for(int id : node.getIntList("items", null)) {
List<ItemData> found = items_by_id.get(id);
if(found == null)
continue;
for(ItemData i : found) {
i.group = name;
i.stack = stack;
}
}
}
System.out.println("loaded " + this.items_by_id.size() + " item IDs for Want");
System.out.println("loaded " + this.items.size() + " item aliases for Want");
/* pack data */
this.packs = new HashMap<String,PackData>();
try {
conf = PluginConfiguration.load(this, this.getFile(), "packs.yml");
} catch(IOException ioe) {
System.out.println(ioe);
return;
}
for(ConfigurationNode node : conf.getNodeList("packs", null)) {
String name = node.getString("name", null);
PackData pack = new PackData(name);
pack.title = node.getString("title", name);
pack.message = node.getString("message", null);
for(ConfigurationNode itemnode : node.getNodeList("items", null)) {
int id = itemnode.getInt("id", 0);
int type = itemnode.getInt("type", 0);
int count = itemnode.getInt("count", 1);
if(id > 0 && count > 0) {
pack.addItem(id, type, count);
}
}
this.packs.put(name, pack);
}
System.out.println("loaded " + this.packs.size() + " packs for Want");
}
|
diff --git a/alchemy-core/src/alchemy/libs/LibComm2.java b/alchemy-core/src/alchemy/libs/LibComm2.java
index ab89f2b..0b0bedd 100644
--- a/alchemy-core/src/alchemy/libs/LibComm2.java
+++ b/alchemy-core/src/alchemy/libs/LibComm2.java
@@ -1,73 +1,73 @@
/*
* This file is a part of Alchemy OS project.
* Copyright (C) 2011-2013, Sergey Basalaev <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package alchemy.libs;
import alchemy.system.NativeLibrary;
import alchemy.system.Process;
import alchemy.types.Int32;
import alchemy.util.Strings;
import java.io.IOException;
import javax.microedition.io.CommConnection;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
/**
* Serial port library for Alchemy OS.
* @author Sergey Basalaev
* @version 2.0
*/
public class LibComm2 extends NativeLibrary {
public LibComm2() throws IOException {
load("/symbols/comm2");
name = "libcomm.2.so";
}
protected Object invokeNative(int index, Process p, Object[] args) throws Exception {
switch (index) {
case 0: { // listCommPorts(): [String]
String ports = System.getProperty("microedition.commports");
if (ports == null) ports = "";
return Strings.split(ports, ',', false);
}
case 1: { // Comm.new(port: String, cfg: CommCfg): Comm
- StringBuffer url = new StringBuffer("comm://");
+ StringBuffer url = new StringBuffer("comm:");
url.append((String)args[0]);
Object[] params = (Object[])args[1];
if (params[0] != Int32.ZERO) url.append(";baudrate=").append(ival(params[0]));
if (params[1] != null) url.append(";bitsperchar=").append(ival(params[1]));
if (params[2] != null) url.append(";stopbits=").append(ival(params[2]));
if (params[3] != null) url.append(";parity=").append((String)params[3]);
if (params[4] != null) url.append(";blocking=").append(bval(params[4]) ? "on" : "off");
if (params[5] != null) url.append(";autocts=").append(bval(params[5]) ? "on" : "off");
if (params[6] != null) url.append(";autorts=").append(bval(params[6]) ? "on" : "off");
Connection conn = Connector.open(url.toString());
p.addConnection(conn);
return conn;
}
case 2: // Comm.getBaudRate(): Int
return Ival(((CommConnection)args[0]).getBaudRate());
case 3: // Comm.setBaudRate(baudrate: Int)
((CommConnection)args[0]).setBaudRate(ival(args[1]));
return null;
default:
return null;
}
}
}
| true | true | protected Object invokeNative(int index, Process p, Object[] args) throws Exception {
switch (index) {
case 0: { // listCommPorts(): [String]
String ports = System.getProperty("microedition.commports");
if (ports == null) ports = "";
return Strings.split(ports, ',', false);
}
case 1: { // Comm.new(port: String, cfg: CommCfg): Comm
StringBuffer url = new StringBuffer("comm://");
url.append((String)args[0]);
Object[] params = (Object[])args[1];
if (params[0] != Int32.ZERO) url.append(";baudrate=").append(ival(params[0]));
if (params[1] != null) url.append(";bitsperchar=").append(ival(params[1]));
if (params[2] != null) url.append(";stopbits=").append(ival(params[2]));
if (params[3] != null) url.append(";parity=").append((String)params[3]);
if (params[4] != null) url.append(";blocking=").append(bval(params[4]) ? "on" : "off");
if (params[5] != null) url.append(";autocts=").append(bval(params[5]) ? "on" : "off");
if (params[6] != null) url.append(";autorts=").append(bval(params[6]) ? "on" : "off");
Connection conn = Connector.open(url.toString());
p.addConnection(conn);
return conn;
}
case 2: // Comm.getBaudRate(): Int
return Ival(((CommConnection)args[0]).getBaudRate());
case 3: // Comm.setBaudRate(baudrate: Int)
((CommConnection)args[0]).setBaudRate(ival(args[1]));
return null;
default:
return null;
}
}
| protected Object invokeNative(int index, Process p, Object[] args) throws Exception {
switch (index) {
case 0: { // listCommPorts(): [String]
String ports = System.getProperty("microedition.commports");
if (ports == null) ports = "";
return Strings.split(ports, ',', false);
}
case 1: { // Comm.new(port: String, cfg: CommCfg): Comm
StringBuffer url = new StringBuffer("comm:");
url.append((String)args[0]);
Object[] params = (Object[])args[1];
if (params[0] != Int32.ZERO) url.append(";baudrate=").append(ival(params[0]));
if (params[1] != null) url.append(";bitsperchar=").append(ival(params[1]));
if (params[2] != null) url.append(";stopbits=").append(ival(params[2]));
if (params[3] != null) url.append(";parity=").append((String)params[3]);
if (params[4] != null) url.append(";blocking=").append(bval(params[4]) ? "on" : "off");
if (params[5] != null) url.append(";autocts=").append(bval(params[5]) ? "on" : "off");
if (params[6] != null) url.append(";autorts=").append(bval(params[6]) ? "on" : "off");
Connection conn = Connector.open(url.toString());
p.addConnection(conn);
return conn;
}
case 2: // Comm.getBaudRate(): Int
return Ival(((CommConnection)args[0]).getBaudRate());
case 3: // Comm.setBaudRate(baudrate: Int)
((CommConnection)args[0]).setBaudRate(ival(args[1]));
return null;
default:
return null;
}
}
|
diff --git a/modules/web/src/main/java/org/torquebox/web/servlet/RackFilter.java b/modules/web/src/main/java/org/torquebox/web/servlet/RackFilter.java
index a6b9b7774..92dacb492 100644
--- a/modules/web/src/main/java/org/torquebox/web/servlet/RackFilter.java
+++ b/modules/web/src/main/java/org/torquebox/web/servlet/RackFilter.java
@@ -1,158 +1,159 @@
/*
* Copyright 2008-2013 Red Hat, Inc, and individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.torquebox.web.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.core.ApplicationFilterChain;
import org.jboss.logging.Logger;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jruby.Ruby;
import org.jruby.exceptions.RaiseException;
import org.projectodd.polyglot.web.servlet.HttpServletResponseCapture;
import org.torquebox.core.component.ComponentResolver;
import org.torquebox.core.runtime.RubyRuntimePool;
import org.torquebox.web.component.RackApplicationComponent;
import org.torquebox.web.rack.RackEnvironment;
import org.torquebox.web.rack.processors.RackWebApplicationInstaller;
public class RackFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
ServiceRegistry registry = (ServiceRegistry) filterConfig.getServletContext().getAttribute( "service.registry" );
ServiceName componentResolverServiceName = (ServiceName) filterConfig.getServletContext().getAttribute( "component.resolver.service-name" );
this.componentResolver = (ComponentResolver) registry.getService( componentResolverServiceName ).getValue();
if (this.componentResolver == null) {
throw new ServletException( "Unable to obtain Rack component resolver: " + componentResolverServiceName );
}
ServiceName runtimePoolServiceName = (ServiceName) filterConfig.getServletContext().getAttribute( "runtime.pool.service-name" );
this.runtimePool = (RubyRuntimePool) registry.getService( runtimePoolServiceName ).getValue();
if (this.runtimePool == null) {
throw new ServletException( "Unable to obtain runtime pool: " + runtimePoolServiceName );
}
this.servletContext = filterConfig.getServletContext();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
doFilter( (HttpServletRequest) request, (HttpServletResponse) response, chain );
}
}
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (((request.getPathInfo() == null) || (request.getPathInfo().equals( "/" ))) && !(request.getRequestURI().endsWith( "/" ))) {
String redirectUri = request.getRequestURI() + "/";
String queryString = request.getQueryString();
if (queryString != null) {
redirectUri = redirectUri + "?" + queryString;
}
redirectUri = response.encodeRedirectURL( redirectUri );
response.sendRedirect( redirectUri );
return;
}
String servletName = "";
try {
servletName = ((ApplicationFilterChain) chain).getServlet().getServletConfig().getServletName();
} catch (Exception e) {
- log.error(e);
+ // If we can't fetch the name, we can be pretty sure it's not one of our servlets, in which case it really
+ // doesn't matter what the name is.
}
if (servletName.equals(RackWebApplicationInstaller.FIVE_HUNDRED_SERVLET_NAME) ||
servletName.equals(RackWebApplicationInstaller.STATIC_RESROUCE_SERVLET_NAME)) {
// Only hand off requests to Rack if they're handled by one of the
// TorqueBox servlets
HttpServletResponseCapture responseCapture = new HttpServletResponseCapture( response );
try {
chain.doFilter( request, responseCapture );
if (responseCapture.isError()) {
response.reset();
} else if (!request.getMethod().equals( "OPTIONS" )) {
// Pass HTTP OPTIONS requests through to the Rack application
return;
}
} catch (ServletException e) {
log.error( "Error performing request", e );
}
doRack( request, response );
} else {
// Bypass our Rack stack entirely for any servlets defined in a
// user's WEB-INF/web.xml
chain.doFilter( request, response );
}
}
protected void doRack(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
RackEnvironment rackEnv = null;
Ruby runtime = null;
RackApplicationComponent rackApp;
try {
runtime = this.runtimePool.borrowRuntime( "rack" );
rackApp = (RackApplicationComponent) this.componentResolver.resolve( runtime );
rackEnv = new RackEnvironment( runtime, servletContext, request );
rackApp.call( rackEnv ).respond( response );
} catch (RaiseException e) {
log.error( "Error invoking Rack filter", e );
log.error( "Underlying Ruby exception", e.getCause() );
throw new ServletException( e );
} catch (Exception e) {
log.error( "Error invoking Rack filter", e );
throw new ServletException( e );
} finally {
if (rackEnv != null) {
rackEnv.close();
}
if (runtime != null) {
this.runtimePool.returnRuntime( runtime );
}
}
}
private static final Logger log = Logger.getLogger( RackFilter.class );
public static final String RACK_APP_DEPLOYMENT_INIT_PARAM = "torquebox.rack.app.deployment.name";
private ComponentResolver componentResolver;
private RubyRuntimePool runtimePool;
private ServletContext servletContext;
}
| true | true | protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (((request.getPathInfo() == null) || (request.getPathInfo().equals( "/" ))) && !(request.getRequestURI().endsWith( "/" ))) {
String redirectUri = request.getRequestURI() + "/";
String queryString = request.getQueryString();
if (queryString != null) {
redirectUri = redirectUri + "?" + queryString;
}
redirectUri = response.encodeRedirectURL( redirectUri );
response.sendRedirect( redirectUri );
return;
}
String servletName = "";
try {
servletName = ((ApplicationFilterChain) chain).getServlet().getServletConfig().getServletName();
} catch (Exception e) {
log.error(e);
}
if (servletName.equals(RackWebApplicationInstaller.FIVE_HUNDRED_SERVLET_NAME) ||
servletName.equals(RackWebApplicationInstaller.STATIC_RESROUCE_SERVLET_NAME)) {
// Only hand off requests to Rack if they're handled by one of the
// TorqueBox servlets
HttpServletResponseCapture responseCapture = new HttpServletResponseCapture( response );
try {
chain.doFilter( request, responseCapture );
if (responseCapture.isError()) {
response.reset();
} else if (!request.getMethod().equals( "OPTIONS" )) {
// Pass HTTP OPTIONS requests through to the Rack application
return;
}
} catch (ServletException e) {
log.error( "Error performing request", e );
}
doRack( request, response );
} else {
// Bypass our Rack stack entirely for any servlets defined in a
// user's WEB-INF/web.xml
chain.doFilter( request, response );
}
}
| protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (((request.getPathInfo() == null) || (request.getPathInfo().equals( "/" ))) && !(request.getRequestURI().endsWith( "/" ))) {
String redirectUri = request.getRequestURI() + "/";
String queryString = request.getQueryString();
if (queryString != null) {
redirectUri = redirectUri + "?" + queryString;
}
redirectUri = response.encodeRedirectURL( redirectUri );
response.sendRedirect( redirectUri );
return;
}
String servletName = "";
try {
servletName = ((ApplicationFilterChain) chain).getServlet().getServletConfig().getServletName();
} catch (Exception e) {
// If we can't fetch the name, we can be pretty sure it's not one of our servlets, in which case it really
// doesn't matter what the name is.
}
if (servletName.equals(RackWebApplicationInstaller.FIVE_HUNDRED_SERVLET_NAME) ||
servletName.equals(RackWebApplicationInstaller.STATIC_RESROUCE_SERVLET_NAME)) {
// Only hand off requests to Rack if they're handled by one of the
// TorqueBox servlets
HttpServletResponseCapture responseCapture = new HttpServletResponseCapture( response );
try {
chain.doFilter( request, responseCapture );
if (responseCapture.isError()) {
response.reset();
} else if (!request.getMethod().equals( "OPTIONS" )) {
// Pass HTTP OPTIONS requests through to the Rack application
return;
}
} catch (ServletException e) {
log.error( "Error performing request", e );
}
doRack( request, response );
} else {
// Bypass our Rack stack entirely for any servlets defined in a
// user's WEB-INF/web.xml
chain.doFilter( request, response );
}
}
|
diff --git a/src/main/java/org/jboss/aerogear/connectivity/rest/registry/applications/InstallationManagementEndpoint.java b/src/main/java/org/jboss/aerogear/connectivity/rest/registry/applications/InstallationManagementEndpoint.java
index 35ce5759..71634b4b 100644
--- a/src/main/java/org/jboss/aerogear/connectivity/rest/registry/applications/InstallationManagementEndpoint.java
+++ b/src/main/java/org/jboss/aerogear/connectivity/rest/registry/applications/InstallationManagementEndpoint.java
@@ -1,111 +1,111 @@
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* 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.jboss.aerogear.connectivity.rest.registry.applications;
import org.jboss.aerogear.connectivity.api.Variant;
import org.jboss.aerogear.connectivity.model.InstallationImpl;
import org.jboss.aerogear.connectivity.service.ClientInstallationService;
import org.jboss.aerogear.connectivity.service.GenericVariantService;
import org.jboss.aerogear.security.authz.Secure;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Stateless
@TransactionAttribute
@Path("/applications/{variantID}/installations/")
@Secure("developer")
public class InstallationManagementEndpoint {
@Inject
private GenericVariantService genericVariantService;
@Inject
private ClientInstallationService clientInstallationService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response findInstallations(@PathParam("variantID") String variantId){
//Find the variant using the variantID
Variant variant = genericVariantService.findByVariantID(variantId);
if(variant == null){
return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Variant").build();
}
return Response.ok(variant.getInstallations()).build();
}
@GET
@Path("/{installationID}")
@Produces(MediaType.APPLICATION_JSON)
public Response findInstallation(@PathParam("variantID") String variantId, @PathParam("installationID") String installationId){
InstallationImpl installation = clientInstallationService.findById(installationId);
if(installation == null){
return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build();
}
return Response.ok(installation).build();
}
@PUT
@Path("/{installationID}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateInstallation(InstallationImpl entity, @PathParam("variantID") String variantId, @PathParam("installationID") String installationId){
InstallationImpl installation = clientInstallationService.findById(installationId);
if(installation == null){
return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build();
}
- clientInstallationService.updateInstallation(entity, installation);
+ clientInstallationService.updateInstallation(installation, entity);
return Response.noContent().build();
}
@DELETE
@Path("/{installationID}")
@Consumes(MediaType.APPLICATION_JSON)
public Response removeInstallation(@PathParam("variantID") String variantId, @PathParam("installationID") String installationId){
InstallationImpl installation = clientInstallationService.findById(installationId);
if(installation == null){
return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build();
}
// remove it
clientInstallationService.removeInstallation(installation);
return Response.noContent().build();
}
}
| true | true | public Response updateInstallation(InstallationImpl entity, @PathParam("variantID") String variantId, @PathParam("installationID") String installationId){
InstallationImpl installation = clientInstallationService.findById(installationId);
if(installation == null){
return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build();
}
clientInstallationService.updateInstallation(entity, installation);
return Response.noContent().build();
}
| public Response updateInstallation(InstallationImpl entity, @PathParam("variantID") String variantId, @PathParam("installationID") String installationId){
InstallationImpl installation = clientInstallationService.findById(installationId);
if(installation == null){
return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Installation").build();
}
clientInstallationService.updateInstallation(installation, entity);
return Response.noContent().build();
}
|
diff --git a/src/agents/KitStand.java b/src/agents/KitStand.java
index e1b0b81..02a7d95 100644
--- a/src/agents/KitStand.java
+++ b/src/agents/KitStand.java
@@ -1,198 +1,201 @@
package agents;
import agents.*;
import agents.include.*;
import agents.interfaces.*;
import java.util.*;
public class KitStand {
/*** Data Structures **/
private int capacity;
private int count;
private int completeKits;
//public List<Kit> kits;
public Kit[] kits;
private InspectionStand inspection;
private boolean inspecting = false;
class InspectionStand {
Kit kit;
public InspectionStand() { }
synchronized public void placeOnInspection(Kit k)
{
kit = k;
}
synchronized public Kit inspectKit()
{
return kit;
}
synchronized public Kit removeFromInspection()
{
Kit k = kit;
kit = null;
return k;
}
}
/*** Constructor **/
public KitStand()
{
capacity = 2;
completeKits = 0;
count = 0;
//kits = new ArrayList<Kit>();
kits = new Kit[2];
inspection = new InspectionStand();
}
/*** Actions ***/
synchronized public void insertEmptyKit(Kit emptyKit) {
kits[count] = emptyKit;
count++;
}
synchronized public List<Map<String, Integer>> getPartConfig() {
List<Map<String, Integer>> configs = new ArrayList<Map<String, Integer>>();
if(kits[0] != null) configs.add(kits[0].config);
if(kits[1] != null) configs.add(kits[1].config);
return configs;
}
// called by PartRobot
synchronized public Map<Part, Integer> insertPartsIntoKits(List<Part> send) {
Map<Part, Integer> parts = new HashMap<Part,Integer>();
for(Part p: send)
{
String type = p.getPartName();
if(kits[0]!=null && kits[0].config.containsKey(type))
{
int zero_num = kits[0].config.get(type);
int zero_count = 0;
for(Part zero_p : kits[0].parts)
{
if(zero_p.getPartName().equals(type)) zero_count++;
}
if(zero_count < zero_num)
{
kits[0].parts.add(p);
parts.put(p,0);
}
else
{
kits[1].parts.add(p);
parts.put(p,1);
}
}
else
{
kits[1].parts.add(p);
parts.put(p,1);
}
}
int complete0 = 1;
- for (String key : kits[0].config.keySet())
+ if(kits[0]!=null)
{
- int num = kits[0].config.get(key);
- int count = 0;
- for(Part p : kits[0].parts)
+ for (String key : kits[0].config.keySet())
{
- if(p.getPartName().equals(key)) count ++;
- }
- if(count < num)
- {
- complete0 = 0;
- break;
- }
+ int num = kits[0].config.get(key);
+ int count = 0;
+ for(Part p : kits[0].parts)
+ {
+ if(p.getPartName().equals(key)) count ++;
+ }
+ if(count < num)
+ {
+ complete0 = 0;
+ break;
+ }
+ }
}
int complete1 = 1;
if(kits[1]!=null)
{
for (String key : kits[1].config.keySet())
{
int num = kits[1].config.get(key);
int count = 0;
for(Part p : kits[1].parts)
{
if(p.getPartName().equals(key)) count ++;
}
if(count < num)
{
complete1 = 0;
break;
}
}
}
completeKits = complete0 + complete1;
return parts;
}
synchronized public int completeKits() { return completeKits; }
// should only do when PartRobot tells we have complete kits!
synchronized public Kit removeCompleteKit() {
System.out.println("KitstandCount: " + count);
if(count == 0) return null;
Kit data;
if(kits[0].complete)
{
System.out.println("am in in 1?");
data = kits[0];
kits[0] = null;
}
else
{
System.out.println("am I in 2?");
data = kits[1];
kits[1] = null;
}
count--;
System.out.println("Kit: " + data);
return data;
}
public void placeInspection(Kit kit)
{
// before calling this, have the moving animation
inspection.placeOnInspection(kit);
DoPlaceInspectionKit(kit);
}
public Kit inspectKit()
{
return inspection.inspectKit();
}
public void removeInspection(Kit kit)
{
DoRemoveInspectionKit(kit);
inspection.removeFromInspection();
// in msg, have remove from moving animation
}
public void DoPlaceInspectionKit(Kit kit)
{
}
public void DoRemoveInspectionKit(Kit kit)
{
}
}
| false | true | synchronized public Map<Part, Integer> insertPartsIntoKits(List<Part> send) {
Map<Part, Integer> parts = new HashMap<Part,Integer>();
for(Part p: send)
{
String type = p.getPartName();
if(kits[0]!=null && kits[0].config.containsKey(type))
{
int zero_num = kits[0].config.get(type);
int zero_count = 0;
for(Part zero_p : kits[0].parts)
{
if(zero_p.getPartName().equals(type)) zero_count++;
}
if(zero_count < zero_num)
{
kits[0].parts.add(p);
parts.put(p,0);
}
else
{
kits[1].parts.add(p);
parts.put(p,1);
}
}
else
{
kits[1].parts.add(p);
parts.put(p,1);
}
}
int complete0 = 1;
for (String key : kits[0].config.keySet())
{
int num = kits[0].config.get(key);
int count = 0;
for(Part p : kits[0].parts)
{
if(p.getPartName().equals(key)) count ++;
}
if(count < num)
{
complete0 = 0;
break;
}
}
int complete1 = 1;
if(kits[1]!=null)
{
for (String key : kits[1].config.keySet())
{
int num = kits[1].config.get(key);
int count = 0;
for(Part p : kits[1].parts)
{
if(p.getPartName().equals(key)) count ++;
}
if(count < num)
{
complete1 = 0;
break;
}
}
}
completeKits = complete0 + complete1;
return parts;
}
| synchronized public Map<Part, Integer> insertPartsIntoKits(List<Part> send) {
Map<Part, Integer> parts = new HashMap<Part,Integer>();
for(Part p: send)
{
String type = p.getPartName();
if(kits[0]!=null && kits[0].config.containsKey(type))
{
int zero_num = kits[0].config.get(type);
int zero_count = 0;
for(Part zero_p : kits[0].parts)
{
if(zero_p.getPartName().equals(type)) zero_count++;
}
if(zero_count < zero_num)
{
kits[0].parts.add(p);
parts.put(p,0);
}
else
{
kits[1].parts.add(p);
parts.put(p,1);
}
}
else
{
kits[1].parts.add(p);
parts.put(p,1);
}
}
int complete0 = 1;
if(kits[0]!=null)
{
for (String key : kits[0].config.keySet())
{
int num = kits[0].config.get(key);
int count = 0;
for(Part p : kits[0].parts)
{
if(p.getPartName().equals(key)) count ++;
}
if(count < num)
{
complete0 = 0;
break;
}
}
}
int complete1 = 1;
if(kits[1]!=null)
{
for (String key : kits[1].config.keySet())
{
int num = kits[1].config.get(key);
int count = 0;
for(Part p : kits[1].parts)
{
if(p.getPartName().equals(key)) count ++;
}
if(count < num)
{
complete1 = 0;
break;
}
}
}
completeKits = complete0 + complete1;
return parts;
}
|
diff --git a/applications/carrot2-examples/examples/org/carrot2/examples/clustering/UsingAttributes.java b/applications/carrot2-examples/examples/org/carrot2/examples/clustering/UsingAttributes.java
index 87f375a8f..ca0f9f399 100644
--- a/applications/carrot2-examples/examples/org/carrot2/examples/clustering/UsingAttributes.java
+++ b/applications/carrot2-examples/examples/org/carrot2/examples/clustering/UsingAttributes.java
@@ -1,207 +1,207 @@
/*
* Carrot2 project.
*
* Copyright (C) 2002-2011, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.examples.clustering;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.carrot2.clustering.lingo.LingoClusteringAlgorithm;
import org.carrot2.clustering.lingo.LingoClusteringAlgorithmDescriptor;
import org.carrot2.core.Cluster;
import org.carrot2.core.Controller;
import org.carrot2.core.ControllerFactory;
import org.carrot2.core.Document;
import org.carrot2.core.ProcessingResult;
import org.carrot2.core.attribute.CommonAttributesDescriptor;
import org.carrot2.examples.ConsoleFormatter;
import org.carrot2.examples.SampleDocumentData;
import org.carrot2.matrix.factorization.IterationNumberGuesser.FactorizationQuality;
import org.carrot2.source.boss.BossSearchService;
import org.carrot2.source.microsoft.BingDocumentSource;
import org.carrot2.source.microsoft.BingDocumentSourceDescriptor;
/**
* This example shows how to customize the behaviour of clustering algorithms and
* document sources by setting attributes. For a complete summary of the available
* attributes, please see Carrot2 manual.
*/
public class UsingAttributes
{
@SuppressWarnings("unused")
public static void main(String [] args)
{
/* [[[start:using-attributes-raw-map-intro]]]
* <div>
* <p>
* You can change the default behaviour of clustering algorithms and document sources
* by changing their <em>attributes</em>. For a complete list of available attributes,
* their identifiers, types and allowed values, please see Carrot2 manual.
* </p>
* <p>
* To pass attributes to Carrot2, put them into a {@link java.util.Map},
* along with query or documents being clustered. The code shown below searches the
* <em>wikipedia.org</em> domain using {@link org.carrot2.source.boss.BossDocumentSource}
* and clusters the results using {@link org.carrot2.clustering.lingo.LingoClusteringAlgorithm}
* customized to create fewer clusters than by default.
* </p>
* </div>
* [[[end:using-attributes-raw-map-intro]]]
*/
{
// [[[start:using-attributes-raw-map]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
/* Put values using attribute builders */
attributes.put(CommonAttributesDescriptor.Keys.QUERY, "data mining");
attributes.put(CommonAttributesDescriptor.Keys.RESULTS, 100);
attributes.put("BossSearchService.sites", "wikipedia.org");
attributes.put("BossSearchService.appid",
BossSearchService.CARROTSEARCH_APPID); // user your own ID here
attributes.put("LingoClusteringAlgorithm.desiredClusterCountBase", 15);
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Documents fetched from the document source, clusters created by Carrot2. */
final List<Document> documents = result.getDocuments();
final List<Cluster> clusters = result.getClusters();
// [[[end:using-attributes-raw-map]]]
ConsoleFormatter.displayResults(result);
}
/* [[[start:using-attributes-builders-intro]]]
*
* <div>
* <p>
* As an alternative to the raw attribute map used in the previous example, you
* can use attribute map builders. Attribute map builders have a number of advantages:
* </p>
*
* <ul>
* <li>Type-safety: the correct type of the value will be enforced at compile time</li>
* <li>Error prevention: unexpected results caused by typos in attribute name strings are avoided</li>
* <li>Early error detection: in case an attribute's key changes, your compiler will detect that</li>
* <li>IDE support: your IDE will suggest the right method names and parameters</li>
* </ul>
*
* <p>
* A possible disadvantage of attribute builders is that one algorithm's attributes can
* be divided into a number of builders and hence not readily available in your IDE's auto
* complete window. Please consult attribute documentation in Carrot2 manual for pointers to
* the appropriate builder classes and methods.
* </p>
*
* <p>
* The code shown below fetches 100 results for query <em>data mining</em> from
* {@link org.carrot2.source.microsoft.BingDocumentSource} and clusters them using
* the {@link org.carrot2.clustering.lingo.LingoClusteringAlgorithm} tuned to create slightly
* fewer clusters than by default. Please note how the API key is passed and use your own
* key in production deployments.
* </p>
* </div>
*
* [[[end:using-attributes-builders-intro]]]
*/
{
/// [[[start:using-attributes-builders]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
/* Put values using attribute builders */
CommonAttributesDescriptor
.attributeBuilder(attributes)
.query("data mining")
.results(100);
LingoClusteringAlgorithmDescriptor
.attributeBuilder(attributes)
.desiredClusterCountBase(15)
.matrixReducer()
.factorizationQuality(FactorizationQuality.HIGH);
BingDocumentSourceDescriptor
.attributeBuilder(attributes)
.appid(BingDocumentSource.CARROTSEARCH_APPID); // use your own key here
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Documents fetched from the document source, clusters created by Carrot2. */
final List<Document> documents = result.getDocuments();
final List<Cluster> clusters = result.getClusters();
/// [[[end:using-attributes-builders]]]
ConsoleFormatter.displayResults(result);
}
/* [[[start:using-attributes-output-intro]]]
* <div>
* <p>
* Some algorithms apart from clusters can produce additional, usually
* diagnostic, output. The output is present in the attributes map contained
* in the {@link org.carrot2.core.ProcessingResult}. You can read the contents
* of that map directly or through the attribute map builders. Carrot2 manual
* lists and describes in detail the output attributes of each component.
* </p>
* <p>
* The code shown below clusters clusters an example collection of
* {@link org.carrot2.core.Document}s using the Lingo algorithm. Lingo can
* optionally use native platform-specific matrix computation libraries. The
* example code reads an attribute to find out whether such libraries were
* successfully loaded and used.
* </p>
* </div>
* [[[end:using-attributes-output-intro]]]
*/
{
/// [[[start:using-attributes-output]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
CommonAttributesDescriptor
.attributeBuilder(attributes)
.documents(SampleDocumentData.DOCUMENTS_DATA_MINING);
LingoClusteringAlgorithmDescriptor
.attributeBuilder(attributes)
.desiredClusterCountBase(15)
.matrixReducer()
.factorizationQuality(FactorizationQuality.HIGH);
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
- BingDocumentSource.class, LingoClusteringAlgorithm.class);
+ LingoClusteringAlgorithm.class);
/* Clusters created by Carrot2, native matrix computation flag */
final List<Cluster> clusters = result.getClusters();
final boolean nativeMatrixUsed = LingoClusteringAlgorithmDescriptor
.attributeBuilder(result.getAttributes())
.nativeMatrixUsed();
/// [[[end:using-attributes-output]]]
ConsoleFormatter.displayResults(result);
}
}
}
| true | true | public static void main(String [] args)
{
/* [[[start:using-attributes-raw-map-intro]]]
* <div>
* <p>
* You can change the default behaviour of clustering algorithms and document sources
* by changing their <em>attributes</em>. For a complete list of available attributes,
* their identifiers, types and allowed values, please see Carrot2 manual.
* </p>
* <p>
* To pass attributes to Carrot2, put them into a {@link java.util.Map},
* along with query or documents being clustered. The code shown below searches the
* <em>wikipedia.org</em> domain using {@link org.carrot2.source.boss.BossDocumentSource}
* and clusters the results using {@link org.carrot2.clustering.lingo.LingoClusteringAlgorithm}
* customized to create fewer clusters than by default.
* </p>
* </div>
* [[[end:using-attributes-raw-map-intro]]]
*/
{
// [[[start:using-attributes-raw-map]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
/* Put values using attribute builders */
attributes.put(CommonAttributesDescriptor.Keys.QUERY, "data mining");
attributes.put(CommonAttributesDescriptor.Keys.RESULTS, 100);
attributes.put("BossSearchService.sites", "wikipedia.org");
attributes.put("BossSearchService.appid",
BossSearchService.CARROTSEARCH_APPID); // user your own ID here
attributes.put("LingoClusteringAlgorithm.desiredClusterCountBase", 15);
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Documents fetched from the document source, clusters created by Carrot2. */
final List<Document> documents = result.getDocuments();
final List<Cluster> clusters = result.getClusters();
// [[[end:using-attributes-raw-map]]]
ConsoleFormatter.displayResults(result);
}
/* [[[start:using-attributes-builders-intro]]]
*
* <div>
* <p>
* As an alternative to the raw attribute map used in the previous example, you
* can use attribute map builders. Attribute map builders have a number of advantages:
* </p>
*
* <ul>
* <li>Type-safety: the correct type of the value will be enforced at compile time</li>
* <li>Error prevention: unexpected results caused by typos in attribute name strings are avoided</li>
* <li>Early error detection: in case an attribute's key changes, your compiler will detect that</li>
* <li>IDE support: your IDE will suggest the right method names and parameters</li>
* </ul>
*
* <p>
* A possible disadvantage of attribute builders is that one algorithm's attributes can
* be divided into a number of builders and hence not readily available in your IDE's auto
* complete window. Please consult attribute documentation in Carrot2 manual for pointers to
* the appropriate builder classes and methods.
* </p>
*
* <p>
* The code shown below fetches 100 results for query <em>data mining</em> from
* {@link org.carrot2.source.microsoft.BingDocumentSource} and clusters them using
* the {@link org.carrot2.clustering.lingo.LingoClusteringAlgorithm} tuned to create slightly
* fewer clusters than by default. Please note how the API key is passed and use your own
* key in production deployments.
* </p>
* </div>
*
* [[[end:using-attributes-builders-intro]]]
*/
{
/// [[[start:using-attributes-builders]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
/* Put values using attribute builders */
CommonAttributesDescriptor
.attributeBuilder(attributes)
.query("data mining")
.results(100);
LingoClusteringAlgorithmDescriptor
.attributeBuilder(attributes)
.desiredClusterCountBase(15)
.matrixReducer()
.factorizationQuality(FactorizationQuality.HIGH);
BingDocumentSourceDescriptor
.attributeBuilder(attributes)
.appid(BingDocumentSource.CARROTSEARCH_APPID); // use your own key here
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Documents fetched from the document source, clusters created by Carrot2. */
final List<Document> documents = result.getDocuments();
final List<Cluster> clusters = result.getClusters();
/// [[[end:using-attributes-builders]]]
ConsoleFormatter.displayResults(result);
}
/* [[[start:using-attributes-output-intro]]]
* <div>
* <p>
* Some algorithms apart from clusters can produce additional, usually
* diagnostic, output. The output is present in the attributes map contained
* in the {@link org.carrot2.core.ProcessingResult}. You can read the contents
* of that map directly or through the attribute map builders. Carrot2 manual
* lists and describes in detail the output attributes of each component.
* </p>
* <p>
* The code shown below clusters clusters an example collection of
* {@link org.carrot2.core.Document}s using the Lingo algorithm. Lingo can
* optionally use native platform-specific matrix computation libraries. The
* example code reads an attribute to find out whether such libraries were
* successfully loaded and used.
* </p>
* </div>
* [[[end:using-attributes-output-intro]]]
*/
{
/// [[[start:using-attributes-output]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
CommonAttributesDescriptor
.attributeBuilder(attributes)
.documents(SampleDocumentData.DOCUMENTS_DATA_MINING);
LingoClusteringAlgorithmDescriptor
.attributeBuilder(attributes)
.desiredClusterCountBase(15)
.matrixReducer()
.factorizationQuality(FactorizationQuality.HIGH);
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Clusters created by Carrot2, native matrix computation flag */
final List<Cluster> clusters = result.getClusters();
final boolean nativeMatrixUsed = LingoClusteringAlgorithmDescriptor
.attributeBuilder(result.getAttributes())
.nativeMatrixUsed();
/// [[[end:using-attributes-output]]]
ConsoleFormatter.displayResults(result);
}
}
| public static void main(String [] args)
{
/* [[[start:using-attributes-raw-map-intro]]]
* <div>
* <p>
* You can change the default behaviour of clustering algorithms and document sources
* by changing their <em>attributes</em>. For a complete list of available attributes,
* their identifiers, types and allowed values, please see Carrot2 manual.
* </p>
* <p>
* To pass attributes to Carrot2, put them into a {@link java.util.Map},
* along with query or documents being clustered. The code shown below searches the
* <em>wikipedia.org</em> domain using {@link org.carrot2.source.boss.BossDocumentSource}
* and clusters the results using {@link org.carrot2.clustering.lingo.LingoClusteringAlgorithm}
* customized to create fewer clusters than by default.
* </p>
* </div>
* [[[end:using-attributes-raw-map-intro]]]
*/
{
// [[[start:using-attributes-raw-map]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
/* Put values using attribute builders */
attributes.put(CommonAttributesDescriptor.Keys.QUERY, "data mining");
attributes.put(CommonAttributesDescriptor.Keys.RESULTS, 100);
attributes.put("BossSearchService.sites", "wikipedia.org");
attributes.put("BossSearchService.appid",
BossSearchService.CARROTSEARCH_APPID); // user your own ID here
attributes.put("LingoClusteringAlgorithm.desiredClusterCountBase", 15);
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Documents fetched from the document source, clusters created by Carrot2. */
final List<Document> documents = result.getDocuments();
final List<Cluster> clusters = result.getClusters();
// [[[end:using-attributes-raw-map]]]
ConsoleFormatter.displayResults(result);
}
/* [[[start:using-attributes-builders-intro]]]
*
* <div>
* <p>
* As an alternative to the raw attribute map used in the previous example, you
* can use attribute map builders. Attribute map builders have a number of advantages:
* </p>
*
* <ul>
* <li>Type-safety: the correct type of the value will be enforced at compile time</li>
* <li>Error prevention: unexpected results caused by typos in attribute name strings are avoided</li>
* <li>Early error detection: in case an attribute's key changes, your compiler will detect that</li>
* <li>IDE support: your IDE will suggest the right method names and parameters</li>
* </ul>
*
* <p>
* A possible disadvantage of attribute builders is that one algorithm's attributes can
* be divided into a number of builders and hence not readily available in your IDE's auto
* complete window. Please consult attribute documentation in Carrot2 manual for pointers to
* the appropriate builder classes and methods.
* </p>
*
* <p>
* The code shown below fetches 100 results for query <em>data mining</em> from
* {@link org.carrot2.source.microsoft.BingDocumentSource} and clusters them using
* the {@link org.carrot2.clustering.lingo.LingoClusteringAlgorithm} tuned to create slightly
* fewer clusters than by default. Please note how the API key is passed and use your own
* key in production deployments.
* </p>
* </div>
*
* [[[end:using-attributes-builders-intro]]]
*/
{
/// [[[start:using-attributes-builders]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
/* Put values using attribute builders */
CommonAttributesDescriptor
.attributeBuilder(attributes)
.query("data mining")
.results(100);
LingoClusteringAlgorithmDescriptor
.attributeBuilder(attributes)
.desiredClusterCountBase(15)
.matrixReducer()
.factorizationQuality(FactorizationQuality.HIGH);
BingDocumentSourceDescriptor
.attributeBuilder(attributes)
.appid(BingDocumentSource.CARROTSEARCH_APPID); // use your own key here
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
BingDocumentSource.class, LingoClusteringAlgorithm.class);
/* Documents fetched from the document source, clusters created by Carrot2. */
final List<Document> documents = result.getDocuments();
final List<Cluster> clusters = result.getClusters();
/// [[[end:using-attributes-builders]]]
ConsoleFormatter.displayResults(result);
}
/* [[[start:using-attributes-output-intro]]]
* <div>
* <p>
* Some algorithms apart from clusters can produce additional, usually
* diagnostic, output. The output is present in the attributes map contained
* in the {@link org.carrot2.core.ProcessingResult}. You can read the contents
* of that map directly or through the attribute map builders. Carrot2 manual
* lists and describes in detail the output attributes of each component.
* </p>
* <p>
* The code shown below clusters clusters an example collection of
* {@link org.carrot2.core.Document}s using the Lingo algorithm. Lingo can
* optionally use native platform-specific matrix computation libraries. The
* example code reads an attribute to find out whether such libraries were
* successfully loaded and used.
* </p>
* </div>
* [[[end:using-attributes-output-intro]]]
*/
{
/// [[[start:using-attributes-output]]]
/* A controller to manage the processing pipeline. */
final Controller controller = ControllerFactory.createSimple();
/* Prepare attribute map */
final Map<String, Object> attributes = new HashMap<String, Object>();
CommonAttributesDescriptor
.attributeBuilder(attributes)
.documents(SampleDocumentData.DOCUMENTS_DATA_MINING);
LingoClusteringAlgorithmDescriptor
.attributeBuilder(attributes)
.desiredClusterCountBase(15)
.matrixReducer()
.factorizationQuality(FactorizationQuality.HIGH);
/* Perform processing */
final ProcessingResult result = controller.process(attributes,
LingoClusteringAlgorithm.class);
/* Clusters created by Carrot2, native matrix computation flag */
final List<Cluster> clusters = result.getClusters();
final boolean nativeMatrixUsed = LingoClusteringAlgorithmDescriptor
.attributeBuilder(result.getAttributes())
.nativeMatrixUsed();
/// [[[end:using-attributes-output]]]
ConsoleFormatter.displayResults(result);
}
}
|
diff --git a/src/net/mdcreator/tpplus/TPPlusExecutor.java b/src/net/mdcreator/tpplus/TPPlusExecutor.java
index b74b19e..2302871 100644
--- a/src/net/mdcreator/tpplus/TPPlusExecutor.java
+++ b/src/net/mdcreator/tpplus/TPPlusExecutor.java
@@ -1,89 +1,93 @@
package net.mdcreator.tpplus;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
public class TPPlusExecutor implements CommandExecutor{
TPPlus plugin;
private String title = ChatColor.DARK_GRAY + "[" + ChatColor.BLUE + "TP+" + ChatColor.DARK_GRAY + "] " + ChatColor.GRAY;
public TPPlusExecutor(TPPlus plugin){
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PluginDescriptionFile pdf = plugin.getDescription();
if(args.length==0){
sender.sendMessage(new String[] {
title + "info",
ChatColor.DARK_GRAY + "by " + ChatColor.GRAY + pdf.getAuthors().get(0),
ChatColor.DARK_GRAY + "vers " + ChatColor.GRAY + pdf.getVersion(),
ChatColor.GRAY + pdf.getDescription()
});
return true;
} else if(args.length==1){
if(args[0].equals("update")){
if(sender instanceof Player && !sender.isOp()){
sender.sendMessage(title + ChatColor.RED + "You can't update the plugin!");
return true;
}
try {
sender.getServer().broadcastMessage(title + "Updating plugin, expect lag");
URL onlinePlugin = new URL("https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
sender.sendMessage(title + "Using https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
plugin.getLogger().info(title + "Updating plugin https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
ReadableByteChannel rbc = Channels.newChannel(onlinePlugin.openStream());
FileOutputStream fos = new FileOutputStream(plugin.getDataFolder().getParentFile().getPath() + "\\TPPlus.jar");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
sender.getServer().broadcastMessage(title + "Reloading server");
plugin.getServer().reload();
sender.getServer().broadcastMessage(title + "Finished updating");
} catch (IOException e) {
sender.sendMessage(title + ChatColor.RED + "An error occurred while updating:" + Arrays.toString(e.getStackTrace()));
e.printStackTrace();
}
return true;
} else return false;
} else if(args.length==2){
if(sender instanceof Player && !sender.isOp()){
sender.sendMessage(title + ChatColor.RED + "You can't update the plugin!");
return true;
}
if(args[0].equals("op-color")){
plugin.configYML.set("op-color", args[1]);
plugin.saveConfig();
sender.sendMessage(title + "Op color set to " + ChatColor.translateAlternateColorCodes('&', args[1] + "this"));
return true;
} else if(args[0].equals("owner-color")){
plugin.configYML.set("owner-color", args[1]);
sender.sendMessage(title + "Owner color set to " + ChatColor.translateAlternateColorCodes('&', args[1] + "this"));
plugin.saveConfig();
return true;
} else if(args[0].equals("remove")){
- String player = args[1];
+ String player = null;
for(String possible : plugin.homesManager.homes.keySet()){
- if(possible.toLowerCase().startsWith(player.toLowerCase())) player = possible;
+ if(possible.toLowerCase().startsWith(args[1].toLowerCase())) player = possible;
+ }
+ if(player==null){
+ sender.sendMessage(title + ChatColor.RED + "That player is not in our records!");
+ return true;
}
plugin.icons.findMarker(player).deleteMarker();
plugin.homesManager.homes.remove(player);
plugin.homesYML.set(player, null);
plugin.saveHomes();
sender.sendMessage(title + "Home for " + player + " deleted.");
return true;
} else return false;
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PluginDescriptionFile pdf = plugin.getDescription();
if(args.length==0){
sender.sendMessage(new String[] {
title + "info",
ChatColor.DARK_GRAY + "by " + ChatColor.GRAY + pdf.getAuthors().get(0),
ChatColor.DARK_GRAY + "vers " + ChatColor.GRAY + pdf.getVersion(),
ChatColor.GRAY + pdf.getDescription()
});
return true;
} else if(args.length==1){
if(args[0].equals("update")){
if(sender instanceof Player && !sender.isOp()){
sender.sendMessage(title + ChatColor.RED + "You can't update the plugin!");
return true;
}
try {
sender.getServer().broadcastMessage(title + "Updating plugin, expect lag");
URL onlinePlugin = new URL("https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
sender.sendMessage(title + "Using https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
plugin.getLogger().info(title + "Updating plugin https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
ReadableByteChannel rbc = Channels.newChannel(onlinePlugin.openStream());
FileOutputStream fos = new FileOutputStream(plugin.getDataFolder().getParentFile().getPath() + "\\TPPlus.jar");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
sender.getServer().broadcastMessage(title + "Reloading server");
plugin.getServer().reload();
sender.getServer().broadcastMessage(title + "Finished updating");
} catch (IOException e) {
sender.sendMessage(title + ChatColor.RED + "An error occurred while updating:" + Arrays.toString(e.getStackTrace()));
e.printStackTrace();
}
return true;
} else return false;
} else if(args.length==2){
if(sender instanceof Player && !sender.isOp()){
sender.sendMessage(title + ChatColor.RED + "You can't update the plugin!");
return true;
}
if(args[0].equals("op-color")){
plugin.configYML.set("op-color", args[1]);
plugin.saveConfig();
sender.sendMessage(title + "Op color set to " + ChatColor.translateAlternateColorCodes('&', args[1] + "this"));
return true;
} else if(args[0].equals("owner-color")){
plugin.configYML.set("owner-color", args[1]);
sender.sendMessage(title + "Owner color set to " + ChatColor.translateAlternateColorCodes('&', args[1] + "this"));
plugin.saveConfig();
return true;
} else if(args[0].equals("remove")){
String player = args[1];
for(String possible : plugin.homesManager.homes.keySet()){
if(possible.toLowerCase().startsWith(player.toLowerCase())) player = possible;
}
plugin.icons.findMarker(player).deleteMarker();
plugin.homesManager.homes.remove(player);
plugin.homesYML.set(player, null);
plugin.saveHomes();
sender.sendMessage(title + "Home for " + player + " deleted.");
return true;
} else return false;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PluginDescriptionFile pdf = plugin.getDescription();
if(args.length==0){
sender.sendMessage(new String[] {
title + "info",
ChatColor.DARK_GRAY + "by " + ChatColor.GRAY + pdf.getAuthors().get(0),
ChatColor.DARK_GRAY + "vers " + ChatColor.GRAY + pdf.getVersion(),
ChatColor.GRAY + pdf.getDescription()
});
return true;
} else if(args.length==1){
if(args[0].equals("update")){
if(sender instanceof Player && !sender.isOp()){
sender.sendMessage(title + ChatColor.RED + "You can't update the plugin!");
return true;
}
try {
sender.getServer().broadcastMessage(title + "Updating plugin, expect lag");
URL onlinePlugin = new URL("https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
sender.sendMessage(title + "Using https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
plugin.getLogger().info(title + "Updating plugin https://github.com/Gratimax/TPPlus/blob/master/deploy/TPPlus.jar?raw=true");
ReadableByteChannel rbc = Channels.newChannel(onlinePlugin.openStream());
FileOutputStream fos = new FileOutputStream(plugin.getDataFolder().getParentFile().getPath() + "\\TPPlus.jar");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
sender.getServer().broadcastMessage(title + "Reloading server");
plugin.getServer().reload();
sender.getServer().broadcastMessage(title + "Finished updating");
} catch (IOException e) {
sender.sendMessage(title + ChatColor.RED + "An error occurred while updating:" + Arrays.toString(e.getStackTrace()));
e.printStackTrace();
}
return true;
} else return false;
} else if(args.length==2){
if(sender instanceof Player && !sender.isOp()){
sender.sendMessage(title + ChatColor.RED + "You can't update the plugin!");
return true;
}
if(args[0].equals("op-color")){
plugin.configYML.set("op-color", args[1]);
plugin.saveConfig();
sender.sendMessage(title + "Op color set to " + ChatColor.translateAlternateColorCodes('&', args[1] + "this"));
return true;
} else if(args[0].equals("owner-color")){
plugin.configYML.set("owner-color", args[1]);
sender.sendMessage(title + "Owner color set to " + ChatColor.translateAlternateColorCodes('&', args[1] + "this"));
plugin.saveConfig();
return true;
} else if(args[0].equals("remove")){
String player = null;
for(String possible : plugin.homesManager.homes.keySet()){
if(possible.toLowerCase().startsWith(args[1].toLowerCase())) player = possible;
}
if(player==null){
sender.sendMessage(title + ChatColor.RED + "That player is not in our records!");
return true;
}
plugin.icons.findMarker(player).deleteMarker();
plugin.homesManager.homes.remove(player);
plugin.homesYML.set(player, null);
plugin.saveHomes();
sender.sendMessage(title + "Home for " + player + " deleted.");
return true;
} else return false;
}
return false;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java
index 318e03d4d..d265d866c 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java
@@ -1,113 +1,113 @@
package com.ForgeEssentials.WorldBorder;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
import com.ForgeEssentials.WorldBorder.Effects.IEffect;
import com.ForgeEssentials.core.ForgeEssentials;
import com.ForgeEssentials.util.OutputHandler;
/**
* This generates the configuration structure
*
* @author Dries007
*
*/
public class ConfigWorldBorder
{
public static final File wbconfig = new File(ForgeEssentials.FEDIR, "WorldBorder.cfg");
public final Configuration config;
/**
* This list makes sure the effect is in the example file.
* Not used for parsing the list from the config.
*/
public static final List<String> PossibleEffects = Arrays.asList("knockback", "message", "potion", "damage", "smite", "serverkick", "executecommand");
public ConfigWorldBorder()
{
config = new Configuration(wbconfig, true);
penaltiesConfig(config);
commonConfig(config);
config.save();
}
/**
* Does all the rest of the config
* @param config
*/
public static void commonConfig(Configuration config)
{
String category = "Settings";
config.addCustomCategoryComment(category, "Common settings.");
ModuleWorldBorder.logToConsole = config.get(category, "LogToConsole", true, "Enable logging to the server console & the log file").getBoolean(true);
Property prop = config.get(category, "overGenerate", 345);
prop.comment = "The amount of blocks that will be generated outside the radius of the border. This is important!" +
" \nIf you set this high, you will need exponentially more time while generating, but you won't get extra land if a player does pass the border." +
" \nIf you use something like Dynmap you should put this number higher, if the border is not there for aesthetic purposes, then you don't need that." +
" \nThe default value (345) is calcultated like this: (20 chuncks for vieuw distance * 16 blocks per chunck) + 25 as backup" +
" \nThis allows players to pass the border 25 blocks before generating new land.";
ModuleWorldBorder.overGenerate = prop.getInt(345);
}
/**
* Does penalty part on config
* @param config
*/
public static void penaltiesConfig(Configuration config)
{
- String penaltyBasePackage = IEffect.class.getPackage().getName() + ".";
+ String penaltyBasePackage = ForgeEssentials.class.getPackage().getName() + ".";
config.addCustomCategoryComment("Penalties", "This is what will happen to the player if he passes the world boder.");
String[] stages = {"Stage1"};
stages = config.get("Penalties", "stages", stages, "If you add an item here, a subcategory will be generated").valueList;
for(String stage : stages)
{
String cat = "Penalties." + stage;
int dist = config.get(cat, "Distance", 0, "The distance outside the border when this gets activated. WARING this needs to be unique! You can specify 2 penalties in 1 stage.").getInt();
String[] effects = {"message", "knockback", "damage"};
effects = config.get(cat, "effects", effects, "Get the list of possibilitys in the example file").valueList;
IEffect[] effctList = new IEffect[effects.length];
int i = 0;
for(String effect : effects)
{
try
{
Class c = Class.forName(penaltyBasePackage + effect.toLowerCase());
try
{
IEffect pentalty = (IEffect) c.newInstance();
pentalty.registerConfig(config, cat + "." + effect);
effctList[i] = pentalty;
i++;
}
catch (Exception e)
{
OutputHandler.SOP("Could not initialize '" + effect + "' in stage '" + stage + "'");
}
}
catch (ClassNotFoundException e)
{
OutputHandler.SOP("'" + effect + "' in the stage '" + stage + "' does not exist!");
}
}
ModuleWorldBorder.registerEffects(dist, effctList);
}
}
}
| true | true | public static void penaltiesConfig(Configuration config)
{
String penaltyBasePackage = IEffect.class.getPackage().getName() + ".";
config.addCustomCategoryComment("Penalties", "This is what will happen to the player if he passes the world boder.");
String[] stages = {"Stage1"};
stages = config.get("Penalties", "stages", stages, "If you add an item here, a subcategory will be generated").valueList;
for(String stage : stages)
{
String cat = "Penalties." + stage;
int dist = config.get(cat, "Distance", 0, "The distance outside the border when this gets activated. WARING this needs to be unique! You can specify 2 penalties in 1 stage.").getInt();
String[] effects = {"message", "knockback", "damage"};
effects = config.get(cat, "effects", effects, "Get the list of possibilitys in the example file").valueList;
IEffect[] effctList = new IEffect[effects.length];
int i = 0;
for(String effect : effects)
{
try
{
Class c = Class.forName(penaltyBasePackage + effect.toLowerCase());
try
{
IEffect pentalty = (IEffect) c.newInstance();
pentalty.registerConfig(config, cat + "." + effect);
effctList[i] = pentalty;
i++;
}
catch (Exception e)
{
OutputHandler.SOP("Could not initialize '" + effect + "' in stage '" + stage + "'");
}
}
catch (ClassNotFoundException e)
{
OutputHandler.SOP("'" + effect + "' in the stage '" + stage + "' does not exist!");
}
}
ModuleWorldBorder.registerEffects(dist, effctList);
}
}
| public static void penaltiesConfig(Configuration config)
{
String penaltyBasePackage = ForgeEssentials.class.getPackage().getName() + ".";
config.addCustomCategoryComment("Penalties", "This is what will happen to the player if he passes the world boder.");
String[] stages = {"Stage1"};
stages = config.get("Penalties", "stages", stages, "If you add an item here, a subcategory will be generated").valueList;
for(String stage : stages)
{
String cat = "Penalties." + stage;
int dist = config.get(cat, "Distance", 0, "The distance outside the border when this gets activated. WARING this needs to be unique! You can specify 2 penalties in 1 stage.").getInt();
String[] effects = {"message", "knockback", "damage"};
effects = config.get(cat, "effects", effects, "Get the list of possibilitys in the example file").valueList;
IEffect[] effctList = new IEffect[effects.length];
int i = 0;
for(String effect : effects)
{
try
{
Class c = Class.forName(penaltyBasePackage + effect.toLowerCase());
try
{
IEffect pentalty = (IEffect) c.newInstance();
pentalty.registerConfig(config, cat + "." + effect);
effctList[i] = pentalty;
i++;
}
catch (Exception e)
{
OutputHandler.SOP("Could not initialize '" + effect + "' in stage '" + stage + "'");
}
}
catch (ClassNotFoundException e)
{
OutputHandler.SOP("'" + effect + "' in the stage '" + stage + "' does not exist!");
}
}
ModuleWorldBorder.registerEffects(dist, effctList);
}
}
|
diff --git a/src/com/androzic/plugin/tracker/SMSReceiver.java b/src/com/androzic/plugin/tracker/SMSReceiver.java
index fc3e226..b69ef25 100644
--- a/src/com/androzic/plugin/tracker/SMSReceiver.java
+++ b/src/com/androzic/plugin/tracker/SMSReceiver.java
@@ -1,210 +1,210 @@
/*
* Androzic - android navigation client that uses OziExplorer maps (ozf2, ozfx3).
* Copyright (C) 2010-2013 Andrey Novikov <http://andreynovikov.info/>
*
* This file is part of Androzic application.
*
* Androzic 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.
*
* Androzic 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 Androzic. If not, see <http://www.gnu.org/licenses/>.
*/
package com.androzic.plugin.tracker;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsMessage;
import android.util.Log;
import com.androzic.data.Tracker;
import com.androzic.util.CoordinateParser;
public class SMSReceiver extends BroadcastReceiver
{
private static final String TAG = "SMSReceiver";
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat XexunDateFormatter = new SimpleDateFormat("dd/MM/yy HH:mm");
private static final Pattern realNumber = Pattern.compile("\\d+\\.\\d+");
@Override
public void onReceive(Context context, Intent intent)
{
Log.e(TAG, "SMS received");
Bundle extras = intent.getExtras();
if (extras == null)
return;
StringBuilder messageBuilder = new StringBuilder();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++)
{
SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
String text = msg.getMessageBody();
if (text == null)
continue;
messageBuilder.append(text);
}
String text = messageBuilder.toString();
Log.i(TAG, "SMS: " + text);
// Xexun family and some clones
// lat: 55.807693 long: 037.730640 speed: 000.0 03/03/13 16:18 bat:F signal:F imei:358948010446647
// lat:55.950468 long:035.867116 speed: 000.0 24/11/12 08:54 bat:F signal:F imei:358948010446647
// lat: 123.345678N long: 0.125621W speed: 001.2 17/07/11 21:34 F:3.92V,1,Signal:F help me imei:123456789012 07 83.8 234 15 006B 24C4
// lat: 22.566901 long: 114.051258 speed: 0.00 14/08/09 06.54 F:3.85V,1,Signal:F help me imei:354776031555474 05 43.5 460 01 2533 720B
// help me! lat:123.45678 long:001.23456 speed:090.00 T:17/01/11 15:14 Bat:25% Signal:F imei:1234567
// http://fiddle.re/fpfa6
Pattern pattern = Pattern.compile("(.*)?\\s?lat:\\s?([^\\s]+)\\slong:\\s?([^\\s]+)\\sspeed:\\s?([\\d\\.]+)\\s(?:T:)?([\\d/:\\.\\s]+)\\s(?:bat|F):([^\\s,]+)(?:V,\\d,)?\\s?signal:([^\\s]+)\\s(.*)?\\s?imei:(\\d+)", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(text);
if (! m.matches())
return;
Tracker tracker = new Tracker();
String latitude = m.group(2);
String longitude = m.group(3);
double coords[] = CoordinateParser.parse(latitude + " " + longitude);
if (Double.isNaN(coords[0]) || Double.isNaN(coords[1]))
return;
tracker.latitude = coords[0];
tracker.longitude = coords[1];
try
{
tracker.speed = Double.parseDouble(m.group(4)) / 3.6;
}
catch (NumberFormatException ignore)
{
}
String time = m.group(5);
try
{
Date date = XexunDateFormatter.parse(time);
tracker.modified = date.getTime();
}
catch (Exception e)
{
Log.e(TAG, "Date error", e);
}
String battery = m.group(6);
if ("F".equals(battery))
tracker.battery = Tracker.LEVEL_FULL;
if ("L".equals(battery))
tracker.battery = Tracker.LEVEL_LOW;
try
{
if (battery.endsWith("%"))
tracker.battery = Integer.parseInt(battery.substring(0, battery.length() - 1));
if (realNumber.matcher(battery).matches())
tracker.battery = (int) (Float.parseFloat(battery) * 100);
}
catch (NumberFormatException ignore)
{
}
String signal = m.group(7);
if ("F".equals(signal))
tracker.signal = Tracker.LEVEL_FULL;
if ("L".equals(signal) || "0".equals(signal))
tracker.signal = Tracker.LEVEL_LOW;
tracker.imei = m.group(9);
String message = m.group(1);
if ("".equals(message))
tracker.message = message;
message = m.group(8);
if ("".equals(message))
tracker.message = message;
if (! "".equals(tracker.imei))
{
// Save tracker data
TrackerDataAccess dataAccess = new TrackerDataAccess(context);
dataAccess.saveTracker(tracker);
try
{
Application application = Application.getApplication();
application.sendMapObject(dataAccess, tracker);
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
dataAccess.close();
context.sendBroadcast(new Intent(Application.TRACKER_DATE_RECEIVED_BROADCAST));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Show notification
boolean notifications = prefs.getBoolean(context.getString(R.string.pref_tracker_notifications), context.getResources().getBoolean(R.bool.def_notifications));
if (notifications)
{
Intent i = new Intent("com.androzic.COORDINATES_RECEIVED");
i.putExtra("title", tracker.name);
i.putExtra("sender", tracker.name);
i.putExtra("origin", context.getApplicationContext().getPackageName());
i.putExtra("lat", tracker.latitude);
i.putExtra("lon", tracker.longitude);
String msg = context.getString(R.string.notif_text, tracker.name);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(context.getString(R.string.app_name));
builder.setContentText(msg);
- PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_ONE_SHOT);
+ PendingIntent contentIntent = PendingIntent.getBroadcast(context, (int) tracker._id, i, PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_stat_tracker);
builder.setTicker(msg);
builder.setWhen(tracker.modified);
int defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
boolean vibrate = prefs.getBoolean(context.getString(R.string.pref_tracker_vibrate), context.getResources().getBoolean(R.bool.def_vibrate));
if (vibrate)
defaults |= Notification.DEFAULT_VIBRATE;
builder.setDefaults(defaults);
builder.setAutoCancel(true);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) tracker._id, notification);
}
// Conceal SMS
boolean concealsms = prefs.getBoolean(context.getString(R.string.pref_tracker_concealsms), context.getResources().getBoolean(R.bool.def_concealsms));
if (concealsms)
abortBroadcast();
}
}
}
| true | true | public void onReceive(Context context, Intent intent)
{
Log.e(TAG, "SMS received");
Bundle extras = intent.getExtras();
if (extras == null)
return;
StringBuilder messageBuilder = new StringBuilder();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++)
{
SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
String text = msg.getMessageBody();
if (text == null)
continue;
messageBuilder.append(text);
}
String text = messageBuilder.toString();
Log.i(TAG, "SMS: " + text);
// Xexun family and some clones
// lat: 55.807693 long: 037.730640 speed: 000.0 03/03/13 16:18 bat:F signal:F imei:358948010446647
// lat:55.950468 long:035.867116 speed: 000.0 24/11/12 08:54 bat:F signal:F imei:358948010446647
// lat: 123.345678N long: 0.125621W speed: 001.2 17/07/11 21:34 F:3.92V,1,Signal:F help me imei:123456789012 07 83.8 234 15 006B 24C4
// lat: 22.566901 long: 114.051258 speed: 0.00 14/08/09 06.54 F:3.85V,1,Signal:F help me imei:354776031555474 05 43.5 460 01 2533 720B
// help me! lat:123.45678 long:001.23456 speed:090.00 T:17/01/11 15:14 Bat:25% Signal:F imei:1234567
// http://fiddle.re/fpfa6
Pattern pattern = Pattern.compile("(.*)?\\s?lat:\\s?([^\\s]+)\\slong:\\s?([^\\s]+)\\sspeed:\\s?([\\d\\.]+)\\s(?:T:)?([\\d/:\\.\\s]+)\\s(?:bat|F):([^\\s,]+)(?:V,\\d,)?\\s?signal:([^\\s]+)\\s(.*)?\\s?imei:(\\d+)", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(text);
if (! m.matches())
return;
Tracker tracker = new Tracker();
String latitude = m.group(2);
String longitude = m.group(3);
double coords[] = CoordinateParser.parse(latitude + " " + longitude);
if (Double.isNaN(coords[0]) || Double.isNaN(coords[1]))
return;
tracker.latitude = coords[0];
tracker.longitude = coords[1];
try
{
tracker.speed = Double.parseDouble(m.group(4)) / 3.6;
}
catch (NumberFormatException ignore)
{
}
String time = m.group(5);
try
{
Date date = XexunDateFormatter.parse(time);
tracker.modified = date.getTime();
}
catch (Exception e)
{
Log.e(TAG, "Date error", e);
}
String battery = m.group(6);
if ("F".equals(battery))
tracker.battery = Tracker.LEVEL_FULL;
if ("L".equals(battery))
tracker.battery = Tracker.LEVEL_LOW;
try
{
if (battery.endsWith("%"))
tracker.battery = Integer.parseInt(battery.substring(0, battery.length() - 1));
if (realNumber.matcher(battery).matches())
tracker.battery = (int) (Float.parseFloat(battery) * 100);
}
catch (NumberFormatException ignore)
{
}
String signal = m.group(7);
if ("F".equals(signal))
tracker.signal = Tracker.LEVEL_FULL;
if ("L".equals(signal) || "0".equals(signal))
tracker.signal = Tracker.LEVEL_LOW;
tracker.imei = m.group(9);
String message = m.group(1);
if ("".equals(message))
tracker.message = message;
message = m.group(8);
if ("".equals(message))
tracker.message = message;
if (! "".equals(tracker.imei))
{
// Save tracker data
TrackerDataAccess dataAccess = new TrackerDataAccess(context);
dataAccess.saveTracker(tracker);
try
{
Application application = Application.getApplication();
application.sendMapObject(dataAccess, tracker);
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
dataAccess.close();
context.sendBroadcast(new Intent(Application.TRACKER_DATE_RECEIVED_BROADCAST));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Show notification
boolean notifications = prefs.getBoolean(context.getString(R.string.pref_tracker_notifications), context.getResources().getBoolean(R.bool.def_notifications));
if (notifications)
{
Intent i = new Intent("com.androzic.COORDINATES_RECEIVED");
i.putExtra("title", tracker.name);
i.putExtra("sender", tracker.name);
i.putExtra("origin", context.getApplicationContext().getPackageName());
i.putExtra("lat", tracker.latitude);
i.putExtra("lon", tracker.longitude);
String msg = context.getString(R.string.notif_text, tracker.name);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(context.getString(R.string.app_name));
builder.setContentText(msg);
PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_stat_tracker);
builder.setTicker(msg);
builder.setWhen(tracker.modified);
int defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
boolean vibrate = prefs.getBoolean(context.getString(R.string.pref_tracker_vibrate), context.getResources().getBoolean(R.bool.def_vibrate));
if (vibrate)
defaults |= Notification.DEFAULT_VIBRATE;
builder.setDefaults(defaults);
builder.setAutoCancel(true);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) tracker._id, notification);
}
// Conceal SMS
boolean concealsms = prefs.getBoolean(context.getString(R.string.pref_tracker_concealsms), context.getResources().getBoolean(R.bool.def_concealsms));
if (concealsms)
abortBroadcast();
}
}
| public void onReceive(Context context, Intent intent)
{
Log.e(TAG, "SMS received");
Bundle extras = intent.getExtras();
if (extras == null)
return;
StringBuilder messageBuilder = new StringBuilder();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++)
{
SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
String text = msg.getMessageBody();
if (text == null)
continue;
messageBuilder.append(text);
}
String text = messageBuilder.toString();
Log.i(TAG, "SMS: " + text);
// Xexun family and some clones
// lat: 55.807693 long: 037.730640 speed: 000.0 03/03/13 16:18 bat:F signal:F imei:358948010446647
// lat:55.950468 long:035.867116 speed: 000.0 24/11/12 08:54 bat:F signal:F imei:358948010446647
// lat: 123.345678N long: 0.125621W speed: 001.2 17/07/11 21:34 F:3.92V,1,Signal:F help me imei:123456789012 07 83.8 234 15 006B 24C4
// lat: 22.566901 long: 114.051258 speed: 0.00 14/08/09 06.54 F:3.85V,1,Signal:F help me imei:354776031555474 05 43.5 460 01 2533 720B
// help me! lat:123.45678 long:001.23456 speed:090.00 T:17/01/11 15:14 Bat:25% Signal:F imei:1234567
// http://fiddle.re/fpfa6
Pattern pattern = Pattern.compile("(.*)?\\s?lat:\\s?([^\\s]+)\\slong:\\s?([^\\s]+)\\sspeed:\\s?([\\d\\.]+)\\s(?:T:)?([\\d/:\\.\\s]+)\\s(?:bat|F):([^\\s,]+)(?:V,\\d,)?\\s?signal:([^\\s]+)\\s(.*)?\\s?imei:(\\d+)", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(text);
if (! m.matches())
return;
Tracker tracker = new Tracker();
String latitude = m.group(2);
String longitude = m.group(3);
double coords[] = CoordinateParser.parse(latitude + " " + longitude);
if (Double.isNaN(coords[0]) || Double.isNaN(coords[1]))
return;
tracker.latitude = coords[0];
tracker.longitude = coords[1];
try
{
tracker.speed = Double.parseDouble(m.group(4)) / 3.6;
}
catch (NumberFormatException ignore)
{
}
String time = m.group(5);
try
{
Date date = XexunDateFormatter.parse(time);
tracker.modified = date.getTime();
}
catch (Exception e)
{
Log.e(TAG, "Date error", e);
}
String battery = m.group(6);
if ("F".equals(battery))
tracker.battery = Tracker.LEVEL_FULL;
if ("L".equals(battery))
tracker.battery = Tracker.LEVEL_LOW;
try
{
if (battery.endsWith("%"))
tracker.battery = Integer.parseInt(battery.substring(0, battery.length() - 1));
if (realNumber.matcher(battery).matches())
tracker.battery = (int) (Float.parseFloat(battery) * 100);
}
catch (NumberFormatException ignore)
{
}
String signal = m.group(7);
if ("F".equals(signal))
tracker.signal = Tracker.LEVEL_FULL;
if ("L".equals(signal) || "0".equals(signal))
tracker.signal = Tracker.LEVEL_LOW;
tracker.imei = m.group(9);
String message = m.group(1);
if ("".equals(message))
tracker.message = message;
message = m.group(8);
if ("".equals(message))
tracker.message = message;
if (! "".equals(tracker.imei))
{
// Save tracker data
TrackerDataAccess dataAccess = new TrackerDataAccess(context);
dataAccess.saveTracker(tracker);
try
{
Application application = Application.getApplication();
application.sendMapObject(dataAccess, tracker);
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
dataAccess.close();
context.sendBroadcast(new Intent(Application.TRACKER_DATE_RECEIVED_BROADCAST));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Show notification
boolean notifications = prefs.getBoolean(context.getString(R.string.pref_tracker_notifications), context.getResources().getBoolean(R.bool.def_notifications));
if (notifications)
{
Intent i = new Intent("com.androzic.COORDINATES_RECEIVED");
i.putExtra("title", tracker.name);
i.putExtra("sender", tracker.name);
i.putExtra("origin", context.getApplicationContext().getPackageName());
i.putExtra("lat", tracker.latitude);
i.putExtra("lon", tracker.longitude);
String msg = context.getString(R.string.notif_text, tracker.name);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(context.getString(R.string.app_name));
builder.setContentText(msg);
PendingIntent contentIntent = PendingIntent.getBroadcast(context, (int) tracker._id, i, PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_stat_tracker);
builder.setTicker(msg);
builder.setWhen(tracker.modified);
int defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
boolean vibrate = prefs.getBoolean(context.getString(R.string.pref_tracker_vibrate), context.getResources().getBoolean(R.bool.def_vibrate));
if (vibrate)
defaults |= Notification.DEFAULT_VIBRATE;
builder.setDefaults(defaults);
builder.setAutoCancel(true);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) tracker._id, notification);
}
// Conceal SMS
boolean concealsms = prefs.getBoolean(context.getString(R.string.pref_tracker_concealsms), context.getResources().getBoolean(R.bool.def_concealsms));
if (concealsms)
abortBroadcast();
}
}
|
diff --git a/src/com/android/browser/IntentHandler.java b/src/com/android/browser/IntentHandler.java
index e4b32018..2a34aba0 100644
--- a/src/com/android/browser/IntentHandler.java
+++ b/src/com/android/browser/IntentHandler.java
@@ -1,359 +1,361 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import com.android.browser.search.SearchEngine;
import com.android.common.Search;
import com.android.common.speech.LoggingEvents;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Browser;
import android.provider.MediaStore;
import android.speech.RecognizerResultsIntent;
import android.text.TextUtils;
import android.util.Patterns;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Handle all browser related intents
*/
public class IntentHandler {
// "source" parameter for Google search suggested by the browser
final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
// "source" parameter for Google search from unknown source
final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
/* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
private Activity mActivity;
private Controller mController;
private TabControl mTabControl;
private BrowserSettings mSettings;
public IntentHandler(Activity browser, Controller controller) {
mActivity = browser;
mController = controller;
mTabControl = mController.getTabControl();
mSettings = controller.getSettings();
}
void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mController.setActiveTab(current);
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) {
mController.bookmarksOrHistoryPicker(false);
return;
}
if (BrowserActivity.ACTION_SHOW_BROWSER.equals(action)) {
mController.removeComboView();
return;
}
// In case the SearchDialog is open.
((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
mActivity.sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(mActivity, mController, intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !mActivity.getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
mController.reuseTab(appTab, appId, urlData);
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
mController.switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
mController.openTabAndShow(null, urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
+ } else if ("about:debug.nav".equals(urlData.mUrl)) {
+ current.getWebView().debugDump();
} else {
mSettings.toggleDebugSettings();
}
return;
}
// Get rid of the subwindow if it exists
mController.dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
mController.loadUrlDataIn(current, urlData);
}
}
}
protected UrlData getUrlDataFromIntent(Intent intent) {
String url = "";
Map<String, String> headers = null;
if (intent != null
&& (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
url = UrlUtils.smartUrlFilter(intent.getData());
if (url != null && url.startsWith("http")) {
final Bundle pairs = intent
.getBundleExtra(Browser.EXTRA_HEADERS);
if (pairs != null && !pairs.isEmpty()) {
Iterator<String> iter = pairs.keySet().iterator();
headers = new HashMap<String, String>();
while (iter.hasNext()) {
String key = iter.next();
headers.put(key, pairs.getString(key));
}
}
}
} else if (Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)) {
url = intent.getStringExtra(SearchManager.QUERY);
if (url != null) {
// In general, we shouldn't modify URL from Intent.
// But currently, we get the user-typed URL from search box as well.
url = UrlUtils.fixUrl(url);
url = UrlUtils.smartUrlFilter(url);
String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
if (url.contains(searchSource)) {
String source = null;
final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
source = appData.getString(Search.SOURCE);
}
if (TextUtils.isEmpty(source)) {
source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
}
url = url.replace(searchSource, "&source=android-"+source+"&");
}
}
}
}
return new UrlData(url, headers, intent);
}
/**
* Launches the default web search activity with the query parameters if the given intent's data
* are identified as plain search terms and not URLs/shortcuts.
* @return true if the intent was handled and web search activity was launched, false if not.
*/
static boolean handleWebSearchIntent(Activity activity,
Controller controller, Intent intent) {
if (intent == null) return false;
String url = null;
final String action = intent.getAction();
if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
action)) {
return false;
}
if (Intent.ACTION_VIEW.equals(action)) {
Uri data = intent.getData();
if (data != null) url = data.toString();
} else if (Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)) {
url = intent.getStringExtra(SearchManager.QUERY);
}
return handleWebSearchRequest(activity, controller, url,
intent.getBundleExtra(SearchManager.APP_DATA),
intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
/**
* Launches the default web search activity with the query parameters if the given url string
* was identified as plain search terms and not URL/shortcut.
* @return true if the request was handled and web search activity was launched, false if not.
*/
private static boolean handleWebSearchRequest(Activity activity,
Controller controller, String inUrl, Bundle appData,
String extraData) {
if (inUrl == null) return false;
// In general, we shouldn't modify URL from Intent.
// But currently, we get the user-typed URL from search box as well.
String url = UrlUtils.fixUrl(inUrl).trim();
if (TextUtils.isEmpty(url)) return false;
// URLs are handled by the regular flow of control, so
// return early.
if (Patterns.WEB_URL.matcher(url).matches()
|| UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
return false;
}
final ContentResolver cr = activity.getContentResolver();
final String newUrl = url;
if (controller == null || controller.getTabControl() == null
|| controller.getTabControl().getCurrentWebView() == null
|| !controller.getTabControl().getCurrentWebView()
.isPrivateBrowsingEnabled()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unused) {
Browser.addSearchUrl(cr, newUrl);
return null;
}
}.execute();
}
SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine();
if (searchEngine == null) return false;
searchEngine.startSearch(activity, url, appData, extraData);
return true;
}
/**
* A UrlData class to abstract how the content will be set to WebView.
* This base class uses loadUrl to show the content.
*/
static class UrlData {
final String mUrl;
final Map<String, String> mHeaders;
final Intent mVoiceIntent;
UrlData(String url) {
this.mUrl = url;
this.mHeaders = null;
this.mVoiceIntent = null;
}
UrlData(String url, Map<String, String> headers, Intent intent) {
this.mUrl = url;
this.mHeaders = headers;
if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(intent.getAction())) {
this.mVoiceIntent = intent;
} else {
this.mVoiceIntent = null;
}
}
boolean isEmpty() {
return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
}
/**
* Load this UrlData into the given Tab. Use loadUrlDataIn to update
* the title bar as well.
*/
public void loadIn(Tab t) {
if (mVoiceIntent != null) {
t.activateVoiceSearchMode(mVoiceIntent);
} else {
t.getWebView().loadUrl(mUrl, mHeaders);
}
}
}
}
| true | true | void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mController.setActiveTab(current);
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) {
mController.bookmarksOrHistoryPicker(false);
return;
}
if (BrowserActivity.ACTION_SHOW_BROWSER.equals(action)) {
mController.removeComboView();
return;
}
// In case the SearchDialog is open.
((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
mActivity.sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(mActivity, mController, intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !mActivity.getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
mController.reuseTab(appTab, appId, urlData);
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
mController.switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
mController.openTabAndShow(null, urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
} else {
mSettings.toggleDebugSettings();
}
return;
}
// Get rid of the subwindow if it exists
mController.dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
mController.loadUrlDataIn(current, urlData);
}
}
}
| void onNewIntent(Intent intent) {
Tab current = mTabControl.getCurrentTab();
// When a tab is closed on exit, the current tab index is set to -1.
// Reset before proceed as Browser requires the current tab to be set.
if (current == null) {
// Try to reset the tab in case the index was incorrect.
current = mTabControl.getTab(0);
if (current == null) {
// No tabs at all so just ignore this intent.
return;
}
mController.setActiveTab(current);
}
final String action = intent.getAction();
final int flags = intent.getFlags();
if (Intent.ACTION_MAIN.equals(action) ||
(flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
// just resume the browser
return;
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) {
mController.bookmarksOrHistoryPicker(false);
return;
}
if (BrowserActivity.ACTION_SHOW_BROWSER.equals(action)) {
mController.removeComboView();
return;
}
// In case the SearchDialog is open.
((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE))
.stopSearch();
boolean activateVoiceSearch = RecognizerResultsIntent
.ACTION_VOICE_SEARCH_RESULTS.equals(action);
if (Intent.ACTION_VIEW.equals(action)
|| Intent.ACTION_SEARCH.equals(action)
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
|| Intent.ACTION_WEB_SEARCH.equals(action)
|| activateVoiceSearch) {
if (current.isInVoiceSearchMode()) {
String title = current.getVoiceDisplayTitle();
if (title != null && title.equals(intent.getStringExtra(
SearchManager.QUERY))) {
// The user submitted the same search as the last voice
// search, so do nothing.
return;
}
if (Intent.ACTION_SEARCH.equals(action)
&& current.voiceSearchSourceIsGoogle()) {
Intent logIntent = new Intent(
LoggingEvents.ACTION_LOG_EVENT);
logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
LoggingEvents.VoiceSearch.QUERY_UPDATED);
logIntent.putExtra(
LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
intent.getDataString());
mActivity.sendBroadcast(logIntent);
// Note, onPageStarted will revert the voice title bar
// When http://b/issue?id=2379215 is fixed, we should update
// the title bar here.
}
}
// If this was a search request (e.g. search query directly typed into the address bar),
// pass it on to the default web search provider.
if (handleWebSearchIntent(mActivity, mController, intent)) {
return;
}
UrlData urlData = getUrlDataFromIntent(intent);
if (urlData.isEmpty()) {
urlData = new UrlData(mSettings.getHomePage());
}
final String appId = intent
.getStringExtra(Browser.EXTRA_APPLICATION_ID);
if ((Intent.ACTION_VIEW.equals(action)
// If a voice search has no appId, it means that it came
// from the browser. In that case, reuse the current tab.
|| (activateVoiceSearch && appId != null))
&& !mActivity.getPackageName().equals(appId)
&& (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Tab appTab = mTabControl.getTabFromId(appId);
if (appTab != null) {
mController.reuseTab(appTab, appId, urlData);
return;
} else {
// No matching application tab, try to find a regular tab
// with a matching url.
appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
if (appTab != null) {
if (current != appTab) {
mController.switchToTab(mTabControl.getTabIndex(appTab));
}
// Otherwise, we are already viewing the correct tab.
} else {
// if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
// will be opened in a new tab unless we have reached
// MAX_TABS. Then the url will be opened in the current
// tab. If a new tab is created, it will have "true" for
// exit on close.
mController.openTabAndShow(null, urlData, true, appId);
}
}
} else {
if (!urlData.isEmpty()
&& urlData.mUrl.startsWith("about:debug")) {
if ("about:debug.dom".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(false);
} else if ("about:debug.dom.file".equals(urlData.mUrl)) {
current.getWebView().dumpDomTree(true);
} else if ("about:debug.render".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(false);
} else if ("about:debug.render.file".equals(urlData.mUrl)) {
current.getWebView().dumpRenderTree(true);
} else if ("about:debug.display".equals(urlData.mUrl)) {
current.getWebView().dumpDisplayTree();
} else if ("about:debug.nav".equals(urlData.mUrl)) {
current.getWebView().debugDump();
} else {
mSettings.toggleDebugSettings();
}
return;
}
// Get rid of the subwindow if it exists
mController.dismissSubWindow(current);
// If the current Tab is being used as an application tab,
// remove the association, since the new Intent means that it is
// no longer associated with that application.
current.setAppId(null);
mController.loadUrlDataIn(current, urlData);
}
}
}
|
diff --git a/ProcessClaim.java b/ProcessClaim.java
index d771f13..da5e2eb 100644
--- a/ProcessClaim.java
+++ b/ProcessClaim.java
@@ -1,62 +1,62 @@
package jdressel.Derporia64;
//James Dressel and James Robertson
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Iterator;
import java.util.*;
public class ProcessClaim extends HttpServlet {
private String claim;
private String assertions;
private String username;
public void doGet(HttpServletRequest request, HttpServletResponse res)
throws ServletException, IOException {
/*
* Send the user back to where they belong
*/
String destination="http://apps-swe432.vse.gmu.edu:8080/swe432/jsp/jdressel/Derporia64/Derporia.jsp";
res.sendRedirect(res.encodeRedirectURL(destination));
}
public void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = request.getSession();
setClaimAssertion(request);
if(session.getAttribute("username")==null){
res.sendRedirect(res.encodeRedirectURL("http://apps-swe432.vse.gmu.edu:8080/swe432/jsp/jdressel/Derporia64/Login.jsp"));//ERROR, send the user back
} else {
- Assertion a = new Assertion((String)session.getAttribute("username").toString(), claim, assertions);
+ Assertion a = new Assertion(session.getAttribute("username").toString(), claim, assertions);
if(getServletContext().getAttribute("jdresselAssertionSet")==null){
Set<Assertion> assertions = new HashSet<Assertion>();
getServletContext().setAttribute("jdresselAssertionSet",assertions);
}
Object d = getServletContext().getAttribute("jdresselAssertionSet");
Set setOfAssets = (Set)d;
setOfAssets.add(a);
getServletContext().setAttribute("jdresselAssertionSet",setOfAssets);
res.sendRedirect(res.encodeRedirectURL("http://apps-swe432.vse.gmu.edu:8080/swe432/servlet/jdressel.Derporia64.Voting"));
}
}
private void setClaimAssertion(HttpServletRequest request){
claim = request.getParameter("claim")==null ? "" : request.getParameter("claim");
assertions = request.getParameter("assertions")==null ? "" : request.getParameter("assertions");
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = request.getSession();
setClaimAssertion(request);
if(session.getAttribute("username")==null){
res.sendRedirect(res.encodeRedirectURL("http://apps-swe432.vse.gmu.edu:8080/swe432/jsp/jdressel/Derporia64/Login.jsp"));//ERROR, send the user back
} else {
Assertion a = new Assertion((String)session.getAttribute("username").toString(), claim, assertions);
if(getServletContext().getAttribute("jdresselAssertionSet")==null){
Set<Assertion> assertions = new HashSet<Assertion>();
getServletContext().setAttribute("jdresselAssertionSet",assertions);
}
Object d = getServletContext().getAttribute("jdresselAssertionSet");
Set setOfAssets = (Set)d;
setOfAssets.add(a);
getServletContext().setAttribute("jdresselAssertionSet",setOfAssets);
res.sendRedirect(res.encodeRedirectURL("http://apps-swe432.vse.gmu.edu:8080/swe432/servlet/jdressel.Derporia64.Voting"));
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = request.getSession();
setClaimAssertion(request);
if(session.getAttribute("username")==null){
res.sendRedirect(res.encodeRedirectURL("http://apps-swe432.vse.gmu.edu:8080/swe432/jsp/jdressel/Derporia64/Login.jsp"));//ERROR, send the user back
} else {
Assertion a = new Assertion(session.getAttribute("username").toString(), claim, assertions);
if(getServletContext().getAttribute("jdresselAssertionSet")==null){
Set<Assertion> assertions = new HashSet<Assertion>();
getServletContext().setAttribute("jdresselAssertionSet",assertions);
}
Object d = getServletContext().getAttribute("jdresselAssertionSet");
Set setOfAssets = (Set)d;
setOfAssets.add(a);
getServletContext().setAttribute("jdresselAssertionSet",setOfAssets);
res.sendRedirect(res.encodeRedirectURL("http://apps-swe432.vse.gmu.edu:8080/swe432/servlet/jdressel.Derporia64.Voting"));
}
}
|
diff --git a/src/minecraft/assemblyline/common/machine/TileEntityManipulator.java b/src/minecraft/assemblyline/common/machine/TileEntityManipulator.java
index 9c0c75f1..25a3bbe5 100644
--- a/src/minecraft/assemblyline/common/machine/TileEntityManipulator.java
+++ b/src/minecraft/assemblyline/common/machine/TileEntityManipulator.java
@@ -1,546 +1,546 @@
package assemblyline.common.machine;
import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.implement.IRedstoneReceptor;
import universalelectricity.prefab.implement.IRotatable;
import universalelectricity.prefab.multiblock.TileEntityMulti;
import universalelectricity.prefab.network.PacketManager;
import assemblyline.api.IManipulator;
import assemblyline.common.block.BlockCrate;
import assemblyline.common.block.TileEntityCrate;
import assemblyline.common.imprinter.prefab.TileEntityFilterable;
import cpw.mods.fml.common.network.PacketDispatcher;
public class TileEntityManipulator extends TileEntityFilterable implements IRotatable, IRedstoneReceptor, IManipulator
{
public boolean selfPulse = false;
/**
* Is the manipulator wrenched to turn into output mode?
*/
private boolean isOutput = false;
private boolean isRedstonePowered = false;
public boolean isOutput()
{
return this.isOutput;
}
public void setOutput(boolean isOutput)
{
this.isOutput = isOutput;
if (!this.worldObj.isRemote)
{
PacketDispatcher.sendPacketToAllPlayers(this.getDescriptionPacket());
}
}
public void toggleOutput()
{
this.setOutput(!this.isOutput());
}
@Override
protected void onUpdate()
{
if (!this.worldObj.isRemote)
{
if (this.ticks % 20 == 0)
{
PacketManager.sendPacketToClients(this.getDescriptionPacket(), this.worldObj, new Vector3(this), 20);
}
if (!this.isDisabled() && this.isRunning())
{
if (!this.isOutput)
{
this.inject();
}
else
{
if (this.selfPulse && this.ticks % 10 == 0)
{
this.isRedstonePowered = true;
}
/**
* Finds the connected inventory and outputs the items upon a redstone pulse.
*/
if (this.isRedstonePowered)
{
this.eject();
}
}
}
}
}
/**
* Find items going into the manipulator and input them into an inventory behind this
* manipulator.
*/
@Override
public void inject()
{
Vector3 inputPosition = new Vector3(this);
Vector3 outputUp = new Vector3(this);
outputUp.modifyPositionFromSide(ForgeDirection.UP);
Vector3 outputDown = new Vector3(this);
outputDown.modifyPositionFromSide(ForgeDirection.DOWN);
Vector3 outputPosition = new Vector3(this);
outputPosition.modifyPositionFromSide(this.getDirection().getOpposite());
/**
* Prevents manipulators from spamming and duping items.
*/
if (outputPosition.getTileEntity(this.worldObj) instanceof TileEntityManipulator)
{
if (((TileEntityManipulator) outputPosition.getTileEntity(this.worldObj)).getDirection() == this.getDirection().getOpposite())
{
return;
}
}
AxisAlignedBB bounds = AxisAlignedBB.getBoundingBox(inputPosition.x, inputPosition.y, inputPosition.z, inputPosition.x + 1, inputPosition.y + 1, inputPosition.z + 1);
List<EntityItem> itemsInBound = this.worldObj.getEntitiesWithinAABB(EntityItem.class, bounds);
for (EntityItem entity : itemsInBound)
{
if (entity.isDead)
continue;
/**
* Try top first, then bottom, then the sides to see if it is possible to insert the
* item into a inventory.
*/
ItemStack remainingStack = entity.getEntityItem().copy();
if (this.getFilter() == null || this.isFiltering(remainingStack))
{
remainingStack = this.tryPlaceInPosition(remainingStack, outputUp, ForgeDirection.DOWN);
if (remainingStack != null)
{
remainingStack = this.tryPlaceInPosition(remainingStack, outputDown, ForgeDirection.UP);
}
if (remainingStack != null)
{
remainingStack = this.tryPlaceInPosition(remainingStack, outputPosition, this.getDirection().getOpposite());
}
if (remainingStack != null && remainingStack.stackSize > 0)
{
this.throwItem(outputPosition, remainingStack);
}
entity.setDead();
}
}
}
/**
* Inject items
*/
@Override
public void eject()
{
this.onPowerOff();
Vector3 inputUp = new Vector3(this);
inputUp.modifyPositionFromSide(ForgeDirection.UP);
Vector3 inputDown = new Vector3(this);
inputDown.modifyPositionFromSide(ForgeDirection.DOWN);
Vector3 inputPosition = new Vector3(this);
inputPosition.modifyPositionFromSide(this.getDirection().getOpposite());
Vector3 outputPosition = new Vector3(this);
outputPosition.modifyPositionFromSide(this.getDirection());
ItemStack itemStack = this.tryGrabFromPosition(inputUp, ForgeDirection.DOWN);
if (itemStack == null)
{
itemStack = this.tryGrabFromPosition(inputDown, ForgeDirection.UP);
}
if (itemStack == null)
{
itemStack = this.tryGrabFromPosition(inputPosition, this.getDirection().getOpposite());
}
if (itemStack != null)
{
if (itemStack.stackSize > 0)
{
this.throwItem(outputPosition, itemStack);
}
}
}
/**
* Throws the items from the manipulator into the world.
*
* @param outputPosition
* @param items
*/
public void throwItem(Vector3 outputPosition, ItemStack items)
{
if (!this.worldObj.isRemote)
{
EntityItem entityItem = new EntityItem(this.worldObj, outputPosition.x + 0.5, outputPosition.y + 0.8, outputPosition.z + 0.5, items);
entityItem.motionX = 0;
entityItem.motionZ = 0;
entityItem.motionY /= 5;
entityItem.delayBeforeCanPickup = 20;
this.worldObj.spawnEntityInWorld(entityItem);
}
}
/**
* Tries to place an itemStack in a specific position if it is an inventory.
*
* @return The ItemStack remained after place attempt
*/
private ItemStack tryPlaceInPosition(ItemStack itemStack, Vector3 position, ForgeDirection direction)
{
TileEntity tileEntity = position.getTileEntity(this.worldObj);
if (tileEntity != null && itemStack != null)
{
/**
* Try to put items into a chest.
*/
if (tileEntity instanceof TileEntityMulti)
{
Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition;
if (mainBlockPosition != null)
{
if (!(mainBlockPosition.getTileEntity(this.worldObj) instanceof TileEntityMulti))
return tryPlaceInPosition(itemStack, mainBlockPosition, direction);
}
}
else if (tileEntity instanceof TileEntityChest)
{
TileEntityChest[] chests = { (TileEntityChest) tileEntity, null };
/**
* Try to find a double chest.
*/
for (int i = 2; i < 6; i++)
{
ForgeDirection searchDirection = ForgeDirection.getOrientation(i);
Vector3 searchPosition = position.clone();
searchPosition.modifyPositionFromSide(searchDirection);
if (searchPosition.getTileEntity(this.worldObj) != null)
{
if (searchPosition.getTileEntity(this.worldObj).getClass() == chests[0].getClass())
{
chests[1] = (TileEntityChest) searchPosition.getTileEntity(this.worldObj);
break;
}
}
}
for (TileEntityChest chest : chests)
{
if (chest != null)
{
for (int i = 0; i < chest.getSizeInventory(); i++)
{
itemStack = this.addStackToInventory(i, chest, itemStack);
if (itemStack == null)
{
return null;
}
}
}
}
}
else if (tileEntity instanceof TileEntityCrate)
{
return BlockCrate.addStackToCrate((TileEntityCrate) tileEntity, itemStack);
}
else if (tileEntity instanceof ISidedInventory)
{
ISidedInventory inventory = (ISidedInventory) tileEntity;
int[] slots = inventory.getAccessibleSlotsFromSide(direction.getOpposite().ordinal());
for (int i = 0; i < slots.length; i++)
{
if (inventory.canInsertItem(slots[i], itemStack, direction.getOpposite().ordinal()))
{
- itemStack = this.addStackToInventory(i, inventory, itemStack);
+ itemStack = this.addStackToInventory(slots[i], inventory, itemStack);
}
if (itemStack == null)
{
return null;
}
}
}
else if (tileEntity instanceof net.minecraftforge.common.ISidedInventory)
{
net.minecraftforge.common.ISidedInventory inventory = (net.minecraftforge.common.ISidedInventory) tileEntity;
int startIndex = inventory.getStartInventorySide(direction.getOpposite());
for (int i = startIndex; i < startIndex + inventory.getSizeInventorySide(direction); i++)
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
if (itemStack == null)
{
return null;
}
}
}
else if (tileEntity instanceof IInventory)
{
IInventory inventory = (IInventory) tileEntity;
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
if (itemStack == null)
{
return null;
}
}
}
}
if (itemStack.stackSize <= 0)
{
return null;
}
return itemStack;
}
public ItemStack addStackToInventory(int slotIndex, IInventory inventory, ItemStack itemStack)
{
if (inventory.getSizeInventory() > slotIndex)
{
ItemStack stackInInventory = inventory.getStackInSlot(slotIndex);
if (stackInInventory == null)
{
inventory.setInventorySlotContents(slotIndex, itemStack);
if (inventory.getStackInSlot(slotIndex) == null)
{
return itemStack;
}
return null;
}
else if (stackInInventory.isItemEqual(itemStack) && stackInInventory.isStackable())
{
stackInInventory = stackInInventory.copy();
int stackLim = Math.min(inventory.getInventoryStackLimit(), itemStack.getMaxStackSize());
int rejectedAmount = Math.max((stackInInventory.stackSize + itemStack.stackSize) - stackLim, 0);
stackInInventory.stackSize = Math.min(Math.max((stackInInventory.stackSize + itemStack.stackSize - rejectedAmount), 0), inventory.getInventoryStackLimit());
itemStack.stackSize = rejectedAmount;
inventory.setInventorySlotContents(slotIndex, stackInInventory);
}
}
if (itemStack.stackSize <= 0)
{
return null;
}
return itemStack;
}
/**
* Tries to take a item from a inventory at a specific position.
*
* @param position
* @return
*/
private ItemStack tryGrabFromPosition(Vector3 position, ForgeDirection direction)
{
ItemStack returnStack = null;
TileEntity tileEntity = position.getTileEntity(this.worldObj);
if (tileEntity != null)
{
/**
* Try to put items into a chest.
*/
if (tileEntity instanceof TileEntityMulti)
{
Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition;
if (mainBlockPosition != null)
{
if (!(mainBlockPosition.getTileEntity(this.worldObj) instanceof TileEntityMulti))
return tryGrabFromPosition(mainBlockPosition, direction);
}
}
else if (tileEntity instanceof TileEntityChest)
{
TileEntityChest[] chests = { (TileEntityChest) tileEntity, null };
/**
* Try to find a double chest.
*/
for (int i = 2; i < 6; i++)
{
ForgeDirection searchDirection = ForgeDirection.getOrientation(i);
Vector3 searchPosition = position.clone();
searchPosition.modifyPositionFromSide(searchDirection);
if (searchPosition.getTileEntity(this.worldObj) != null)
{
if (searchPosition.getTileEntity(this.worldObj).getClass() == chests[0].getClass())
{
chests[1] = (TileEntityChest) searchPosition.getTileEntity(this.worldObj);
break;
}
}
}
chestSearch:
for (TileEntityChest chest : chests)
{
if (chest != null)
{
for (int i = 0; i < chest.getSizeInventory(); i++)
{
ItemStack itemStack = this.removeStackFromInventory(i, chest);
if (itemStack != null)
{
returnStack = itemStack;
break chestSearch;
}
}
}
}
}
else if (tileEntity instanceof ISidedInventory)
{
ISidedInventory inventory = (ISidedInventory) tileEntity;
int[] slots = inventory.getAccessibleSlotsFromSide(direction.ordinal());
for (int i = 0; i < slots.length; i++)
{
int slot = slots[i];
ItemStack itemStack = this.removeStackFromInventory(i, inventory);
if (itemStack != null && inventory.canExtractItem(slot, itemStack, direction.ordinal()))
{
returnStack = itemStack;
break;
}
}
}
else if (tileEntity instanceof net.minecraftforge.common.ISidedInventory)
{
net.minecraftforge.common.ISidedInventory inventory = (net.minecraftforge.common.ISidedInventory) tileEntity;
int startIndex = inventory.getStartInventorySide(direction);
for (int i = startIndex; i < startIndex + inventory.getSizeInventorySide(direction); i++)
{
ItemStack itemStack = this.removeStackFromInventory(i, inventory);
if (itemStack != null)
{
returnStack = itemStack;
break;
}
}
}
else if (tileEntity instanceof IInventory)
{
IInventory inventory = (IInventory) tileEntity;
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
ItemStack itemStack = this.removeStackFromInventory(i, inventory);
if (itemStack != null)
{
returnStack = itemStack;
break;
}
}
}
}
return returnStack;
}
public ItemStack removeStackFromInventory(int slotIndex, IInventory inventory)
{
if (inventory.getStackInSlot(slotIndex) != null)
{
ItemStack itemStack = inventory.getStackInSlot(slotIndex).copy();
if (this.getFilter() == null || this.isFiltering(itemStack))
{
itemStack.stackSize = 1;
inventory.decrStackSize(slotIndex, 1);
return itemStack;
}
}
return null;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
this.isOutput = nbt.getBoolean("isOutput");
this.selfPulse = nbt.getBoolean("selfpulse");
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setBoolean("isOutput", this.isOutput);
nbt.setBoolean("selfpulse", this.selfPulse);
}
@Override
public void onPowerOn()
{
this.isRedstonePowered = true;
}
@Override
public void onPowerOff()
{
this.isRedstonePowered = false;
}
@Override
public boolean canConnect(ForgeDirection dir)
{
return dir != this.getDirection();
}
}
| true | true | private ItemStack tryPlaceInPosition(ItemStack itemStack, Vector3 position, ForgeDirection direction)
{
TileEntity tileEntity = position.getTileEntity(this.worldObj);
if (tileEntity != null && itemStack != null)
{
/**
* Try to put items into a chest.
*/
if (tileEntity instanceof TileEntityMulti)
{
Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition;
if (mainBlockPosition != null)
{
if (!(mainBlockPosition.getTileEntity(this.worldObj) instanceof TileEntityMulti))
return tryPlaceInPosition(itemStack, mainBlockPosition, direction);
}
}
else if (tileEntity instanceof TileEntityChest)
{
TileEntityChest[] chests = { (TileEntityChest) tileEntity, null };
/**
* Try to find a double chest.
*/
for (int i = 2; i < 6; i++)
{
ForgeDirection searchDirection = ForgeDirection.getOrientation(i);
Vector3 searchPosition = position.clone();
searchPosition.modifyPositionFromSide(searchDirection);
if (searchPosition.getTileEntity(this.worldObj) != null)
{
if (searchPosition.getTileEntity(this.worldObj).getClass() == chests[0].getClass())
{
chests[1] = (TileEntityChest) searchPosition.getTileEntity(this.worldObj);
break;
}
}
}
for (TileEntityChest chest : chests)
{
if (chest != null)
{
for (int i = 0; i < chest.getSizeInventory(); i++)
{
itemStack = this.addStackToInventory(i, chest, itemStack);
if (itemStack == null)
{
return null;
}
}
}
}
}
else if (tileEntity instanceof TileEntityCrate)
{
return BlockCrate.addStackToCrate((TileEntityCrate) tileEntity, itemStack);
}
else if (tileEntity instanceof ISidedInventory)
{
ISidedInventory inventory = (ISidedInventory) tileEntity;
int[] slots = inventory.getAccessibleSlotsFromSide(direction.getOpposite().ordinal());
for (int i = 0; i < slots.length; i++)
{
if (inventory.canInsertItem(slots[i], itemStack, direction.getOpposite().ordinal()))
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
}
if (itemStack == null)
{
return null;
}
}
}
else if (tileEntity instanceof net.minecraftforge.common.ISidedInventory)
{
net.minecraftforge.common.ISidedInventory inventory = (net.minecraftforge.common.ISidedInventory) tileEntity;
int startIndex = inventory.getStartInventorySide(direction.getOpposite());
for (int i = startIndex; i < startIndex + inventory.getSizeInventorySide(direction); i++)
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
if (itemStack == null)
{
return null;
}
}
}
else if (tileEntity instanceof IInventory)
{
IInventory inventory = (IInventory) tileEntity;
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
if (itemStack == null)
{
return null;
}
}
}
}
if (itemStack.stackSize <= 0)
{
return null;
}
return itemStack;
}
| private ItemStack tryPlaceInPosition(ItemStack itemStack, Vector3 position, ForgeDirection direction)
{
TileEntity tileEntity = position.getTileEntity(this.worldObj);
if (tileEntity != null && itemStack != null)
{
/**
* Try to put items into a chest.
*/
if (tileEntity instanceof TileEntityMulti)
{
Vector3 mainBlockPosition = ((TileEntityMulti) tileEntity).mainBlockPosition;
if (mainBlockPosition != null)
{
if (!(mainBlockPosition.getTileEntity(this.worldObj) instanceof TileEntityMulti))
return tryPlaceInPosition(itemStack, mainBlockPosition, direction);
}
}
else if (tileEntity instanceof TileEntityChest)
{
TileEntityChest[] chests = { (TileEntityChest) tileEntity, null };
/**
* Try to find a double chest.
*/
for (int i = 2; i < 6; i++)
{
ForgeDirection searchDirection = ForgeDirection.getOrientation(i);
Vector3 searchPosition = position.clone();
searchPosition.modifyPositionFromSide(searchDirection);
if (searchPosition.getTileEntity(this.worldObj) != null)
{
if (searchPosition.getTileEntity(this.worldObj).getClass() == chests[0].getClass())
{
chests[1] = (TileEntityChest) searchPosition.getTileEntity(this.worldObj);
break;
}
}
}
for (TileEntityChest chest : chests)
{
if (chest != null)
{
for (int i = 0; i < chest.getSizeInventory(); i++)
{
itemStack = this.addStackToInventory(i, chest, itemStack);
if (itemStack == null)
{
return null;
}
}
}
}
}
else if (tileEntity instanceof TileEntityCrate)
{
return BlockCrate.addStackToCrate((TileEntityCrate) tileEntity, itemStack);
}
else if (tileEntity instanceof ISidedInventory)
{
ISidedInventory inventory = (ISidedInventory) tileEntity;
int[] slots = inventory.getAccessibleSlotsFromSide(direction.getOpposite().ordinal());
for (int i = 0; i < slots.length; i++)
{
if (inventory.canInsertItem(slots[i], itemStack, direction.getOpposite().ordinal()))
{
itemStack = this.addStackToInventory(slots[i], inventory, itemStack);
}
if (itemStack == null)
{
return null;
}
}
}
else if (tileEntity instanceof net.minecraftforge.common.ISidedInventory)
{
net.minecraftforge.common.ISidedInventory inventory = (net.minecraftforge.common.ISidedInventory) tileEntity;
int startIndex = inventory.getStartInventorySide(direction.getOpposite());
for (int i = startIndex; i < startIndex + inventory.getSizeInventorySide(direction); i++)
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
if (itemStack == null)
{
return null;
}
}
}
else if (tileEntity instanceof IInventory)
{
IInventory inventory = (IInventory) tileEntity;
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
itemStack = this.addStackToInventory(i, inventory, itemStack);
if (itemStack == null)
{
return null;
}
}
}
}
if (itemStack.stackSize <= 0)
{
return null;
}
return itemStack;
}
|
diff --git a/src/wvulaunchpad3/XMLWriter.java b/src/wvulaunchpad3/XMLWriter.java
index a681b46..1b96eb2 100644
--- a/src/wvulaunchpad3/XMLWriter.java
+++ b/src/wvulaunchpad3/XMLWriter.java
@@ -1,80 +1,80 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wvulaunchpad3;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author dom
*/
public class XMLWriter {
private Set set;
private String setViewXML;
public XMLWriter(Set set) {
setViewXML = set.toXML();
this.set = set;
}
public XMLWriter() {
}
public void write() throws FileNotFoundException, IOException {
FileWriter fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml");
fw.write(this.setViewXML);
fw.close();
String[] params = new String[6];
params[0] = "python";
params[1] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/xmlWriter.py";
params[2] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/beginning.xml";
params[3] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml";
params[4] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/end.xml";
params[5] = "/home/calvr/setconfig/runtimeConfig.xml";
Runtime.getRuntime().exec(params);
}
public void write(String specifiedFilePath) throws FileNotFoundException, IOException {
String description = set.getDescription() + "\n";
description += "Cells:\n";
ArrayList<Cell> cells = set.getCells();
for (Cell cell : cells){
description += cell + "\n";
}
FileWriter fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/description.xml");
fw.write("<desc>\n");
fw.write(description);
fw.write("</desc>");
fw.close();
fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml");
fw.write(this.setViewXML);
fw.close();
- String[] params = new String[6];
+ String[] params = new String[7];
params[0] = "python";
params[1] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/xmlWriter.py";
params[2] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/description.xml";
params[3] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/beginning.xml";
params[4] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml";
params[5] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/end.xml";
params[6] = specifiedFilePath;
Runtime.getRuntime().exec(params);
}
public void copyOver(String specifiedFilePath) throws FileNotFoundException, IOException {
String[] params = new String[6];
params[0] = "python";
params[1] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/xmlWriter.py";
params[2] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/empty.xml";
params[3] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/empty.xml";
params[4] = specifiedFilePath;
params[5] = "/home/calvr/setconfig/runtimeConfig.xml";
Runtime.getRuntime().exec(params);
}
}
| true | true | public void write(String specifiedFilePath) throws FileNotFoundException, IOException {
String description = set.getDescription() + "\n";
description += "Cells:\n";
ArrayList<Cell> cells = set.getCells();
for (Cell cell : cells){
description += cell + "\n";
}
FileWriter fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/description.xml");
fw.write("<desc>\n");
fw.write(description);
fw.write("</desc>");
fw.close();
fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml");
fw.write(this.setViewXML);
fw.close();
String[] params = new String[6];
params[0] = "python";
params[1] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/xmlWriter.py";
params[2] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/description.xml";
params[3] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/beginning.xml";
params[4] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml";
params[5] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/end.xml";
params[6] = specifiedFilePath;
Runtime.getRuntime().exec(params);
}
| public void write(String specifiedFilePath) throws FileNotFoundException, IOException {
String description = set.getDescription() + "\n";
description += "Cells:\n";
ArrayList<Cell> cells = set.getCells();
for (Cell cell : cells){
description += cell + "\n";
}
FileWriter fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/description.xml");
fw.write("<desc>\n");
fw.write(description);
fw.write("</desc>");
fw.close();
fw = new FileWriter("/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml");
fw.write(this.setViewXML);
fw.close();
String[] params = new String[7];
params[0] = "python";
params[1] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/xmlWriter.py";
params[2] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/description.xml";
params[3] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/beginning.xml";
params[4] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/middle.xml";
params[5] = "/home/calvr/NetBeansProjects/WVULaunchPad3/src/wvulaunchpad3/end.xml";
params[6] = specifiedFilePath;
Runtime.getRuntime().exec(params);
}
|
diff --git a/src/org/eclipse/core/internal/localstore/BlobStore.java b/src/org/eclipse/core/internal/localstore/BlobStore.java
index c95d2dca..2fff5e8b 100644
--- a/src/org/eclipse/core/internal/localstore/BlobStore.java
+++ b/src/org/eclipse/core/internal/localstore/BlobStore.java
@@ -1,167 +1,167 @@
/**********************************************************************
* Copyright (c) 2000,2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
**********************************************************************/
package org.eclipse.core.internal.localstore;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.runtime.*;
import org.eclipse.core.internal.localstore.FileSystemStore;
import org.eclipse.core.internal.resources.ResourceException;
import org.eclipse.core.internal.utils.*;
import java.io.*;
import java.util.*;
//
public class BlobStore {
protected File storeLocation;
protected FileSystemStore localStore;
/** Limits the range of directories' names. */
protected byte mask;
//private static short[] randomArray = {213, 231, 37, 85, 211, 29, 161, 175, 187, 3, 147, 246, 170, 30, 202, 183, 242, 47, 254, 189, 25, 248, 193, 2, 119, 133, 125, 12, 76, 213, 219, 79, 69, 133, 202, 80, 150, 190, 157, 190, 80, 190, 219, 150, 169, 117, 95, 10, 77, 214, 233, 70, 5, 188, 44, 91, 165, 149, 177, 93, 17, 112, 4, 41, 230, 148, 188, 107, 213, 31, 52, 60, 111, 246, 226, 121, 129, 197, 144, 248, 92, 133, 96, 116, 104, 67, 74, 144, 185, 141, 96, 34, 182, 90, 36, 217, 28, 205, 107, 52, 201, 14, 8, 1, 27, 216, 60, 35, 251, 194, 7, 156, 32, 5, 145, 29, 96, 61, 110, 145, 50, 56, 235, 239, 170, 138, 17, 211, 56, 98, 101, 126, 27, 57, 211, 144, 206, 207, 179, 111, 160, 50, 243, 69, 106, 118, 155, 159, 28, 57, 11, 175, 43, 173, 96, 181, 99, 169, 171, 156, 246, 243, 30, 198, 251, 81, 77, 92, 160, 235, 215, 187, 23, 71, 58, 247, 127, 56, 118, 132, 79, 188, 42, 188, 158, 121, 255, 65, 154, 118, 172, 217, 4, 47, 105, 204, 135, 27, 43, 90, 9, 31, 59, 115, 193, 28, 55, 101, 9, 117, 211, 112, 61, 55, 23, 235, 51, 104, 123, 138, 76, 148, 115, 119, 81, 54, 39, 46, 149, 191, 79, 16, 222, 69, 219, 136, 148, 181, 77, 250, 101, 223, 140, 194, 141, 44, 195, 217, 31, 223, 207, 149, 245, 115, 243, 183};
private static byte[] randomArray = {-43, -25, 37, 85, -45, 29, -95, -81, -69, 3, -109, -10, -86, 30, -54, -73, -14, 47, -2, -67, 25, -8, -63, 2, 119, -123, 125, 12, 76, -43, -37, 79, 69, -123, -54, 80, -106, -66, -99, -66, 80, -66, -37, -106, -87, 117, 95, 10, 77, -42, -23, 70, 5, -68, 44, 91, -91, -107, -79, 93, 17, 112, 4, 41, -26, -108, -68, 107, -43, 31, 52, 60, 111, -10, -30, 121, -127, -59, -112, -8, 92, -123, 96, 116, 104, 67, 74, -112, -71, -115, 96, 34, -74, 90, 36, -39, 28, -51, 107, 52, -55, 14, 8, 1, 27, -40, 60, 35, -5, -62, 7, -100, 32, 5, -111, 29, 96, 61, 110, -111, 50, 56, -21, -17, -86, -118, 17, -45, 56, 98, 101, 126, 27, 57, -45, -112, -50, -49, -77, 111, -96, 50, -13, 69, 106, 118, -101, -97, 28, 57, 11, -81, 43, -83, 96, -75, 99, -87, -85, -100, -10, -13, 30, -58, -5, 81, 77, 92, -96, -21, -41, -69, 23, 71, 58, -9, 127, 56, 118, -124, 79, -68, 42, -68, -98, 121, -1, 65, -102, 118, -84, -39, 4, 47, 105, -52, -121, 27, 43, 90, 9, 31, 59, 115, -63, 28, 55, 101, 9, 117, -45, 112, 61, 55, 23, -21, 51, 104, 123, -118, 76, -108, 115, 119, 81, 54, 39, 46, -107, -65, 79, 16, -34, 69, -37, -120, -108, -75, 77, -6, 101, -33, -116, -62, -115, 44, -61, -39, 31, -33, -49, -107, -11, 115, -13, -73,};
/**
* The limit is the maximum number of directories managed by this store.
* This number must be power of 2 and do not exceed 256. The location
* should be an existing valid directory.
*/
public BlobStore(IPath location, int limit) {
Assert.isNotNull(location);
Assert.isTrue(!location.equals(Path.EMPTY));
storeLocation = location.toFile();
Assert.isTrue(storeLocation.isDirectory());
Assert.isTrue(limit == 256 || limit == 128 || limit == 64 || limit == 32 || limit == 16 || limit == 8 || limit == 4 || limit == 2 || limit == 1);
mask = (byte) (limit - 1);
localStore = new FileSystemStore();
}
public UniversalUniqueIdentifier addBlob(File target, boolean moveContents) throws CoreException {
UniversalUniqueIdentifier uuid = new UniversalUniqueIdentifier();
File dir = folderFor(uuid);
if (!dir.exists())
if (!dir.mkdirs()) {
- String message = Policy.bind("fileOverFolder", dir.getAbsolutePath()); //$NON-NLS-1$
+ String message = Policy.bind("localstore.couldNotCreateFolder", dir.getAbsolutePath()); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.FAILED_WRITE_LOCAL, new Path(dir.getAbsolutePath()), message, null);
}
File destination = fileFor(uuid);
if (moveContents)
localStore.move(target, destination, true, null);
else
localStore.copy(target, destination, IResource.DEPTH_ZERO, null);
return uuid;
}
/**
* @see UniversalUniqueIdentifier#appendByteString
*/
private void appendByteString(StringBuffer buffer, byte value) {
String hexString;
if (value < 0)
hexString = Integer.toHexString(256 + value);
else
hexString = Integer.toHexString(value);
if (hexString.length() == 1)
buffer.append("0"); //$NON-NLS-1$
buffer.append(hexString);
}
/**
* Converts an array of bytes into a String.
*
* @see UniversalUniqueIdentifier#toString
*/
private String bytesToHexString(byte[] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; i++)
appendByteString(buffer, b[i]);
return buffer.toString();
}
/**
* Deletes a blobFile and if the directory becomes empty it is also
* deleted. If the file does not exist, do nothing.
*/
protected boolean delete(File blobFile) {
CoreFileSystemLibrary.setReadOnly(blobFile.getAbsolutePath(), false);
boolean deleted = blobFile.delete();
deleteEmptyDir(new File(blobFile.getParent()));
return deleted;
}
public void deleteAll() {
deleteAll(storeLocation);
}
public void deleteAll(File root) {
if (root.isDirectory()) {
String[] list = root.list();
if (list != null)
for (int i = 0; i < list.length; i++)
deleteAll(new File(root, list[i]));
}
root.delete();
}
public boolean deleteBlob(String uuid) {
return deleteBlob(new UniversalUniqueIdentifier(uuid));
}
/**
* Deletes a blobFile and if the directory becomes empty it is also
* deleted. Returns true if the blob was deleted.
*/
public boolean deleteBlob(UniversalUniqueIdentifier uuid) {
Assert.isNotNull(uuid);
return delete(fileFor(uuid));
}
protected boolean deleteEmptyDir(File dir) {
if (dir.exists()) {
String[] list = dir.list();
if (list != null && list.length == 0)
return dir.delete();
}
return false;
}
public File fileFor(UniversalUniqueIdentifier uuid) {
File root = folderFor(uuid);
return new File(root, bytesToHexString(uuid.toBytes()));
}
/**
* Find out the name of the directory that fits better to this UUID.
*/
public File folderFor(UniversalUniqueIdentifier uuid) {
byte hash = hashUUIDbytes(uuid);
hash &= mask; // limit the range of the directory
String dirName = Integer.toHexString(hash + (128 & mask)); // +(128 & mask) makes sure 00h is the lower value
File dir = new File(storeLocation, dirName);
return dir;
}
public InputStream getBlob(UniversalUniqueIdentifier uuid) throws CoreException {
File blobFile = fileFor(uuid);
return localStore.read(blobFile);
}
public Set getBlobNames() {
Set result = new HashSet(50);
String[] folders = storeLocation.list();
if (folders != null)
for (int i = 0; i < folders.length; i++) {
File folder = new File(storeLocation, folders[i]);
String[] blobs = folder.list();
if (blobs != null)
for (int j = 0; j < blobs.length; j++)
result.add(blobs[j]);
}
return result;
}
/**
* Converts a byte array into a byte hash representation. It is used to
* get a directory name.
*/
protected byte hashUUIDbytes(UniversalUniqueIdentifier uuid) {
byte[] bytes = uuid.toBytes();
byte hash = 0;
for (int i = 0; i < bytes.length; i++)
hash ^= randomArray[bytes[i] + 128]; // +128 makes sure the index is >0
return hash;
}
}
| true | true | public UniversalUniqueIdentifier addBlob(File target, boolean moveContents) throws CoreException {
UniversalUniqueIdentifier uuid = new UniversalUniqueIdentifier();
File dir = folderFor(uuid);
if (!dir.exists())
if (!dir.mkdirs()) {
String message = Policy.bind("fileOverFolder", dir.getAbsolutePath()); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.FAILED_WRITE_LOCAL, new Path(dir.getAbsolutePath()), message, null);
}
File destination = fileFor(uuid);
if (moveContents)
localStore.move(target, destination, true, null);
else
localStore.copy(target, destination, IResource.DEPTH_ZERO, null);
return uuid;
}
| public UniversalUniqueIdentifier addBlob(File target, boolean moveContents) throws CoreException {
UniversalUniqueIdentifier uuid = new UniversalUniqueIdentifier();
File dir = folderFor(uuid);
if (!dir.exists())
if (!dir.mkdirs()) {
String message = Policy.bind("localstore.couldNotCreateFolder", dir.getAbsolutePath()); //$NON-NLS-1$
throw new ResourceException(IResourceStatus.FAILED_WRITE_LOCAL, new Path(dir.getAbsolutePath()), message, null);
}
File destination = fileFor(uuid);
if (moveContents)
localStore.move(target, destination, true, null);
else
localStore.copy(target, destination, IResource.DEPTH_ZERO, null);
return uuid;
}
|
diff --git a/OVE/src/main/java/BB/MyPageBean.java b/OVE/src/main/java/BB/MyPageBean.java
index 6103ea4..85a34cd 100644
--- a/OVE/src/main/java/BB/MyPageBean.java
+++ b/OVE/src/main/java/BB/MyPageBean.java
@@ -1,195 +1,195 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BB;
import Model.AbstractPerson;
import Model.Account;
import Model.Person;
import EJB.UserRegistry;
import EJB.WorkerRegistry;
import Model.Worker;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
/**
*
* @author kristofferskjutar
*/
@Named("mypageBean")
@SessionScoped
public class MyPageBean implements Serializable {
@EJB
private UserRegistry reg;
@EJB
private WorkerRegistry wReg;
private String username;
private Long idNumber;
private String name;
private String adress;
private String telephoneNumber;
private String emailAdress;
private String picUrl;
private Account a;
private Worker person;
@PostConstruct
public void init()
{
Long modelId = (Long)FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("id");
a = reg.find(modelId);
- person = (Worker)a.getPerson();
+ person = a.getPerson();
setUsername(a.getUserName());
setAdress(person.getAddress());
setEmailAdress(person.getMail());
setIdNumber(person.getIdNumber());
setTelephoneNumber(person.getPhoneNbr());
setName(person.getName());
setPicUrl(person.getPicUrl());
initSessionList();
}
private void initSessionList()
{
}
public String update()
{
person.setAddress(getAdress());
person.setIdNumber(getIdNumber());
person.setMail(getEmailAdress());
person.setName(getName());
person.setPhoneNbr(getTelephoneNumber());
person.setPicUrl(picUrl);
//Worker w = new Worker(person.getId(),getIdNumber(), getName(), getEmailAdress(),
// getTelephoneNumber(), getAdress());
wReg.update(person);
return "MyPage";
}
/**
* @return the idNumber
*/
public Long getIdNumber() {
return idNumber;
}
/**
* @param idNumber the idNumber to set
*/
public void setIdNumber(Long idNumber) {
this.idNumber = idNumber;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the adress
*/
public String getAdress() {
return adress;
}
/**
* @param adress the adress to set
*/
public void setAdress(String adress) {
this.adress = adress;
}
/**
* @return the telephoneNumber
*/
public String getTelephoneNumber() {
return telephoneNumber;
}
/**
* @param telephoneNumber the telephoneNumber to set
*/
public void setTelephoneNumber(String telephoneNumber) {
this.telephoneNumber = telephoneNumber;
}
/**
* @return the emailAdress
*/
public String getEmailAdress() {
return emailAdress;
}
/**
* @param emailAdress the emailAdress to set
*/
public void setEmailAdress(String emailAdress) {
this.emailAdress = emailAdress;
}
/**
* @return the picUrl
*/
public String getPicUrl() {
return picUrl;
}
/**
* @param picUrl the picUrl to set
*/
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
}
| true | true | public void init()
{
Long modelId = (Long)FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("id");
a = reg.find(modelId);
person = (Worker)a.getPerson();
setUsername(a.getUserName());
setAdress(person.getAddress());
setEmailAdress(person.getMail());
setIdNumber(person.getIdNumber());
setTelephoneNumber(person.getPhoneNbr());
setName(person.getName());
setPicUrl(person.getPicUrl());
initSessionList();
}
| public void init()
{
Long modelId = (Long)FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("id");
a = reg.find(modelId);
person = a.getPerson();
setUsername(a.getUserName());
setAdress(person.getAddress());
setEmailAdress(person.getMail());
setIdNumber(person.getIdNumber());
setTelephoneNumber(person.getPhoneNbr());
setName(person.getName());
setPicUrl(person.getPicUrl());
initSessionList();
}
|
diff --git a/solr/src/java/org/apache/solr/handler/MoreLikeThisHandler.java b/solr/src/java/org/apache/solr/handler/MoreLikeThisHandler.java
index 5a685c5fe..d5acf3c27 100644
--- a/solr/src/java/org/apache/solr/handler/MoreLikeThisHandler.java
+++ b/solr/src/java/org/apache/solr/handler/MoreLikeThisHandler.java
@@ -1,416 +1,418 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.handler;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.similar.MoreLikeThis;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.MoreLikeThisParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.MoreLikeThisParams.TermStyle;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SimpleFacets;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.DocIterator;
import org.apache.solr.search.DocList;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.SolrPluginUtils;
/**
* Solr MoreLikeThis --
*
* Return similar documents either based on a single document or based on posted text.
*
* @since solr 1.3
*/
public class MoreLikeThisHandler extends RequestHandlerBase
{
// Pattern is thread safe -- TODO? share this with general 'fl' param
private static final Pattern splitList = Pattern.compile(",| ");
@Override
public void init(NamedList args) {
super.init(args);
}
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception
{
SolrParams params = req.getParams();
SolrIndexSearcher searcher = req.getSearcher();
MoreLikeThisHelper mlt = new MoreLikeThisHelper( params, searcher );
List<Query> filters = SolrPluginUtils.parseFilterQueries(req);
// Hold on to the interesting terms if relevant
TermStyle termStyle = TermStyle.get( params.get( MoreLikeThisParams.INTERESTING_TERMS ) );
List<InterestingTerm> interesting = (termStyle == TermStyle.NONE )
? null : new ArrayList<InterestingTerm>( mlt.mlt.getMaxQueryTerms() );
DocListAndSet mltDocs = null;
String q = params.get( CommonParams.Q );
// Parse Required Params
// This will either have a single Reader or valid query
Reader reader = null;
try {
if (q == null || q.trim().length() < 1) {
Iterable<ContentStream> streams = req.getContentStreams();
if (streams != null) {
Iterator<ContentStream> iter = streams.iterator();
if (iter.hasNext()) {
reader = iter.next().getReader();
}
if (iter.hasNext()) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis does not support multiple ContentStreams");
}
}
}
// What fields do we need to return
String fl = params.get(CommonParams.FL);
int flags = 0;
if (fl != null) {
flags |= SolrPluginUtils.setReturnFields(fl, rsp);
}
int start = params.getInt(CommonParams.START, 0);
int rows = params.getInt(CommonParams.ROWS, 10);
// Find documents MoreLikeThis - either with a reader or a query
// --------------------------------------------------------------------------------
if (reader != null) {
mltDocs = mlt.getMoreLikeThis(reader, start, rows, filters,
interesting, flags);
} else if (q != null) {
// Matching options
boolean includeMatch = params.getBool(MoreLikeThisParams.MATCH_INCLUDE,
true);
int matchOffset = params.getInt(MoreLikeThisParams.MATCH_OFFSET, 0);
// Find the base match
Query query = QueryParsing.parseQuery(q, params.get(CommonParams.DF),
params, req.getSchema());
DocList match = searcher.getDocList(query, null, null, matchOffset, 1,
flags); // only get the first one...
if (includeMatch) {
rsp.add("match", match);
}
// This is an iterator, but we only handle the first match
DocIterator iterator = match.iterator();
if (iterator.hasNext()) {
// do a MoreLikeThis query for each document in results
int id = iterator.nextDoc();
mltDocs = mlt.getMoreLikeThis(id, start, rows, filters, interesting,
flags);
}
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis requires either a query (?q=) or text to find similar documents.");
}
} finally {
if (reader != null) {
reader.close();
}
}
if( mltDocs == null ) {
mltDocs = new DocListAndSet(); // avoid NPE
}
rsp.add( "response", mltDocs.docList );
if( interesting != null ) {
if( termStyle == TermStyle.DETAILS ) {
NamedList<Float> it = new NamedList<Float>();
for( InterestingTerm t : interesting ) {
it.add( t.term.toString(), t.boost );
}
rsp.add( "interestingTerms", it );
}
else {
List<String> it = new ArrayList<String>( interesting.size() );
for( InterestingTerm t : interesting ) {
it.add( t.term.text());
}
rsp.add( "interestingTerms", it );
}
}
// maybe facet the results
if (params.getBool(FacetParams.FACET,false)) {
if( mltDocs.docSet == null ) {
rsp.add( "facet_counts", null );
}
else {
SimpleFacets f = new SimpleFacets(req, mltDocs.docSet, params );
rsp.add( "facet_counts", f.getFacetCounts() );
}
}
boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false);
boolean dbgQuery = false, dbgResults = false;
if (dbg == false){//if it's true, we are doing everything anyway.
String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG);
- for (int i = 0; i < dbgParams.length; i++) {
- if (dbgParams[i].equals(CommonParams.QUERY)){
- dbgQuery = true;
- } else if (dbgParams[i].equals(CommonParams.RESULTS)){
- dbgResults = true;
+ if (dbgParams != null) {
+ for (int i = 0; i < dbgParams.length; i++) {
+ if (dbgParams[i].equals(CommonParams.QUERY)){
+ dbgQuery = true;
+ } else if (dbgParams[i].equals(CommonParams.RESULTS)){
+ dbgResults = true;
+ }
}
}
} else {
dbgQuery = true;
dbgResults = true;
}
// Copied from StandardRequestHandler... perhaps it should be added to doStandardDebug?
if (dbg == true) {
try {
NamedList<Object> dbgInfo = SolrPluginUtils.doStandardDebug(req, q, mlt.mltquery, mltDocs.docList, dbgQuery, dbgResults);
if (null != dbgInfo) {
if (null != filters) {
dbgInfo.add("filter_queries",req.getParams().getParams(CommonParams.FQ));
List<String> fqs = new ArrayList<String>(filters.size());
for (Query fq : filters) {
fqs.add(QueryParsing.toString(fq, req.getSchema()));
}
dbgInfo.add("parsed_filter_queries",fqs);
}
rsp.add("debug", dbgInfo);
}
} catch (Exception e) {
SolrException.logOnce(SolrCore.log, "Exception during debug", e);
rsp.add("exception_during_debug", SolrException.toStr(e));
}
}
}
public static class InterestingTerm
{
public Term term;
public float boost;
public static Comparator<InterestingTerm> BOOST_ORDER = new Comparator<InterestingTerm>() {
public int compare(InterestingTerm t1, InterestingTerm t2) {
float d = t1.boost - t2.boost;
if( d == 0 ) {
return 0;
}
return (d>0)?1:-1;
}
};
}
/**
* Helper class for MoreLikeThis that can be called from other request handlers
*/
public static class MoreLikeThisHelper
{
final SolrIndexSearcher searcher;
final MoreLikeThis mlt;
final IndexReader reader;
final SchemaField uniqueKeyField;
final boolean needDocSet;
Map<String,Float> boostFields;
Query mltquery; // expose this for debugging
public MoreLikeThisHelper( SolrParams params, SolrIndexSearcher searcher )
{
this.searcher = searcher;
this.reader = searcher.getReader();
this.uniqueKeyField = searcher.getSchema().getUniqueKeyField();
this.needDocSet = params.getBool(FacetParams.FACET,false);
SolrParams required = params.required();
String[] fields = splitList.split( required.get(MoreLikeThisParams.SIMILARITY_FIELDS) );
if( fields.length < 1 ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis requires at least one similarity field: "+MoreLikeThisParams.SIMILARITY_FIELDS );
}
this.mlt = new MoreLikeThis( reader ); // TODO -- after LUCENE-896, we can use , searcher.getSimilarity() );
mlt.setFieldNames(fields);
mlt.setAnalyzer( searcher.getSchema().getAnalyzer() );
// configurable params
mlt.setMinTermFreq( params.getInt(MoreLikeThisParams.MIN_TERM_FREQ, MoreLikeThis.DEFAULT_MIN_TERM_FREQ));
mlt.setMinDocFreq( params.getInt(MoreLikeThisParams.MIN_DOC_FREQ, MoreLikeThis.DEFAULT_MIN_DOC_FREQ));
mlt.setMinWordLen( params.getInt(MoreLikeThisParams.MIN_WORD_LEN, MoreLikeThis.DEFAULT_MIN_WORD_LENGTH));
mlt.setMaxWordLen( params.getInt(MoreLikeThisParams.MAX_WORD_LEN, MoreLikeThis.DEFAULT_MAX_WORD_LENGTH));
mlt.setMaxQueryTerms( params.getInt(MoreLikeThisParams.MAX_QUERY_TERMS, MoreLikeThis.DEFAULT_MAX_QUERY_TERMS));
mlt.setMaxNumTokensParsed(params.getInt(MoreLikeThisParams.MAX_NUM_TOKENS_PARSED, MoreLikeThis.DEFAULT_MAX_NUM_TOKENS_PARSED));
mlt.setBoost( params.getBool(MoreLikeThisParams.BOOST, false ) );
boostFields = SolrPluginUtils.parseFieldBoosts(params.getParams(MoreLikeThisParams.QF));
}
private void setBoosts(Query mltquery) {
if (boostFields.size() > 0) {
List clauses = ((BooleanQuery)mltquery).clauses();
for( Object o : clauses ) {
TermQuery q = (TermQuery)((BooleanClause)o).getQuery();
Float b = this.boostFields.get(q.getTerm().field());
if (b != null) {
q.setBoost(b*q.getBoost());
}
}
}
}
public DocListAndSet getMoreLikeThis( int id, int start, int rows, List<Query> filters, List<InterestingTerm> terms, int flags ) throws IOException
{
Document doc = reader.document(id);
mltquery = mlt.like(id);
setBoosts(mltquery);
if( terms != null ) {
fillInterestingTermsFromMLTQuery( mltquery, terms );
}
// exclude current document from results
BooleanQuery mltQuery = new BooleanQuery();
mltQuery.add(mltquery, BooleanClause.Occur.MUST);
mltQuery.add(
new TermQuery(new Term(uniqueKeyField.getName(), uniqueKeyField.getType().storedToIndexed(doc.getFieldable(uniqueKeyField.getName())))),
BooleanClause.Occur.MUST_NOT);
DocListAndSet results = new DocListAndSet();
if (this.needDocSet) {
results = searcher.getDocListAndSet(mltQuery, filters, null, start, rows, flags);
} else {
results.docList = searcher.getDocList(mltQuery, filters, null, start, rows, flags);
}
return results;
}
public DocListAndSet getMoreLikeThis( Reader reader, int start, int rows, List<Query> filters, List<InterestingTerm> terms, int flags ) throws IOException
{
mltquery = mlt.like(reader);
setBoosts(mltquery);
if( terms != null ) {
fillInterestingTermsFromMLTQuery( mltquery, terms );
}
DocListAndSet results = new DocListAndSet();
if (this.needDocSet) {
results = searcher.getDocListAndSet(mltquery, filters, null, start, rows, flags);
} else {
results.docList = searcher.getDocList(mltquery, filters, null, start, rows, flags);
}
return results;
}
public NamedList<DocList> getMoreLikeThese( DocList docs, int rows, int flags ) throws IOException
{
IndexSchema schema = searcher.getSchema();
NamedList<DocList> mlt = new SimpleOrderedMap<DocList>();
DocIterator iterator = docs.iterator();
while( iterator.hasNext() ) {
int id = iterator.nextDoc();
DocListAndSet sim = getMoreLikeThis( id, 0, rows, null, null, flags );
String name = schema.printableUniqueKey( reader.document( id ) );
mlt.add(name, sim.docList);
}
return mlt;
}
private void fillInterestingTermsFromMLTQuery( Query query, List<InterestingTerm> terms )
{
List clauses = ((BooleanQuery)mltquery).clauses();
for( Object o : clauses ) {
TermQuery q = (TermQuery)((BooleanClause)o).getQuery();
InterestingTerm it = new InterestingTerm();
it.boost = q.getBoost();
it.term = q.getTerm();
terms.add( it );
}
// alternatively we could use
// mltquery.extractTerms( terms );
}
public MoreLikeThis getMoreLikeThis()
{
return mlt;
}
}
//////////////////////// SolrInfoMBeans methods //////////////////////
@Override
public String getVersion() {
return "$Revision$";
}
@Override
public String getDescription() {
return "Solr MoreLikeThis";
}
@Override
public String getSourceId() {
return "$Id$";
}
@Override
public String getSource() {
return "$URL$";
}
@Override
public URL[] getDocs() {
try {
return new URL[] { new URL("http://wiki.apache.org/solr/MoreLikeThis") };
}
catch( MalformedURLException ex ) { return null; }
}
}
| true | true | public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception
{
SolrParams params = req.getParams();
SolrIndexSearcher searcher = req.getSearcher();
MoreLikeThisHelper mlt = new MoreLikeThisHelper( params, searcher );
List<Query> filters = SolrPluginUtils.parseFilterQueries(req);
// Hold on to the interesting terms if relevant
TermStyle termStyle = TermStyle.get( params.get( MoreLikeThisParams.INTERESTING_TERMS ) );
List<InterestingTerm> interesting = (termStyle == TermStyle.NONE )
? null : new ArrayList<InterestingTerm>( mlt.mlt.getMaxQueryTerms() );
DocListAndSet mltDocs = null;
String q = params.get( CommonParams.Q );
// Parse Required Params
// This will either have a single Reader or valid query
Reader reader = null;
try {
if (q == null || q.trim().length() < 1) {
Iterable<ContentStream> streams = req.getContentStreams();
if (streams != null) {
Iterator<ContentStream> iter = streams.iterator();
if (iter.hasNext()) {
reader = iter.next().getReader();
}
if (iter.hasNext()) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis does not support multiple ContentStreams");
}
}
}
// What fields do we need to return
String fl = params.get(CommonParams.FL);
int flags = 0;
if (fl != null) {
flags |= SolrPluginUtils.setReturnFields(fl, rsp);
}
int start = params.getInt(CommonParams.START, 0);
int rows = params.getInt(CommonParams.ROWS, 10);
// Find documents MoreLikeThis - either with a reader or a query
// --------------------------------------------------------------------------------
if (reader != null) {
mltDocs = mlt.getMoreLikeThis(reader, start, rows, filters,
interesting, flags);
} else if (q != null) {
// Matching options
boolean includeMatch = params.getBool(MoreLikeThisParams.MATCH_INCLUDE,
true);
int matchOffset = params.getInt(MoreLikeThisParams.MATCH_OFFSET, 0);
// Find the base match
Query query = QueryParsing.parseQuery(q, params.get(CommonParams.DF),
params, req.getSchema());
DocList match = searcher.getDocList(query, null, null, matchOffset, 1,
flags); // only get the first one...
if (includeMatch) {
rsp.add("match", match);
}
// This is an iterator, but we only handle the first match
DocIterator iterator = match.iterator();
if (iterator.hasNext()) {
// do a MoreLikeThis query for each document in results
int id = iterator.nextDoc();
mltDocs = mlt.getMoreLikeThis(id, start, rows, filters, interesting,
flags);
}
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis requires either a query (?q=) or text to find similar documents.");
}
} finally {
if (reader != null) {
reader.close();
}
}
if( mltDocs == null ) {
mltDocs = new DocListAndSet(); // avoid NPE
}
rsp.add( "response", mltDocs.docList );
if( interesting != null ) {
if( termStyle == TermStyle.DETAILS ) {
NamedList<Float> it = new NamedList<Float>();
for( InterestingTerm t : interesting ) {
it.add( t.term.toString(), t.boost );
}
rsp.add( "interestingTerms", it );
}
else {
List<String> it = new ArrayList<String>( interesting.size() );
for( InterestingTerm t : interesting ) {
it.add( t.term.text());
}
rsp.add( "interestingTerms", it );
}
}
// maybe facet the results
if (params.getBool(FacetParams.FACET,false)) {
if( mltDocs.docSet == null ) {
rsp.add( "facet_counts", null );
}
else {
SimpleFacets f = new SimpleFacets(req, mltDocs.docSet, params );
rsp.add( "facet_counts", f.getFacetCounts() );
}
}
boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false);
boolean dbgQuery = false, dbgResults = false;
if (dbg == false){//if it's true, we are doing everything anyway.
String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG);
for (int i = 0; i < dbgParams.length; i++) {
if (dbgParams[i].equals(CommonParams.QUERY)){
dbgQuery = true;
} else if (dbgParams[i].equals(CommonParams.RESULTS)){
dbgResults = true;
}
}
} else {
dbgQuery = true;
dbgResults = true;
}
// Copied from StandardRequestHandler... perhaps it should be added to doStandardDebug?
if (dbg == true) {
try {
NamedList<Object> dbgInfo = SolrPluginUtils.doStandardDebug(req, q, mlt.mltquery, mltDocs.docList, dbgQuery, dbgResults);
if (null != dbgInfo) {
if (null != filters) {
dbgInfo.add("filter_queries",req.getParams().getParams(CommonParams.FQ));
List<String> fqs = new ArrayList<String>(filters.size());
for (Query fq : filters) {
fqs.add(QueryParsing.toString(fq, req.getSchema()));
}
dbgInfo.add("parsed_filter_queries",fqs);
}
rsp.add("debug", dbgInfo);
}
} catch (Exception e) {
SolrException.logOnce(SolrCore.log, "Exception during debug", e);
rsp.add("exception_during_debug", SolrException.toStr(e));
}
}
}
| public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception
{
SolrParams params = req.getParams();
SolrIndexSearcher searcher = req.getSearcher();
MoreLikeThisHelper mlt = new MoreLikeThisHelper( params, searcher );
List<Query> filters = SolrPluginUtils.parseFilterQueries(req);
// Hold on to the interesting terms if relevant
TermStyle termStyle = TermStyle.get( params.get( MoreLikeThisParams.INTERESTING_TERMS ) );
List<InterestingTerm> interesting = (termStyle == TermStyle.NONE )
? null : new ArrayList<InterestingTerm>( mlt.mlt.getMaxQueryTerms() );
DocListAndSet mltDocs = null;
String q = params.get( CommonParams.Q );
// Parse Required Params
// This will either have a single Reader or valid query
Reader reader = null;
try {
if (q == null || q.trim().length() < 1) {
Iterable<ContentStream> streams = req.getContentStreams();
if (streams != null) {
Iterator<ContentStream> iter = streams.iterator();
if (iter.hasNext()) {
reader = iter.next().getReader();
}
if (iter.hasNext()) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis does not support multiple ContentStreams");
}
}
}
// What fields do we need to return
String fl = params.get(CommonParams.FL);
int flags = 0;
if (fl != null) {
flags |= SolrPluginUtils.setReturnFields(fl, rsp);
}
int start = params.getInt(CommonParams.START, 0);
int rows = params.getInt(CommonParams.ROWS, 10);
// Find documents MoreLikeThis - either with a reader or a query
// --------------------------------------------------------------------------------
if (reader != null) {
mltDocs = mlt.getMoreLikeThis(reader, start, rows, filters,
interesting, flags);
} else if (q != null) {
// Matching options
boolean includeMatch = params.getBool(MoreLikeThisParams.MATCH_INCLUDE,
true);
int matchOffset = params.getInt(MoreLikeThisParams.MATCH_OFFSET, 0);
// Find the base match
Query query = QueryParsing.parseQuery(q, params.get(CommonParams.DF),
params, req.getSchema());
DocList match = searcher.getDocList(query, null, null, matchOffset, 1,
flags); // only get the first one...
if (includeMatch) {
rsp.add("match", match);
}
// This is an iterator, but we only handle the first match
DocIterator iterator = match.iterator();
if (iterator.hasNext()) {
// do a MoreLikeThis query for each document in results
int id = iterator.nextDoc();
mltDocs = mlt.getMoreLikeThis(id, start, rows, filters, interesting,
flags);
}
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"MoreLikeThis requires either a query (?q=) or text to find similar documents.");
}
} finally {
if (reader != null) {
reader.close();
}
}
if( mltDocs == null ) {
mltDocs = new DocListAndSet(); // avoid NPE
}
rsp.add( "response", mltDocs.docList );
if( interesting != null ) {
if( termStyle == TermStyle.DETAILS ) {
NamedList<Float> it = new NamedList<Float>();
for( InterestingTerm t : interesting ) {
it.add( t.term.toString(), t.boost );
}
rsp.add( "interestingTerms", it );
}
else {
List<String> it = new ArrayList<String>( interesting.size() );
for( InterestingTerm t : interesting ) {
it.add( t.term.text());
}
rsp.add( "interestingTerms", it );
}
}
// maybe facet the results
if (params.getBool(FacetParams.FACET,false)) {
if( mltDocs.docSet == null ) {
rsp.add( "facet_counts", null );
}
else {
SimpleFacets f = new SimpleFacets(req, mltDocs.docSet, params );
rsp.add( "facet_counts", f.getFacetCounts() );
}
}
boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false);
boolean dbgQuery = false, dbgResults = false;
if (dbg == false){//if it's true, we are doing everything anyway.
String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG);
if (dbgParams != null) {
for (int i = 0; i < dbgParams.length; i++) {
if (dbgParams[i].equals(CommonParams.QUERY)){
dbgQuery = true;
} else if (dbgParams[i].equals(CommonParams.RESULTS)){
dbgResults = true;
}
}
}
} else {
dbgQuery = true;
dbgResults = true;
}
// Copied from StandardRequestHandler... perhaps it should be added to doStandardDebug?
if (dbg == true) {
try {
NamedList<Object> dbgInfo = SolrPluginUtils.doStandardDebug(req, q, mlt.mltquery, mltDocs.docList, dbgQuery, dbgResults);
if (null != dbgInfo) {
if (null != filters) {
dbgInfo.add("filter_queries",req.getParams().getParams(CommonParams.FQ));
List<String> fqs = new ArrayList<String>(filters.size());
for (Query fq : filters) {
fqs.add(QueryParsing.toString(fq, req.getSchema()));
}
dbgInfo.add("parsed_filter_queries",fqs);
}
rsp.add("debug", dbgInfo);
}
} catch (Exception e) {
SolrException.logOnce(SolrCore.log, "Exception during debug", e);
rsp.add("exception_during_debug", SolrException.toStr(e));
}
}
}
|
diff --git a/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java b/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java
index 48f4d1472f..e98306f4b5 100644
--- a/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java
+++ b/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java
@@ -1,382 +1,382 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 0.4.8
*
* This file is part of Qcadoo.
*
* Qcadoo 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.productionCounting.internal.print;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.qcadoo.localization.api.utils.DateUtils;
import com.qcadoo.mes.productionCounting.internal.print.utils.EntityProductInOutComparator;
import com.qcadoo.mes.productionCounting.internal.print.utils.EntityProductionRecordComparator;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.report.api.pdf.PdfDocumentService;
import com.qcadoo.report.api.pdf.PdfUtil;
import com.qcadoo.security.api.SecurityService;
@Service
public class ProductionCountingPdfService extends PdfDocumentService {
@Autowired
DataDefinitionService dataDefinitionService;
@Autowired
SecurityService securityService;
@Override
protected void buildPdfContent(final Document document, final Entity productionCounting, final Locale locale)
throws DocumentException {
String documentTitle = getTranslationService().translate("productionCounting.productionCounting.report.title", locale)
+ " " + productionCounting.getId().toString();
String documentAuthor = getTranslationService().translate("qcadooReport.commons.generatedBy.label", locale);
PdfUtil.addDocumentHeader(document, "", documentTitle, documentAuthor, (Date) productionCounting.getField("date"),
securityService.getCurrentUserName());
PdfPTable leftPanel = createLeftPanel(productionCounting, locale);
PdfPTable rightPanel = createRightPanel(productionCounting, locale);
PdfPTable panelTable = PdfUtil.createPanelTable(2);
panelTable.addCell(leftPanel);
panelTable.addCell(rightPanel);
panelTable.setSpacingAfter(20);
panelTable.setSpacingBefore(20);
document.add(panelTable);
List<Entity> productionRecordsList = new ArrayList<Entity>(productionCounting.getBelongsToField("order").getHasManyField(
"productionRecords"));
Collections.sort(productionRecordsList, new EntityProductionRecordComparator());
for (Entity productionRecord : productionRecordsList) {
addProductionRecord(document, productionRecord, locale);
}
}
private void addTableCellAsTable(final PdfPTable table, final String label, final Object fieldValue, final String nullValue,
final Font headerFont, final Font valueFont, final DecimalFormat df) {
PdfPTable cellTable = new PdfPTable(2);
cellTable.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
cellTable.addCell(new Phrase(label, headerFont));
Object value = fieldValue;
if (value == null) {
cellTable.addCell(new Phrase(nullValue, valueFont));
} else {
if (value instanceof BigDecimal && df != null) {
cellTable.addCell(new Phrase(df.format(value), valueFont));
} else {
cellTable.addCell(new Phrase(value.toString(), valueFont));
}
}
table.addCell(cellTable);
}
private PdfPTable createLeftPanel(final Entity productionCounting, final Locale locale) {
PdfPTable leftPanel = PdfUtil.createPanelTable(1);
addTableCellAsTable(leftPanel,
getTranslationService().translate("productionCounting.productionCounting.report.title", locale) + ":",
productionCounting.getId().toString(), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(leftPanel,
getTranslationService().translate("productionCounting.productionBalance.report.panel.order", locale),
productionCounting.getBelongsToField("order").getStringField("name"), null, PdfUtil.getArialBold9Dark(),
PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(leftPanel,
getTranslationService().translate("productionCounting.productionBalance.report.panel.product", locale),
productionCounting.getBelongsToField("product").getStringField("name"), null, PdfUtil.getArialBold9Dark(),
PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(leftPanel,
getTranslationService().translate("productionCounting.productionBalance.report.panel.numberOfRecords", locale),
String.valueOf(productionCounting.getBelongsToField("order").getHasManyField("productionRecords").size()), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(leftPanel,
getTranslationService().translate("productionCounting.productionBalance.description.label", locale) + ":",
productionCounting.getStringField("description"), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(),
null);
return leftPanel;
}
private PdfPTable createRightPanel(final Entity productionCounting, final Locale locale) {
PdfPTable rightPanel = PdfUtil.createPanelTable(1);
rightPanel.addCell(new Phrase(getTranslationService().translate(
"costCalculation.costCalculationDetails.window.mainTab.form.parameters", locale)
+ ":", PdfUtil.getArialBold10Dark()));
rightPanel
.addCell(new Phrase(
"\t \t \t"
+ getTranslationService().translate(
"productionCounting.productionBalance.report.panel.registerQuantityOutProduct", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField("order").getField("registerQuantityInProduct") ? getTranslationService()
.translate("qcadooView.true", locale) : getTranslationService().translate(
"qcadooView.false", locale)), PdfUtil.getArialBold9Dark()));
rightPanel
.addCell(new Phrase(
"\t \t \t"
+ getTranslationService().translate(
"productionCounting.productionBalance.report.panel.registerQuantityInProduct", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField("order").getField("registerQuantityOutProduct") ? getTranslationService()
.translate("qcadooView.true", locale) : getTranslationService().translate(
"qcadooView.false", locale)), PdfUtil.getArialBold9Dark()));
rightPanel
.addCell(new Phrase(
"\t \t \t"
+ getTranslationService().translate(
"productionCounting.productionBalance.report.panel.registerProductionTime", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField("order").getField("registerProductionTime") ? getTranslationService()
.translate("qcadooView.true", locale) : getTranslationService().translate(
"qcadooView.false", locale)), PdfUtil.getArialBold9Dark()));
rightPanel.addCell(new Phrase("\t \t \t"
+ getTranslationService().translate("productionCounting.productionBalance.report.panel.allowedPartial", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField("order").getField("allowedPartial") ? getTranslationService()
.translate("qcadooView.true", locale) : getTranslationService().translate("qcadooView.false", locale)),
PdfUtil.getArialBold9Dark()));
rightPanel.addCell(new Phrase("\t \t \t"
+ getTranslationService().translate("productionCounting.productionBalance.report.panel.blockClosing", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField("order").getField("blockClosing") ? getTranslationService()
.translate("qcadooView.true", locale) : getTranslationService().translate("qcadooView.false", locale)),
PdfUtil.getArialBold9Dark()));
rightPanel.addCell(new Phrase("\t \t \t"
+ getTranslationService().translate("productionCounting.productionBalance.report.panel.autoCloseOrder", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField("order").getField("autoCloseOrder") ? getTranslationService()
.translate("qcadooView.true", locale) : getTranslationService().translate("qcadooView.false", locale)),
PdfUtil.getArialBold9Dark()));
return rightPanel;
}
private void addProductionRecord(Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(getTranslationService().translate("productionCounting.productionCounting.report.paragraph",
locale)
+ " " + productionRecord.getStringField("number"), PdfUtil.getArialBold19Dark()));
PdfPTable panelTable = PdfUtil.createPanelTable(2);
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.recordType", locale),
(Boolean) productionRecord.getField("isFinal") == false ? getTranslationService().translate(
"productionCounting.productionCounting.report.panel.recordType.partial", locale)
: getTranslationService().translate(
"productionCounting.productionCounting.report.panel.recordType.final", locale), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if (productionRecord.getBelongsToField("order").getStringField("typeOfProductionRecording").equals("02cumulated"))
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.operationAndLevel",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
else
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.operationAndLevel",
- locale), productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
- .getStringField("name")
- + " " + productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber"),
- null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
+ locale), productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber")
+ + " "
+ + productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
+ .getStringField("name"), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.dateAndTime", locale),
(new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT).format((Date) productionRecord.getField("creationTime")))
.toString(), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.machineOperationTime",
locale), convertTimeToString(new BigDecimal((Integer) productionRecord.getField("machineTime"))),
null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.machineOperationTime",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
}
addTableCellAsTable(panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.worker", locale),
productionRecord.getStringField("worker"), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.laborOperationTime",
locale), convertTimeToString(new BigDecimal((Integer) productionRecord.getField("laborTime"))), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.laborOperationTime",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
}
panelTable.setSpacingBefore(10);
document.add(panelTable);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerQuantityInProduct"))
addInputProducts(document, productionRecord, locale);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerQuantityOutProduct"))
addOutputProducts(document, productionRecord, locale);
}
private void addInputProducts(Document document, final Entity productionRecord, final Locale locale) throws DocumentException {
document.add(new Paragraph(getTranslationService().translate("productionCounting.productionCounting.report.paragraph2",
locale), PdfUtil.getArialBold11Dark()));
List<String> inputProductsTableHeader = new ArrayList<String>();
inputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionBalance.report.columnHeader.number", locale));
inputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionBalance.report.columnHeader.productionName", locale));
inputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionBalance.report.columnHeader.type", locale));
inputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionCounting.report.columnHeader.quantity", locale));
inputProductsTableHeader.add(getTranslationService().translate("basic.product.unit.label", locale));
PdfPTable inputProductsTable = PdfUtil.createTableWithHeader(5, inputProductsTableHeader, false);
if (productionRecord.getHasManyField("recordOperationProductInComponents") != null) {
List<Entity> productsInList = new ArrayList<Entity>(
productionRecord.getHasManyField("recordOperationProductInComponents"));
Collections.sort(productsInList, new EntityProductInOutComparator());
for (Entity productIn : productsInList) {
inputProductsTable.addCell(new Phrase(productIn.getBelongsToField("product").getStringField("number"), PdfUtil
.getArialRegular9Dark()));
inputProductsTable.addCell(new Phrase(productIn.getBelongsToField("product").getStringField("name"), PdfUtil
.getArialRegular9Dark()));
inputProductsTable.addCell(new Phrase(getTranslationService().translate(
"basic.product.typeOfMaterial.value."
+ productIn.getBelongsToField("product").getStringField("typeOfMaterial"), locale), PdfUtil
.getArialRegular9Dark()));
inputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
if (productIn.getField("usedQuantity") != null)
inputProductsTable.addCell(new Phrase(getDecimalFormat().format(productIn.getField("usedQuantity")), PdfUtil
.getArialRegular9Dark()));
else
inputProductsTable.addCell(new Phrase("N/A", PdfUtil.getArialRegular9Dark()));
inputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
inputProductsTable.addCell(new Phrase(productIn.getBelongsToField("product").getStringField("unit"), PdfUtil
.getArialRegular9Dark()));
}
}
document.add(inputProductsTable);
}
private void addOutputProducts(Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(getTranslationService().translate("productionCounting.productionCounting.report.paragraph3",
locale), PdfUtil.getArialBold11Dark()));
List<String> outputProductsTableHeader = new ArrayList<String>();
outputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionBalance.report.columnHeader.number", locale));
outputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionBalance.report.columnHeader.productionName", locale));
outputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionBalance.report.columnHeader.type", locale));
outputProductsTableHeader.add(getTranslationService().translate(
"productionCounting.productionCounting.report.columnHeader.quantity", locale));
outputProductsTableHeader.add(getTranslationService().translate("basic.product.unit.label", locale));
PdfPTable outputProductsTable = PdfUtil.createTableWithHeader(5, outputProductsTableHeader, false);
if (productionRecord.getHasManyField("recordOperationProductOutComponents") != null) {
List<Entity> productsOutList = new ArrayList<Entity>(
productionRecord.getHasManyField("recordOperationProductOutComponents"));
Collections.sort(productsOutList, new EntityProductInOutComparator());
for (Entity productOut : productsOutList) {
outputProductsTable.addCell(new Phrase(productOut.getBelongsToField("product").getStringField("number"), PdfUtil
.getArialRegular9Dark()));
outputProductsTable.addCell(new Phrase(productOut.getBelongsToField("product").getStringField("name"), PdfUtil
.getArialRegular9Dark()));
outputProductsTable.addCell(new Phrase(getTranslationService().translate(
"basic.product.typeOfMaterial.value."
+ productOut.getBelongsToField("product").getStringField("typeOfMaterial"), locale), PdfUtil
.getArialRegular9Dark()));
outputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
if (productOut.getField("usedQuantity") != null)
outputProductsTable.addCell(new Phrase(getDecimalFormat().format(productOut.getField("usedQuantity")),
PdfUtil.getArialRegular9Dark()));
else
outputProductsTable.addCell(new Phrase("N/A", PdfUtil.getArialRegular9Dark()));
outputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
outputProductsTable.addCell(new Phrase(productOut.getBelongsToField("product").getStringField("unit"), PdfUtil
.getArialRegular9Dark()));
}
}
document.add(outputProductsTable);
}
@Override
protected String getSuffix() {
return "";
}
@Override
protected String getReportTitle(final Locale locale) {
return getTranslationService().translate("productionCounting.productionBalance.report.title", locale);
}
public String convertTimeToString(final BigDecimal duration) {
long longValueFromDuration = duration.longValue();
long hours = longValueFromDuration / 3600;
long minutes = longValueFromDuration % 3600 / 60;
long seconds = longValueFromDuration % 3600 % 60;
Boolean minus = false;
if (hours < 0) {
minus = true;
hours = -hours;
}
if (minutes < 0) {
minus = true;
minutes = -minutes;
}
if (seconds < 0) {
minus = true;
seconds = -seconds;
}
return (minus ? "-" : "") + (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":"
+ (seconds < 10 ? "0" : "") + seconds;
}
}
| true | true | private void addProductionRecord(Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(getTranslationService().translate("productionCounting.productionCounting.report.paragraph",
locale)
+ " " + productionRecord.getStringField("number"), PdfUtil.getArialBold19Dark()));
PdfPTable panelTable = PdfUtil.createPanelTable(2);
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.recordType", locale),
(Boolean) productionRecord.getField("isFinal") == false ? getTranslationService().translate(
"productionCounting.productionCounting.report.panel.recordType.partial", locale)
: getTranslationService().translate(
"productionCounting.productionCounting.report.panel.recordType.final", locale), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if (productionRecord.getBelongsToField("order").getStringField("typeOfProductionRecording").equals("02cumulated"))
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.operationAndLevel",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
else
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.operationAndLevel",
locale), productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
.getStringField("name")
+ " " + productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber"),
null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.dateAndTime", locale),
(new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT).format((Date) productionRecord.getField("creationTime")))
.toString(), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.machineOperationTime",
locale), convertTimeToString(new BigDecimal((Integer) productionRecord.getField("machineTime"))),
null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.machineOperationTime",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
}
addTableCellAsTable(panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.worker", locale),
productionRecord.getStringField("worker"), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.laborOperationTime",
locale), convertTimeToString(new BigDecimal((Integer) productionRecord.getField("laborTime"))), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.laborOperationTime",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
}
panelTable.setSpacingBefore(10);
document.add(panelTable);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerQuantityInProduct"))
addInputProducts(document, productionRecord, locale);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerQuantityOutProduct"))
addOutputProducts(document, productionRecord, locale);
}
| private void addProductionRecord(Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(getTranslationService().translate("productionCounting.productionCounting.report.paragraph",
locale)
+ " " + productionRecord.getStringField("number"), PdfUtil.getArialBold19Dark()));
PdfPTable panelTable = PdfUtil.createPanelTable(2);
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.recordType", locale),
(Boolean) productionRecord.getField("isFinal") == false ? getTranslationService().translate(
"productionCounting.productionCounting.report.panel.recordType.partial", locale)
: getTranslationService().translate(
"productionCounting.productionCounting.report.panel.recordType.final", locale), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if (productionRecord.getBelongsToField("order").getStringField("typeOfProductionRecording").equals("02cumulated"))
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.operationAndLevel",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
else
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.operationAndLevel",
locale), productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber")
+ " "
+ productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
.getStringField("name"), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
addTableCellAsTable(panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.dateAndTime", locale),
(new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT).format((Date) productionRecord.getField("creationTime")))
.toString(), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.machineOperationTime",
locale), convertTimeToString(new BigDecimal((Integer) productionRecord.getField("machineTime"))),
null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.machineOperationTime",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
}
addTableCellAsTable(panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.worker", locale),
productionRecord.getStringField("worker"), null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.laborOperationTime",
locale), convertTimeToString(new BigDecimal((Integer) productionRecord.getField("laborTime"))), null,
PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
getTranslationService().translate("productionCounting.productionCounting.report.panel.laborOperationTime",
locale), "N/A", null, PdfUtil.getArialBold9Dark(), PdfUtil.getArialBold9Dark(), null);
}
panelTable.setSpacingBefore(10);
document.add(panelTable);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerQuantityInProduct"))
addInputProducts(document, productionRecord, locale);
if ((Boolean) productionRecord.getBelongsToField("order").getField("registerQuantityOutProduct"))
addOutputProducts(document, productionRecord, locale);
}
|
diff --git a/src/main/java/yucatan/communication/ReadOnlyMemberAccessor.java b/src/main/java/yucatan/communication/ReadOnlyMemberAccessor.java
index c23157b..7ab9783 100644
--- a/src/main/java/yucatan/communication/ReadOnlyMemberAccessor.java
+++ b/src/main/java/yucatan/communication/ReadOnlyMemberAccessor.java
@@ -1,11 +1,11 @@
package yucatan.communication;
public interface ReadOnlyMemberAccessor {
/**
* Provides an instance of an wrapped object. Usually a public member of the instance.
*
* @param key The
* @return The requested Object or null;
*/
- public Object get(String key);
+ Object get(String key);
}
| true | true | public Object get(String key);
| Object get(String key);
|
diff --git a/server/src/main/java/org/apache/abdera/protocol/server/impl/AbstractCollectionAdapter.java b/server/src/main/java/org/apache/abdera/protocol/server/impl/AbstractCollectionAdapter.java
index 4a2590b6..2794b5e0 100755
--- a/server/src/main/java/org/apache/abdera/protocol/server/impl/AbstractCollectionAdapter.java
+++ b/server/src/main/java/org/apache/abdera/protocol/server/impl/AbstractCollectionAdapter.java
@@ -1,289 +1,289 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. 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. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
package org.apache.abdera.protocol.server.impl;
import static org.apache.abdera.protocol.server.ProviderHelper.calculateEntityTag;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.text.UrlEncoding;
import org.apache.abdera.model.AtomDate;
import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.ParseException;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.protocol.server.CategoriesInfo;
import org.apache.abdera.protocol.server.CollectionAdapter;
import org.apache.abdera.protocol.server.CollectionInfo;
import org.apache.abdera.protocol.server.MediaCollectionAdapter;
import org.apache.abdera.protocol.server.ProviderHelper;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
import org.apache.abdera.protocol.server.Transactional;
import org.apache.abdera.protocol.server.context.AbstractResponseContext;
import org.apache.abdera.protocol.server.context.BaseResponseContext;
import org.apache.abdera.protocol.server.context.EmptyResponseContext;
import org.apache.abdera.protocol.server.context.ResponseContextException;
import org.apache.abdera.util.EntityTag;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Base CollectionAdapter implementation that provides a number of helper
* utility methods for adapter implementations.
*/
public abstract class AbstractCollectionAdapter
implements CollectionAdapter,
MediaCollectionAdapter,
Transactional,
CollectionInfo {
private final static Log log = LogFactory.getLog(AbstractEntityCollectionAdapter.class);
private String href;
private Map<String,Object> hrefParams = new HashMap<String,Object>();
public AbstractCollectionAdapter() {
super();
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
hrefParams.put("collection", href);
}
public String getHref(RequestContext request) {
return request.urlFor("feed", hrefParams);
}
public void compensate(RequestContext request, Throwable t) {
}
public void end(RequestContext request, ResponseContext response) {
}
public void start(RequestContext request) throws ResponseContextException {
}
public String[] getAccepts(RequestContext request) {
return new String[] { "application/atom+xml;type=entry" };
}
public CategoriesInfo[] getCategoriesInfo(RequestContext request) {
return null;
}
public ResponseContext getCategories(RequestContext request) {
return null;
}
public ResponseContext deleteMedia(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext getMedia(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext headMedia(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext optionsMedia(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext putMedia(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext postMedia(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext headEntry(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public ResponseContext optionsEntry(RequestContext request) {
return ProviderHelper.notsupported(request);
}
public abstract String getAuthor(RequestContext request) throws ResponseContextException;
public abstract String getId(RequestContext request);
/**
* Creates the ResponseContext for a newly created entry. By default, a
* BaseResponseContext is returned. The Location, Content-Location, Etag and
* status are set appropriately.
*/
protected ResponseContext buildCreateEntryResponse(String link, Entry entry) {
BaseResponseContext<Entry> rc = new BaseResponseContext<Entry>(entry);
rc.setLocation(link);
rc.setContentLocation(rc.getLocation().toString());
rc.setEntityTag(calculateEntityTag(entry));
rc.setStatus(201);
return rc;
}
/**
* Creates the ResponseContext for a newly created entry. By default, a
* BaseResponseContext is returned. The Location, Content-Location, Etag and
* status are set appropriately.
*/
protected ResponseContext buildPostMediaEntryResponse(String link, Entry entry) {
return buildCreateEntryResponse(link, entry);
}
/**
* Creates the ResponseContext for a GET entry request. By default, a BaseResponseContext
* is returned. The Entry will contain an appropriate atom:source element
* and the Etag header will be set.
*/
protected ResponseContext buildGetEntryResponse(RequestContext request, Entry entry) throws ResponseContextException {
Feed feed = createFeedBase(request);
entry.setSource(feed.getAsSource());
Document<Entry> entry_doc = entry.getDocument();
AbstractResponseContext rc = new BaseResponseContext<Document<Entry>>(entry_doc);
rc.setEntityTag(calculateEntityTag(entry));
return rc;
}
/**
* Creates the ResponseContext for a HEAD entry request. By default, an EmptyResponseContext
* is returned. The Etag header will be set.
*/
protected ResponseContext buildHeadEntryResponse(RequestContext request,
String id,
Date updated) throws ResponseContextException {
EmptyResponseContext rc = new EmptyResponseContext(200);
rc.setEntityTag(EntityTag.generate(id, AtomDate.format(updated)));
return rc;
}
/**
* Creates the ResponseContext for a GET feed request. By default, a BaseResponseContext
* is returned. The Etag header will be set.
*/
protected ResponseContext buildGetFeedResponse(Feed feed) {
Document<Feed> document = feed.getDocument();
AbstractResponseContext rc = new BaseResponseContext<Document<Feed>>(document);
rc.setEntityTag(calculateEntityTag(document.getRoot()));
return rc;
}
/**
* Create a ResponseContext (or take it from the Exception) for an exception
* that occurred in the application.
*
* @param e
* @return
*/
protected ResponseContext createErrorResponse(ResponseContextException e) {
if (log.isInfoEnabled()) {
log.info("A ResponseException was thrown.", e);
} else if (e.getResponseContext() instanceof EmptyResponseContext
&& ((EmptyResponseContext)e.getResponseContext()).getStatus() >= 500) {
log.warn("A ResponseException was thrown.", e);
}
return e.getResponseContext();
}
/**
* Create the base feed for the requested collection.
*/
protected Feed createFeedBase(RequestContext request) throws ResponseContextException {
Factory factory = request.getAbdera().getFactory();
Feed feed = factory.newFeed();
feed.setId(getId(request));
feed.setTitle(getTitle(request));
feed.addLink("");
feed.addLink("", "self");
feed.addAuthor(getAuthor(request));
feed.setUpdated(new Date());
return feed;
}
/**
* Retrieves the FOM Entry object from the request payload.
*/
@SuppressWarnings("unchecked")
protected Entry getEntryFromRequest(RequestContext request) throws ResponseContextException {
Abdera abdera = request.getAbdera();
Parser parser = abdera.getParser();
Document<Entry> entry_doc;
try {
entry_doc = (Document<Entry>)request.getDocument(parser).clone();
} catch (ParseException e) {
- throw new ResponseContextException(500, e);
+ throw new ResponseContextException(400, e);
} catch (IOException e) {
throw new ResponseContextException(500, e);
}
if (entry_doc == null) {
return null;
}
return entry_doc.getRoot();
}
/**
* Get's the name of the specific resource requested
*/
protected String getResourceName(RequestContext request) {
String path = request.getTargetPath();
int q = path.indexOf("?");
if (q != -1) {
path = path.substring(0, q);
}
String[] segments = path.split("/");
String id = segments[segments.length - 1];
return UrlEncoding.decode(id);
}
public ResponseContext extensionRequest(RequestContext request) {
return ProviderHelper.notallowed(request, getMethods(request));
}
private String[] getMethods(RequestContext request) {
return ProviderHelper.getDefaultMethods(request);
}
public Collection asCollectionElement(RequestContext request) {
Collection collection = request.getAbdera().getFactory().newCollection();
collection.setHref(getHref(request));
collection.setTitle(getTitle(request));
collection.setAccept(getAccepts(request));
for (CategoriesInfo catsinfo : getCategoriesInfo(request)) {
collection.addCategories(catsinfo.asCategoriesElement(request));
}
return collection;
}
}
| true | true | protected Entry getEntryFromRequest(RequestContext request) throws ResponseContextException {
Abdera abdera = request.getAbdera();
Parser parser = abdera.getParser();
Document<Entry> entry_doc;
try {
entry_doc = (Document<Entry>)request.getDocument(parser).clone();
} catch (ParseException e) {
throw new ResponseContextException(500, e);
} catch (IOException e) {
throw new ResponseContextException(500, e);
}
if (entry_doc == null) {
return null;
}
return entry_doc.getRoot();
}
| protected Entry getEntryFromRequest(RequestContext request) throws ResponseContextException {
Abdera abdera = request.getAbdera();
Parser parser = abdera.getParser();
Document<Entry> entry_doc;
try {
entry_doc = (Document<Entry>)request.getDocument(parser).clone();
} catch (ParseException e) {
throw new ResponseContextException(400, e);
} catch (IOException e) {
throw new ResponseContextException(500, e);
}
if (entry_doc == null) {
return null;
}
return entry_doc.getRoot();
}
|
diff --git a/src/CuadroTablero.java b/src/CuadroTablero.java
index e95ac01..a8cbd18 100755
--- a/src/CuadroTablero.java
+++ b/src/CuadroTablero.java
@@ -1,162 +1,167 @@
/**
* @author (Luis Ballinas, Gabriel Ramos Olvera, Fernando Gomez, Francisco
* Barros)
* @version (9/13/2013)
*/
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public abstract class CuadroTablero extends JPanel {
private Posicion posicion;
protected Color colorFondo;
private Ficha ficha;
private Tablero tablero;
private ArrayList<Posicion> posiblesMovs;
public CuadroTablero(Color color, Posicion posicion) {
super();
this.posicion = posicion;
this.colorFondo = color;
setBackground(color);
setOpaque(true);
setLayout(new BorderLayout(0, 0));
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cuadroPresionado(evt);
}
});
}
public abstract void restablecerColorFondo();
private void cuadroPresionado(java.awt.event.MouseEvent evt) {
CuadroTablero[][] cuadros = this.tablero.getCuadros();
// Si hay cuadros en verde de posibles movs regresar a su estado original sólo si ya tiró
if (!Tablero.tirando) {
this.tablero.restablecerCuadros();
}
// System.out.println("# Se presionó el cuadro en:");
// Determinar en qué posiciones se puede mover
// System.out.println(posicion);
// Si no está tirando apenas va a seleccionar una ficha para moverla
if (!Tablero.tirando) {
if (this.ficha == null) {
System.out.println("NO HAY FICHA");
} else {
boolean puedeMover = false;
System.out.println("HAY FICHA EN ESTE CUADRO");
// Sólo puede tirar si selecciona una ficha de su propio tipo
if (this.ficha instanceof FichaB && Tablero.turnoJugador1) {
// Puede mover esa ficha
puedeMover = true;
} else if (this.ficha instanceof FichaA && !Tablero.turnoJugador1) {
// Puede mover esta ficha
puedeMover = true;
} else {
puedeMover = false;
System.out.println("NO PUEDES MOVER ESTA FICHA");
JOptionPane.showMessageDialog(this, "NO PUEDES MOVER ESTA FICHA");
}
if (puedeMover) {
ficha.determinarPosiblesMovimientos();
- Tablero.tirando = true;
+ // Sólo si tiene posibles movimientos puede tirar, sino necesita
+ // seleccionar otra ficha
+ if (ficha.getPosiblesMovs().size() > 0) {
+ Tablero.tirando = true;
+ Tablero.fichaAMover = ficha;
+ }
}
- Tablero.fichaAMover = ficha;
}
} else {
// Si ya está tirando entonces seleccionó un cuadro donde quiere mover la ficha
System.out.println("INTENTANDO TIRAR en:");
System.out.println(posicion);
// Si la ficha que se quiere mover contiene la posición en posible mov
// de este cuadro entonces se puede mover
boolean movValido = false;
for (Posicion p : Tablero.fichaAMover.getPosiblesMovs()) {
if (p.getX() == posicion.getX() && p.getY() == posicion.getY()) {
movValido = true;
break;
}
}
if (movValido) {
System.out.println("# MOVIMIENTO VÁLIDO. Tiraste en:");
System.out.println(posicion);
// Tirar: mover ficha al nuevo cuadro y remover la antigua
Tablero.fichaAMover.getCuadro().removeAll();
Tablero.fichaAMover.getCuadro().revalidate();
Tablero.fichaAMover.getCuadro().repaint();
+ Tablero.fichaAMover.getCuadro().setFicha(null);
add(Tablero.fichaAMover);
setFicha(Tablero.fichaAMover);
Tablero.fichaAMover.setCuadro(this);
Tablero.fichaAMover.setPosicion(posicion);
// Ya tiró, establecer como tirando false
Tablero.tirando = false;
// Restablecer cuadros (quitar color verde)
this.tablero.restablecerCuadros();
// Cambiar de turno
if (Tablero.turnoJugador1) {
Tablero.turnoJugador1 = false;
this.tablero.getVentanaJuego().cambiarLblTurno("TURNO DE JUGADOR 2");
} else {
Tablero.turnoJugador1 = true;
this.tablero.getVentanaJuego().cambiarLblTurno("TURNO DE JUGADOR 1");
}
} else {
System.out.println("MOVIMIENTO INVÁLIDO");
JOptionPane.showMessageDialog(this, "MOVIMIENTO INVÁLIDO");
}
}
}
public void agregarFicha(Ficha ficha) {
add(ficha);
this.ficha = ficha;
this.ficha.setCuadro(this);
ficha.setPosicion(posicion);
}
public boolean hayFicha() {
if (this.ficha == null) {
return false;
} else {
return true;
}
}
@Override
public String toString() {
if (this.ficha != null) {
return "o";
} else {
return "x";
}
}
public Posicion getPosicion() {
return posicion;
}
public void setPosicion(Posicion posicion) {
this.posicion = posicion;
}
public Ficha getFicha() {
return ficha;
}
public void setFicha(Ficha ficha) {
this.ficha = ficha;
}
public Tablero getTablero() {
return tablero;
}
public void setTablero(Tablero tablero) {
this.tablero = tablero;
}
}
| false | true | private void cuadroPresionado(java.awt.event.MouseEvent evt) {
CuadroTablero[][] cuadros = this.tablero.getCuadros();
// Si hay cuadros en verde de posibles movs regresar a su estado original sólo si ya tiró
if (!Tablero.tirando) {
this.tablero.restablecerCuadros();
}
// System.out.println("# Se presionó el cuadro en:");
// Determinar en qué posiciones se puede mover
// System.out.println(posicion);
// Si no está tirando apenas va a seleccionar una ficha para moverla
if (!Tablero.tirando) {
if (this.ficha == null) {
System.out.println("NO HAY FICHA");
} else {
boolean puedeMover = false;
System.out.println("HAY FICHA EN ESTE CUADRO");
// Sólo puede tirar si selecciona una ficha de su propio tipo
if (this.ficha instanceof FichaB && Tablero.turnoJugador1) {
// Puede mover esa ficha
puedeMover = true;
} else if (this.ficha instanceof FichaA && !Tablero.turnoJugador1) {
// Puede mover esta ficha
puedeMover = true;
} else {
puedeMover = false;
System.out.println("NO PUEDES MOVER ESTA FICHA");
JOptionPane.showMessageDialog(this, "NO PUEDES MOVER ESTA FICHA");
}
if (puedeMover) {
ficha.determinarPosiblesMovimientos();
Tablero.tirando = true;
}
Tablero.fichaAMover = ficha;
}
} else {
// Si ya está tirando entonces seleccionó un cuadro donde quiere mover la ficha
System.out.println("INTENTANDO TIRAR en:");
System.out.println(posicion);
// Si la ficha que se quiere mover contiene la posición en posible mov
// de este cuadro entonces se puede mover
boolean movValido = false;
for (Posicion p : Tablero.fichaAMover.getPosiblesMovs()) {
if (p.getX() == posicion.getX() && p.getY() == posicion.getY()) {
movValido = true;
break;
}
}
if (movValido) {
System.out.println("# MOVIMIENTO VÁLIDO. Tiraste en:");
System.out.println(posicion);
// Tirar: mover ficha al nuevo cuadro y remover la antigua
Tablero.fichaAMover.getCuadro().removeAll();
Tablero.fichaAMover.getCuadro().revalidate();
Tablero.fichaAMover.getCuadro().repaint();
add(Tablero.fichaAMover);
setFicha(Tablero.fichaAMover);
Tablero.fichaAMover.setCuadro(this);
Tablero.fichaAMover.setPosicion(posicion);
// Ya tiró, establecer como tirando false
Tablero.tirando = false;
// Restablecer cuadros (quitar color verde)
this.tablero.restablecerCuadros();
// Cambiar de turno
if (Tablero.turnoJugador1) {
Tablero.turnoJugador1 = false;
this.tablero.getVentanaJuego().cambiarLblTurno("TURNO DE JUGADOR 2");
} else {
Tablero.turnoJugador1 = true;
this.tablero.getVentanaJuego().cambiarLblTurno("TURNO DE JUGADOR 1");
}
} else {
System.out.println("MOVIMIENTO INVÁLIDO");
JOptionPane.showMessageDialog(this, "MOVIMIENTO INVÁLIDO");
}
}
}
| private void cuadroPresionado(java.awt.event.MouseEvent evt) {
CuadroTablero[][] cuadros = this.tablero.getCuadros();
// Si hay cuadros en verde de posibles movs regresar a su estado original sólo si ya tiró
if (!Tablero.tirando) {
this.tablero.restablecerCuadros();
}
// System.out.println("# Se presionó el cuadro en:");
// Determinar en qué posiciones se puede mover
// System.out.println(posicion);
// Si no está tirando apenas va a seleccionar una ficha para moverla
if (!Tablero.tirando) {
if (this.ficha == null) {
System.out.println("NO HAY FICHA");
} else {
boolean puedeMover = false;
System.out.println("HAY FICHA EN ESTE CUADRO");
// Sólo puede tirar si selecciona una ficha de su propio tipo
if (this.ficha instanceof FichaB && Tablero.turnoJugador1) {
// Puede mover esa ficha
puedeMover = true;
} else if (this.ficha instanceof FichaA && !Tablero.turnoJugador1) {
// Puede mover esta ficha
puedeMover = true;
} else {
puedeMover = false;
System.out.println("NO PUEDES MOVER ESTA FICHA");
JOptionPane.showMessageDialog(this, "NO PUEDES MOVER ESTA FICHA");
}
if (puedeMover) {
ficha.determinarPosiblesMovimientos();
// Sólo si tiene posibles movimientos puede tirar, sino necesita
// seleccionar otra ficha
if (ficha.getPosiblesMovs().size() > 0) {
Tablero.tirando = true;
Tablero.fichaAMover = ficha;
}
}
}
} else {
// Si ya está tirando entonces seleccionó un cuadro donde quiere mover la ficha
System.out.println("INTENTANDO TIRAR en:");
System.out.println(posicion);
// Si la ficha que se quiere mover contiene la posición en posible mov
// de este cuadro entonces se puede mover
boolean movValido = false;
for (Posicion p : Tablero.fichaAMover.getPosiblesMovs()) {
if (p.getX() == posicion.getX() && p.getY() == posicion.getY()) {
movValido = true;
break;
}
}
if (movValido) {
System.out.println("# MOVIMIENTO VÁLIDO. Tiraste en:");
System.out.println(posicion);
// Tirar: mover ficha al nuevo cuadro y remover la antigua
Tablero.fichaAMover.getCuadro().removeAll();
Tablero.fichaAMover.getCuadro().revalidate();
Tablero.fichaAMover.getCuadro().repaint();
Tablero.fichaAMover.getCuadro().setFicha(null);
add(Tablero.fichaAMover);
setFicha(Tablero.fichaAMover);
Tablero.fichaAMover.setCuadro(this);
Tablero.fichaAMover.setPosicion(posicion);
// Ya tiró, establecer como tirando false
Tablero.tirando = false;
// Restablecer cuadros (quitar color verde)
this.tablero.restablecerCuadros();
// Cambiar de turno
if (Tablero.turnoJugador1) {
Tablero.turnoJugador1 = false;
this.tablero.getVentanaJuego().cambiarLblTurno("TURNO DE JUGADOR 2");
} else {
Tablero.turnoJugador1 = true;
this.tablero.getVentanaJuego().cambiarLblTurno("TURNO DE JUGADOR 1");
}
} else {
System.out.println("MOVIMIENTO INVÁLIDO");
JOptionPane.showMessageDialog(this, "MOVIMIENTO INVÁLIDO");
}
}
}
|
diff --git a/src/main/wikiduper/utils/SampleSentences.java b/src/main/wikiduper/utils/SampleSentences.java
index bc39108..ea3a8f6 100644
--- a/src/main/wikiduper/utils/SampleSentences.java
+++ b/src/main/wikiduper/utils/SampleSentences.java
@@ -1,195 +1,195 @@
package wikiduper.utils;
import java.io.IOException;
import java.util.HashSet;
import java.util.Random;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.tools.GetConf;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import edu.umd.cloud9.io.pair.PairOfLongInt;
import edu.umd.cloud9.io.pair.PairOfStrings;
public class SampleSentences extends Configured implements Tool {
private static final Logger LOG = Logger.getLogger(SampleSentences.class);
private static class SampleMapper extends MapReduceBase implements
Mapper<PairOfLongInt, PairOfStrings, PairOfLongInt, PairOfStrings> {
static long rseed;
static Random r;
static String sampleLang;
static long limit;
static long count;
public void map(PairOfLongInt key, PairOfStrings p, OutputCollector<PairOfLongInt, PairOfStrings> output,
Reporter reporter) throws IOException {
String lang = p.getLeftElement();
if(lang.equals(sampleLang)){
if(Math.abs(r.nextLong())%count <= limit){
output.collect(key, p);
}
}
}
public void configure(JobConf job) {
rseed = job.getLong("rseed", 112345);
r = new Random(rseed);
count = job.getLong("count", 1000000);
int nSamples = job.getInt("nSamples", 1000000);
if(nSamples > count){
limit = 1;
}
limit = count/nSamples;
}
}
private static final String INPUT = "input";
private static final String OUTPUT = "output";
private static final String SAMPLE_LANG = "lang";
private static final String SAMPLES = "samples";
@SuppressWarnings("static-access")
@Override
public int run(String[] args) throws Exception {
Options options = new Options();
options.addOption(OptionBuilder.withArgName("path")
.hasArg().withDescription("output path").create(OUTPUT));
options.addOption(OptionBuilder.withArgName("path")
.hasArg().withDescription("input").create(INPUT));
options.addOption(OptionBuilder.withArgName("lang")
.hasArg().withDescription("language to sample from").create(SAMPLE_LANG));
options.addOption(OptionBuilder.withArgName("int")
- .hasArg().withDescription("language to sample from").create(SAMPLES));
+ .hasArg().withDescription("number of samples").create(SAMPLES));
CommandLine cmdline;
CommandLineParser parser = new GnuParser();
try {
cmdline = parser.parse(options, args);
} catch (ParseException exp) {
System.err.println("Error parsing command line: " + exp.getMessage());
return -1;
}
if (!cmdline.hasOption(OUTPUT) || !cmdline.hasOption(INPUT)
|| !cmdline.hasOption(SAMPLE_LANG) || !cmdline.hasOption(SAMPLES)
) {
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(120);
formatter.printHelp(this.getClass().getName(), options);
ToolRunner.printGenericCommandUsage(System.out);
return -1;
}
String inputPath = cmdline.getOptionValue(INPUT);
String outputPath = cmdline.getOptionValue(OUTPUT);
String sampleLang = cmdline.getOptionValue(SAMPLE_LANG);
int nSamples = Integer.parseInt(cmdline.getOptionValue(SAMPLES));
LOG.info("Tool name: " + this.getClass().getName());
LOG.info(" - nput file: " + inputPath);
LOG.info(" - output file: " + outputPath);
LOG.info(" - sample language: " + sampleLang);
JobConf conf = new JobConf(getConf(), SampleSentences.class);
// Set heap space - using old API
conf.set("mapred.job.map.memory.mb", "2048");
conf.set("mapred.map.child.java.opts", "-Xmx2048m");
conf.set("mapred.job.reduce.memory.mb", "8000");
conf.set("mapred.reduce.child.java.opts", "-Xmx8000m");
//conf.set("mapred.child.java.opts", "-Xmx2048m");
conf.setInputFormat(SequenceFileInputFormat.class);
conf.setOutputFormat(SequenceFileOutputFormat.class);
conf.setOutputKeyClass(PairOfLongInt.class);
conf.setOutputValueClass(PairOfStrings.class);
// Job 1
conf.setJobName(String.format("SampleSentences-2[%s: %s]", OUTPUT, outputPath));
conf.setNumMapTasks(20);
conf.setNumReduceTasks(0);
FileInputFormat.setInputPaths(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path("tmppath"));
// Delete the output directory if it exists already.
Path outputDir = new Path("tmppath");
FileSystem.get(conf).delete(outputDir, true);
JobClient.runJob(conf);
String jobID = args[0];
JobClient jobClient = new JobClient(new JobConf(getConf()));
- RunningJob job = jobClient.getJob(JobID.forName(jobID));
+ RunningJob job = jobClient.getJob(JobID.forName(conf.getJobName()));
Counters counters = job.getCounters();
long count = counters.getCounter(org.apache.hadoop.mapred.Task.Counter.MAP_INPUT_RECORDS);
// Job 2
conf.setLong("rseed", 1123456);
conf.setLong("count", count);
conf.setInt("nSamples", nSamples);
conf.set("sampleLang", sampleLang);
conf.setNumMapTasks(1);
conf.setNumReduceTasks(0);
conf.setMapperClass(SampleMapper.class);
//conf.setReducerClass(SignatureReducer.class);
conf.setJobName(String.format("SampleSentences-2[%s: %s]", OUTPUT, outputPath));
FileInputFormat.setInputPaths(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path(outputPath));
// Delete the output directory if it exists already.
outputDir = new Path(outputPath);
FileSystem.get(conf).delete(outputDir, true);
JobClient.runJob(conf);
return 0;
}
public SampleSentences() {}
public static void main(String[] args) throws Exception {
ToolRunner.run(new SampleSentences(), args);
}
}
| false | true | public int run(String[] args) throws Exception {
Options options = new Options();
options.addOption(OptionBuilder.withArgName("path")
.hasArg().withDescription("output path").create(OUTPUT));
options.addOption(OptionBuilder.withArgName("path")
.hasArg().withDescription("input").create(INPUT));
options.addOption(OptionBuilder.withArgName("lang")
.hasArg().withDescription("language to sample from").create(SAMPLE_LANG));
options.addOption(OptionBuilder.withArgName("int")
.hasArg().withDescription("language to sample from").create(SAMPLES));
CommandLine cmdline;
CommandLineParser parser = new GnuParser();
try {
cmdline = parser.parse(options, args);
} catch (ParseException exp) {
System.err.println("Error parsing command line: " + exp.getMessage());
return -1;
}
if (!cmdline.hasOption(OUTPUT) || !cmdline.hasOption(INPUT)
|| !cmdline.hasOption(SAMPLE_LANG) || !cmdline.hasOption(SAMPLES)
) {
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(120);
formatter.printHelp(this.getClass().getName(), options);
ToolRunner.printGenericCommandUsage(System.out);
return -1;
}
String inputPath = cmdline.getOptionValue(INPUT);
String outputPath = cmdline.getOptionValue(OUTPUT);
String sampleLang = cmdline.getOptionValue(SAMPLE_LANG);
int nSamples = Integer.parseInt(cmdline.getOptionValue(SAMPLES));
LOG.info("Tool name: " + this.getClass().getName());
LOG.info(" - nput file: " + inputPath);
LOG.info(" - output file: " + outputPath);
LOG.info(" - sample language: " + sampleLang);
JobConf conf = new JobConf(getConf(), SampleSentences.class);
// Set heap space - using old API
conf.set("mapred.job.map.memory.mb", "2048");
conf.set("mapred.map.child.java.opts", "-Xmx2048m");
conf.set("mapred.job.reduce.memory.mb", "8000");
conf.set("mapred.reduce.child.java.opts", "-Xmx8000m");
//conf.set("mapred.child.java.opts", "-Xmx2048m");
conf.setInputFormat(SequenceFileInputFormat.class);
conf.setOutputFormat(SequenceFileOutputFormat.class);
conf.setOutputKeyClass(PairOfLongInt.class);
conf.setOutputValueClass(PairOfStrings.class);
// Job 1
conf.setJobName(String.format("SampleSentences-2[%s: %s]", OUTPUT, outputPath));
conf.setNumMapTasks(20);
conf.setNumReduceTasks(0);
FileInputFormat.setInputPaths(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path("tmppath"));
// Delete the output directory if it exists already.
Path outputDir = new Path("tmppath");
FileSystem.get(conf).delete(outputDir, true);
JobClient.runJob(conf);
String jobID = args[0];
JobClient jobClient = new JobClient(new JobConf(getConf()));
RunningJob job = jobClient.getJob(JobID.forName(jobID));
Counters counters = job.getCounters();
long count = counters.getCounter(org.apache.hadoop.mapred.Task.Counter.MAP_INPUT_RECORDS);
// Job 2
conf.setLong("rseed", 1123456);
conf.setLong("count", count);
conf.setInt("nSamples", nSamples);
conf.set("sampleLang", sampleLang);
conf.setNumMapTasks(1);
conf.setNumReduceTasks(0);
conf.setMapperClass(SampleMapper.class);
//conf.setReducerClass(SignatureReducer.class);
conf.setJobName(String.format("SampleSentences-2[%s: %s]", OUTPUT, outputPath));
FileInputFormat.setInputPaths(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path(outputPath));
// Delete the output directory if it exists already.
outputDir = new Path(outputPath);
FileSystem.get(conf).delete(outputDir, true);
JobClient.runJob(conf);
return 0;
}
| public int run(String[] args) throws Exception {
Options options = new Options();
options.addOption(OptionBuilder.withArgName("path")
.hasArg().withDescription("output path").create(OUTPUT));
options.addOption(OptionBuilder.withArgName("path")
.hasArg().withDescription("input").create(INPUT));
options.addOption(OptionBuilder.withArgName("lang")
.hasArg().withDescription("language to sample from").create(SAMPLE_LANG));
options.addOption(OptionBuilder.withArgName("int")
.hasArg().withDescription("number of samples").create(SAMPLES));
CommandLine cmdline;
CommandLineParser parser = new GnuParser();
try {
cmdline = parser.parse(options, args);
} catch (ParseException exp) {
System.err.println("Error parsing command line: " + exp.getMessage());
return -1;
}
if (!cmdline.hasOption(OUTPUT) || !cmdline.hasOption(INPUT)
|| !cmdline.hasOption(SAMPLE_LANG) || !cmdline.hasOption(SAMPLES)
) {
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(120);
formatter.printHelp(this.getClass().getName(), options);
ToolRunner.printGenericCommandUsage(System.out);
return -1;
}
String inputPath = cmdline.getOptionValue(INPUT);
String outputPath = cmdline.getOptionValue(OUTPUT);
String sampleLang = cmdline.getOptionValue(SAMPLE_LANG);
int nSamples = Integer.parseInt(cmdline.getOptionValue(SAMPLES));
LOG.info("Tool name: " + this.getClass().getName());
LOG.info(" - nput file: " + inputPath);
LOG.info(" - output file: " + outputPath);
LOG.info(" - sample language: " + sampleLang);
JobConf conf = new JobConf(getConf(), SampleSentences.class);
// Set heap space - using old API
conf.set("mapred.job.map.memory.mb", "2048");
conf.set("mapred.map.child.java.opts", "-Xmx2048m");
conf.set("mapred.job.reduce.memory.mb", "8000");
conf.set("mapred.reduce.child.java.opts", "-Xmx8000m");
//conf.set("mapred.child.java.opts", "-Xmx2048m");
conf.setInputFormat(SequenceFileInputFormat.class);
conf.setOutputFormat(SequenceFileOutputFormat.class);
conf.setOutputKeyClass(PairOfLongInt.class);
conf.setOutputValueClass(PairOfStrings.class);
// Job 1
conf.setJobName(String.format("SampleSentences-2[%s: %s]", OUTPUT, outputPath));
conf.setNumMapTasks(20);
conf.setNumReduceTasks(0);
FileInputFormat.setInputPaths(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path("tmppath"));
// Delete the output directory if it exists already.
Path outputDir = new Path("tmppath");
FileSystem.get(conf).delete(outputDir, true);
JobClient.runJob(conf);
String jobID = args[0];
JobClient jobClient = new JobClient(new JobConf(getConf()));
RunningJob job = jobClient.getJob(JobID.forName(conf.getJobName()));
Counters counters = job.getCounters();
long count = counters.getCounter(org.apache.hadoop.mapred.Task.Counter.MAP_INPUT_RECORDS);
// Job 2
conf.setLong("rseed", 1123456);
conf.setLong("count", count);
conf.setInt("nSamples", nSamples);
conf.set("sampleLang", sampleLang);
conf.setNumMapTasks(1);
conf.setNumReduceTasks(0);
conf.setMapperClass(SampleMapper.class);
//conf.setReducerClass(SignatureReducer.class);
conf.setJobName(String.format("SampleSentences-2[%s: %s]", OUTPUT, outputPath));
FileInputFormat.setInputPaths(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path(outputPath));
// Delete the output directory if it exists already.
outputDir = new Path(outputPath);
FileSystem.get(conf).delete(outputDir, true);
JobClient.runJob(conf);
return 0;
}
|
diff --git a/WEB-INF/lps/server/src/org/openlaszlo/compiler/FileResolver.java b/WEB-INF/lps/server/src/org/openlaszlo/compiler/FileResolver.java
index d71a954c..adcd04e2 100644
--- a/WEB-INF/lps/server/src/org/openlaszlo/compiler/FileResolver.java
+++ b/WEB-INF/lps/server/src/org/openlaszlo/compiler/FileResolver.java
@@ -1,197 +1,198 @@
/* *****************************************************************************
* FileResolver.java
* ****************************************************************************/
/* J_LZ_COPYRIGHT_BEGIN *******************************************************
* Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* J_LZ_COPYRIGHT_END *********************************************************/
package org.openlaszlo.compiler;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
import org.openlaszlo.server.*;
import org.apache.log4j.*;
import org.openlaszlo.utils.FileUtils;
/**
* Provides an interface for resolving a pathname to a File. The
* Compiler class uses this to resolve includes (hrefs).
*
* @author Oliver Steele
*/
public interface FileResolver {
/** An instance of the DefaultFileResolver */
FileResolver DEFAULT_FILE_RESOLVER = new DefaultFileResolver();
/** Given a pathname, return the File that it names.
* @param pathname a path to resolve
* @param base a relative URI against which to resolve it
* @param asLibrary whether this URI is to a library or not
* @return see doc
* @exception java.io.FileNotFoundException if an error occurs
*/
File resolve(String pathname, String base, boolean asLibrary)
throws java.io.FileNotFoundException;
File resolve(CompilationEnvironment env, String pathname, String base, boolean asLibrary)
throws java.io.FileNotFoundException;
/**
* The Set of Files that represents the includes that have been
* implicitly included by binary libraries. This is updated by
* the library compiler and used to resolve paths that may not
* exist in the binary distribution.
*/
Set getBinaryIncludes();
}
/** DefaultFileResolver maps each pathname onto the File that
* it names, without doing any directory resolution or other
* magic. (The operating system's notion of a working directory
* supplies the context for partial pathnames.)
*/
class DefaultFileResolver implements FileResolver {
public Set binaryIncludes = new HashSet();
public Set getBinaryIncludes() { return binaryIncludes; }
public DefaultFileResolver() {
}
public File resolve(String pathname, String base, boolean asLibrary)
throws java.io.FileNotFoundException {
return resolve(null, pathname, base, asLibrary);
}
/** @see FileResolver */
public File resolve(CompilationEnvironment env, String pathname, String base, boolean asLibrary)
throws java.io.FileNotFoundException {
if (asLibrary) {
// If it is a library, search for .lzo's, consider the
// path may be just to the directory of the library
File library = null;
if (pathname.endsWith(".lzx")) {
library = resolveInternal(env, pathname.substring(0, pathname.length()-4) +".lzo", base);
if (library != null) {
return library;
}
} else {
// Try pathname as a directory
library = resolveInternal(env, (new File(pathname, "library.lzo").getPath()), base);
if (library != null) {
return library;
}
library = resolveInternal(env, (new File(pathname, "library.lzx").getPath()), base);
if (library != null) {
return library;
}
}
}
// Last resort for a library, normal case for plain files
File resolved = resolveInternal(env, pathname, base);
if (resolved != null) {
return resolved;
}
throw new java.io.FileNotFoundException(pathname);
}
protected File resolveInternal(CompilationEnvironment env, String pathname, String base) {
Logger mLogger = Logger.getLogger(FileResolver.class);
final String FILE_PROTOCOL = "file";
String protocol = FILE_PROTOCOL;
// The >1 test allows file pathnames to start with DOS
// drive letters.
int pos = pathname.indexOf(':');
if (pos > 1) {
protocol = pathname.substring(0, pos);
pathname = pathname.substring(pos + 1);
}
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Resolving pathname: " + p[0] + " and base: " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FileResolver.class.getName(),"051018-68", new Object[] {pathname, base})
);
if (!FILE_PROTOCOL.equals(protocol)) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="unknown protocol: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FileResolver.class.getName(),"051018-77", new Object[] {protocol})
);
}
// Determine whether to substitue resource files initially just swf to png
String pnext = FileUtils.getExtension(pathname);
boolean dhtmlResourceFlag = false;
if (env != null) {
dhtmlResourceFlag = env.isDHTML();
}
boolean SWFtoPNG = dhtmlResourceFlag && pnext.equalsIgnoreCase("swf");
if (SWFtoPNG) {
String pnbase = FileUtils.getBase(pathname);
pathname = pnbase + ".png";
}
// FIXME: [ebloch] this vector should be in a properties file
Vector v = new Vector();
if (pathname.startsWith("/")) {
// Try absolute
v.add("");
+ v.add(LPS.getComponentsDirectory());
}
v.add(base);
if (SWFtoPNG) {
String toAdd = FileUtils.insertSubdir(base + "/", "autoPng");
mLogger.debug("Default File Resolver Adding " + toAdd + '\n');
v.add(toAdd);
}
if (!pathname.startsWith("./") && !pathname.startsWith("../")) {
v.add(LPS.getComponentsDirectory());
v.add(LPS.getFontDirectory());
v.add(LPS.getLFCDirectory());
}
Enumeration e = v.elements();
while (e.hasMoreElements()) {
String dir = (String)e.nextElement();
try {
File f = (new File(dir, pathname)).getCanonicalFile();
if (f.exists() ||
((binaryIncludes != null) && binaryIncludes.contains(f))) {
mLogger.debug("Resolved " + pathname + " to " +
f.getAbsolutePath());
return f;
} else if (SWFtoPNG) {
String autoPngPath = FileUtils.insertSubdir(f.getPath(), "autoPng");
mLogger.debug("Default File Resolver Looking for " + autoPngPath + '\n');
File autoPngFile = new File(autoPngPath);
if (autoPngFile.exists()) {
mLogger.debug("Default File Resolver " + pathname + " to " +
autoPngFile.getAbsolutePath() + '\n');
return autoPngFile;
} else {
File [] pathArray = FileUtils.matchPlusSuffix(autoPngFile);
if (pathArray != null && pathArray.length != 0) {
return autoPngFile;
}
}
}
} catch (java.io.IOException ex) {
// Not a valid file?
}
}
return null;
}
}
| true | true | protected File resolveInternal(CompilationEnvironment env, String pathname, String base) {
Logger mLogger = Logger.getLogger(FileResolver.class);
final String FILE_PROTOCOL = "file";
String protocol = FILE_PROTOCOL;
// The >1 test allows file pathnames to start with DOS
// drive letters.
int pos = pathname.indexOf(':');
if (pos > 1) {
protocol = pathname.substring(0, pos);
pathname = pathname.substring(pos + 1);
}
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Resolving pathname: " + p[0] + " and base: " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FileResolver.class.getName(),"051018-68", new Object[] {pathname, base})
);
if (!FILE_PROTOCOL.equals(protocol)) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="unknown protocol: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FileResolver.class.getName(),"051018-77", new Object[] {protocol})
);
}
// Determine whether to substitue resource files initially just swf to png
String pnext = FileUtils.getExtension(pathname);
boolean dhtmlResourceFlag = false;
if (env != null) {
dhtmlResourceFlag = env.isDHTML();
}
boolean SWFtoPNG = dhtmlResourceFlag && pnext.equalsIgnoreCase("swf");
if (SWFtoPNG) {
String pnbase = FileUtils.getBase(pathname);
pathname = pnbase + ".png";
}
// FIXME: [ebloch] this vector should be in a properties file
Vector v = new Vector();
if (pathname.startsWith("/")) {
// Try absolute
v.add("");
}
v.add(base);
if (SWFtoPNG) {
String toAdd = FileUtils.insertSubdir(base + "/", "autoPng");
mLogger.debug("Default File Resolver Adding " + toAdd + '\n');
v.add(toAdd);
}
if (!pathname.startsWith("./") && !pathname.startsWith("../")) {
v.add(LPS.getComponentsDirectory());
v.add(LPS.getFontDirectory());
v.add(LPS.getLFCDirectory());
}
Enumeration e = v.elements();
while (e.hasMoreElements()) {
String dir = (String)e.nextElement();
try {
File f = (new File(dir, pathname)).getCanonicalFile();
if (f.exists() ||
((binaryIncludes != null) && binaryIncludes.contains(f))) {
mLogger.debug("Resolved " + pathname + " to " +
f.getAbsolutePath());
return f;
} else if (SWFtoPNG) {
String autoPngPath = FileUtils.insertSubdir(f.getPath(), "autoPng");
mLogger.debug("Default File Resolver Looking for " + autoPngPath + '\n');
File autoPngFile = new File(autoPngPath);
if (autoPngFile.exists()) {
mLogger.debug("Default File Resolver " + pathname + " to " +
autoPngFile.getAbsolutePath() + '\n');
return autoPngFile;
} else {
File [] pathArray = FileUtils.matchPlusSuffix(autoPngFile);
if (pathArray != null && pathArray.length != 0) {
return autoPngFile;
}
}
}
} catch (java.io.IOException ex) {
// Not a valid file?
}
}
return null;
}
| protected File resolveInternal(CompilationEnvironment env, String pathname, String base) {
Logger mLogger = Logger.getLogger(FileResolver.class);
final String FILE_PROTOCOL = "file";
String protocol = FILE_PROTOCOL;
// The >1 test allows file pathnames to start with DOS
// drive letters.
int pos = pathname.indexOf(':');
if (pos > 1) {
protocol = pathname.substring(0, pos);
pathname = pathname.substring(pos + 1);
}
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Resolving pathname: " + p[0] + " and base: " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FileResolver.class.getName(),"051018-68", new Object[] {pathname, base})
);
if (!FILE_PROTOCOL.equals(protocol)) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="unknown protocol: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FileResolver.class.getName(),"051018-77", new Object[] {protocol})
);
}
// Determine whether to substitue resource files initially just swf to png
String pnext = FileUtils.getExtension(pathname);
boolean dhtmlResourceFlag = false;
if (env != null) {
dhtmlResourceFlag = env.isDHTML();
}
boolean SWFtoPNG = dhtmlResourceFlag && pnext.equalsIgnoreCase("swf");
if (SWFtoPNG) {
String pnbase = FileUtils.getBase(pathname);
pathname = pnbase + ".png";
}
// FIXME: [ebloch] this vector should be in a properties file
Vector v = new Vector();
if (pathname.startsWith("/")) {
// Try absolute
v.add("");
v.add(LPS.getComponentsDirectory());
}
v.add(base);
if (SWFtoPNG) {
String toAdd = FileUtils.insertSubdir(base + "/", "autoPng");
mLogger.debug("Default File Resolver Adding " + toAdd + '\n');
v.add(toAdd);
}
if (!pathname.startsWith("./") && !pathname.startsWith("../")) {
v.add(LPS.getComponentsDirectory());
v.add(LPS.getFontDirectory());
v.add(LPS.getLFCDirectory());
}
Enumeration e = v.elements();
while (e.hasMoreElements()) {
String dir = (String)e.nextElement();
try {
File f = (new File(dir, pathname)).getCanonicalFile();
if (f.exists() ||
((binaryIncludes != null) && binaryIncludes.contains(f))) {
mLogger.debug("Resolved " + pathname + " to " +
f.getAbsolutePath());
return f;
} else if (SWFtoPNG) {
String autoPngPath = FileUtils.insertSubdir(f.getPath(), "autoPng");
mLogger.debug("Default File Resolver Looking for " + autoPngPath + '\n');
File autoPngFile = new File(autoPngPath);
if (autoPngFile.exists()) {
mLogger.debug("Default File Resolver " + pathname + " to " +
autoPngFile.getAbsolutePath() + '\n');
return autoPngFile;
} else {
File [] pathArray = FileUtils.matchPlusSuffix(autoPngFile);
if (pathArray != null && pathArray.length != 0) {
return autoPngFile;
}
}
}
} catch (java.io.IOException ex) {
// Not a valid file?
}
}
return null;
}
|
diff --git a/safe-online-data-ws/src/main/java/net/link/safeonline/data/ws/DataServiceFactory.java b/safe-online-data-ws/src/main/java/net/link/safeonline/data/ws/DataServiceFactory.java
index 6a15e7ed6..868f6ead1 100644
--- a/safe-online-data-ws/src/main/java/net/link/safeonline/data/ws/DataServiceFactory.java
+++ b/safe-online-data-ws/src/main/java/net/link/safeonline/data/ws/DataServiceFactory.java
@@ -1,32 +1,31 @@
/*
* SafeOnline project.
*
* Copyright 2006-2007 Lin.k N.V. All rights reserved.
* Lin.k N.V. proprietary/confidential. Use is subject to license terms.
*/
package net.link.safeonline.data.ws;
import java.net.URL;
import javax.xml.namespace.QName;
import liberty.dst._2006_08.ref.safe_online.DataService;
public class DataServiceFactory {
private DataServiceFactory() {
// empty
}
public static DataService newInstance() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL wsdlUrl = classLoader.getResource( "liberty-idwsf-dst-ref-v2.1-link.wsdl" );
if (null == wsdlUrl)
throw new RuntimeException( "Liberty ID-WSF DST Ref WSDL not found" );
- DataService dataService = new DataService( wsdlUrl, new QName( "urn:liberty:dst:2006-08:ref:safe-online", "DataService" ) );
- return dataService;
+ return new DataService( wsdlUrl, new QName( "urn:liberty:dst:2006-08:ref:safe-online", "DataService" ) );
}
}
| true | true | public static DataService newInstance() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL wsdlUrl = classLoader.getResource( "liberty-idwsf-dst-ref-v2.1-link.wsdl" );
if (null == wsdlUrl)
throw new RuntimeException( "Liberty ID-WSF DST Ref WSDL not found" );
DataService dataService = new DataService( wsdlUrl, new QName( "urn:liberty:dst:2006-08:ref:safe-online", "DataService" ) );
return dataService;
}
| public static DataService newInstance() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL wsdlUrl = classLoader.getResource( "liberty-idwsf-dst-ref-v2.1-link.wsdl" );
if (null == wsdlUrl)
throw new RuntimeException( "Liberty ID-WSF DST Ref WSDL not found" );
return new DataService( wsdlUrl, new QName( "urn:liberty:dst:2006-08:ref:safe-online", "DataService" ) );
}
|
diff --git a/src/java/net/sf/jabref/ContentSelectorDialog.java b/src/java/net/sf/jabref/ContentSelectorDialog.java
index da56e4591..ba91cb552 100644
--- a/src/java/net/sf/jabref/ContentSelectorDialog.java
+++ b/src/java/net/sf/jabref/ContentSelectorDialog.java
@@ -1,309 +1,309 @@
package net.sf.jabref;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.util.Iterator;
import java.util.Vector;
import java.util.TreeSet;
public class ContentSelectorDialog extends JDialog {
JPanel panel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JButton Close = new JButton();
GridBagLayout gridBagLayout1 = new GridBagLayout();
JPanel jPanel1 = new JPanel();
JLabel lab = new JLabel();
JTextField fieldTf = new JTextField();
JButton add = new JButton();
JPanel jPanel3 = new JPanel();
JButton remove = new JButton();
JComboBox fieldSelector = new JComboBox();
GridBagLayout gridBagLayout2 = new GridBagLayout();
//HelpAction help;
JButton help;
JPanel jPanel4 = new JPanel();
GridBagLayout gridBagLayout3 = new GridBagLayout();
GridBagLayout gridBagLayout4 = new GridBagLayout();
TitledBorder titledBorder1;
TitledBorder titledBorder2;
JLabel jLabel1 = new JLabel();
JComboBox wordSelector = new JComboBox();
JTextField wordTf = new JTextField();
JPanel jPanel5 = new JPanel();
GridBagLayout gridBagLayout5 = new GridBagLayout();
JButton addWord = new JButton();
JPanel jPanel6 = new JPanel();
JButton removeWord = new JButton();
GridBagLayout gridBagLayout6 = new GridBagLayout();
JButton select = new JButton();
final String
WORD_EMPTY_TEXT = Globals.lang("<no field>"),
WORD_FIRSTLINE_TEXT = Globals.lang("<select word>"),
FIELD_FIRST_LINE = Globals.lang("<field name>");
MetaData metaData;
String currentField = null;
TreeSet fieldSet, wordSet;
JabRefFrame frame;
public ContentSelectorDialog(JabRefFrame frame, boolean modal, MetaData metaData) {
super(frame, Globals.lang("Setup selectors"), modal);
this.metaData = metaData;
this.frame = frame;
help = new JButton(Globals.lang("Help"));
help.addActionListener(new HelpAction(frame.helpDiag, GUIGlobals.contentSelectorHelp, "Help"));
//help = new HelpAction(frame.helpDiag, GUIGlobals.contentSelectorHelp, "Help");
try {
jbInit();
wordSelector.addItem(WORD_EMPTY_TEXT);
pack();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public ContentSelectorDialog(JabRefFrame frame, boolean modal, MetaData metaData,
String fieldName) {
this(frame, modal, metaData);
try {
fieldSelector.setSelectedItem(fieldName);
} catch (Exception ex) {
ex.printStackTrace();
}
// The next two lines remove the part of the interface allowing
// the user to control which fields have a selector. I think this
// makes the dialog more intuitive. When the user opens this dialog
// from the Tools menu, the full interface will be available.
panel1.remove(jPanel1);
pack();
}
/**
* Set the contents of the field selector combobox.
*
*/
private void setupFieldSelector() {
fieldSelector.removeAllItems();
fieldSelector.addItem(FIELD_FIRST_LINE);
for (Iterator i=metaData.iterator(); i.hasNext();) {
String s = (String)i.next();
if (s.startsWith(Globals.SELECTOR_META_PREFIX))
fieldSelector.addItem(s.substring(Globals.SELECTOR_META_PREFIX.length()));
}
}
private void updateWordPanel() {
if (currentField == null) {
titledBorder2.setTitle("");
jPanel3.repaint();
return;
}
titledBorder2.setTitle(Globals.lang("Field")+": "+currentField);
jPanel3.repaint();
fillWordSelector();
wordTf.setText("");
}
private void fillWordSelector() {
wordSelector.removeAllItems();
wordSelector.addItem(WORD_FIRSTLINE_TEXT);
Vector items = metaData.getData(Globals.SELECTOR_META_PREFIX+currentField);
if ((items != null)) { // && (items.size() > 0)) {
wordSet = new TreeSet(items);
for (Iterator i=wordSet.iterator(); i.hasNext();)
wordSelector.addItem(i.next());
}
}
private void addWord() {
if (currentField == null)
return;
- String word = wordTf.getText().trim().toLowerCase();
+ String word = wordTf.getText().trim();
if (!wordSet.contains(word)) {
Util.pr(Globals.SELECTOR_META_PREFIX+currentField);
wordSet.add(word);
// Create a new Vector for this word list, and update the MetaData.
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector(wordSet));
fillWordSelector();
frame.basePanel().markNonUndoableBaseChanged();
//wordTf.selectAll();
wordTf.setText("");
wordTf.requestFocus();
}
}
private void addField() {
currentField = fieldTf.getText().trim().toLowerCase();
if (metaData.getData(Globals.SELECTOR_META_PREFIX+currentField) == null) {
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector());
frame.basePanel().markNonUndoableBaseChanged();
setupFieldSelector();
updateWordPanel();
}
}
private void removeWord() {
String word = wordTf.getText().trim().toLowerCase();
if (wordSet.contains(word)) {
wordSet.remove(word);
// Create a new Vector for this word list, and update the MetaData.
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector(wordSet));
fillWordSelector();
frame.basePanel().markNonUndoableBaseChanged();
//wordTf.selectAll();
wordTf.setText("");
wordTf.requestFocus();
}
}
void fieldSelector_actionPerformed(ActionEvent e) {
if (fieldSelector.getSelectedIndex() > 0) {
//fieldTf.setText((String)fieldSelector.getSelectedItem());
currentField = (String)fieldSelector.getSelectedItem();
updateWordPanel();
}
}
private void jbInit() throws Exception {
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142)),Globals.lang("Selector enabled fields"));
titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142)),Globals.lang("Item list for field"));
//jPanel1.setBackground(GUIGlobals.lightGray);
//jPanel2.setBackground(GUIGlobals.lightGray);
//panel1.setBackground(GUIGlobals.lightGray);
panel1.setLayout(gridBagLayout1);
Close.setText(Globals.lang("Close"));
Close.addActionListener(new ContentSelectorDialog_Close_actionAdapter(this));
lab.setRequestFocusEnabled(true);
lab.setText(Globals.lang("Field name")+":");
fieldTf.setSelectionEnd(8);
add.setText(Globals.lang("Add"));
remove.setText(Globals.lang("Remove"));
jPanel1.setLayout(gridBagLayout2);
jPanel1.setBorder(titledBorder1);
jPanel3.setBorder(titledBorder2);
jPanel3.setLayout(gridBagLayout4);
jPanel4.setLayout(gridBagLayout3);
jLabel1.setText(Globals.lang("Word")+":");
jPanel5.setLayout(gridBagLayout5);
addWord.setText(Globals.lang("Add"));
removeWord.setText(Globals.lang("Remove"));
jPanel6.setLayout(gridBagLayout6);
select.setText(Globals.lang("Select"));
fieldSelector.addActionListener(new ContentSelectorDialog_fieldSelector_actionAdapter(this));
getContentPane().add(panel1);
this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
//JToolBar tlb = new JToolBar();
//tlb.setLayout(new GridLayout(1,1));
//tlb.setPreferredSize(new Dimension(28, 28));
//tlb.setFloatable(false);
//tlb.add(help);
jPanel2.add(help, null);
jPanel2.add(Close, null);
panel1.add(jPanel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(lab, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(fieldTf, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 0));
panel1.add(jPanel3, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(fieldSelector, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(jPanel4, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel4.add(add, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel4.add(remove, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
jPanel3.add(wordSelector, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(wordTf, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(jPanel5, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel3.add(jPanel6, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel6.add(addWord, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel6.add(removeWord, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
jPanel1.add(select, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addField();
}
});
wordTf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addWord();
}
});
addWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addWord();
}
});
removeWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeWord();
}
});
wordSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (wordSelector.getSelectedIndex() > 0) {
wordTf.setText((String)wordSelector.getSelectedItem());
wordTf.requestFocus();
}
}
});
setupFieldSelector();
}
void Close_actionPerformed(ActionEvent e) {
dispose();
}
}
class ContentSelectorDialog_Close_actionAdapter implements java.awt.event.ActionListener {
ContentSelectorDialog adaptee;
ContentSelectorDialog_Close_actionAdapter(ContentSelectorDialog adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.Close_actionPerformed(e);
}
}
class ContentSelectorDialog_fieldSelector_actionAdapter implements java.awt.event.ActionListener {
ContentSelectorDialog adaptee;
ContentSelectorDialog_fieldSelector_actionAdapter(ContentSelectorDialog adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.fieldSelector_actionPerformed(e);
}
}
| true | true | private void fillWordSelector() {
wordSelector.removeAllItems();
wordSelector.addItem(WORD_FIRSTLINE_TEXT);
Vector items = metaData.getData(Globals.SELECTOR_META_PREFIX+currentField);
if ((items != null)) { // && (items.size() > 0)) {
wordSet = new TreeSet(items);
for (Iterator i=wordSet.iterator(); i.hasNext();)
wordSelector.addItem(i.next());
}
}
private void addWord() {
if (currentField == null)
return;
String word = wordTf.getText().trim().toLowerCase();
if (!wordSet.contains(word)) {
Util.pr(Globals.SELECTOR_META_PREFIX+currentField);
wordSet.add(word);
// Create a new Vector for this word list, and update the MetaData.
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector(wordSet));
fillWordSelector();
frame.basePanel().markNonUndoableBaseChanged();
//wordTf.selectAll();
wordTf.setText("");
wordTf.requestFocus();
}
}
private void addField() {
currentField = fieldTf.getText().trim().toLowerCase();
if (metaData.getData(Globals.SELECTOR_META_PREFIX+currentField) == null) {
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector());
frame.basePanel().markNonUndoableBaseChanged();
setupFieldSelector();
updateWordPanel();
}
}
private void removeWord() {
String word = wordTf.getText().trim().toLowerCase();
if (wordSet.contains(word)) {
wordSet.remove(word);
// Create a new Vector for this word list, and update the MetaData.
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector(wordSet));
fillWordSelector();
frame.basePanel().markNonUndoableBaseChanged();
//wordTf.selectAll();
wordTf.setText("");
wordTf.requestFocus();
}
}
void fieldSelector_actionPerformed(ActionEvent e) {
if (fieldSelector.getSelectedIndex() > 0) {
//fieldTf.setText((String)fieldSelector.getSelectedItem());
currentField = (String)fieldSelector.getSelectedItem();
updateWordPanel();
}
}
private void jbInit() throws Exception {
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142)),Globals.lang("Selector enabled fields"));
titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142)),Globals.lang("Item list for field"));
//jPanel1.setBackground(GUIGlobals.lightGray);
//jPanel2.setBackground(GUIGlobals.lightGray);
//panel1.setBackground(GUIGlobals.lightGray);
panel1.setLayout(gridBagLayout1);
Close.setText(Globals.lang("Close"));
Close.addActionListener(new ContentSelectorDialog_Close_actionAdapter(this));
lab.setRequestFocusEnabled(true);
lab.setText(Globals.lang("Field name")+":");
fieldTf.setSelectionEnd(8);
add.setText(Globals.lang("Add"));
remove.setText(Globals.lang("Remove"));
jPanel1.setLayout(gridBagLayout2);
jPanel1.setBorder(titledBorder1);
jPanel3.setBorder(titledBorder2);
jPanel3.setLayout(gridBagLayout4);
jPanel4.setLayout(gridBagLayout3);
jLabel1.setText(Globals.lang("Word")+":");
jPanel5.setLayout(gridBagLayout5);
addWord.setText(Globals.lang("Add"));
removeWord.setText(Globals.lang("Remove"));
jPanel6.setLayout(gridBagLayout6);
select.setText(Globals.lang("Select"));
fieldSelector.addActionListener(new ContentSelectorDialog_fieldSelector_actionAdapter(this));
getContentPane().add(panel1);
this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
//JToolBar tlb = new JToolBar();
//tlb.setLayout(new GridLayout(1,1));
//tlb.setPreferredSize(new Dimension(28, 28));
//tlb.setFloatable(false);
//tlb.add(help);
jPanel2.add(help, null);
jPanel2.add(Close, null);
panel1.add(jPanel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(lab, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(fieldTf, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 0));
panel1.add(jPanel3, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(fieldSelector, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(jPanel4, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel4.add(add, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel4.add(remove, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
jPanel3.add(wordSelector, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(wordTf, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(jPanel5, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel3.add(jPanel6, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel6.add(addWord, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel6.add(removeWord, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
jPanel1.add(select, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addField();
}
});
wordTf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addWord();
}
});
addWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addWord();
}
});
removeWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeWord();
}
});
wordSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (wordSelector.getSelectedIndex() > 0) {
wordTf.setText((String)wordSelector.getSelectedItem());
wordTf.requestFocus();
}
}
});
setupFieldSelector();
}
void Close_actionPerformed(ActionEvent e) {
dispose();
}
}
| private void fillWordSelector() {
wordSelector.removeAllItems();
wordSelector.addItem(WORD_FIRSTLINE_TEXT);
Vector items = metaData.getData(Globals.SELECTOR_META_PREFIX+currentField);
if ((items != null)) { // && (items.size() > 0)) {
wordSet = new TreeSet(items);
for (Iterator i=wordSet.iterator(); i.hasNext();)
wordSelector.addItem(i.next());
}
}
private void addWord() {
if (currentField == null)
return;
String word = wordTf.getText().trim();
if (!wordSet.contains(word)) {
Util.pr(Globals.SELECTOR_META_PREFIX+currentField);
wordSet.add(word);
// Create a new Vector for this word list, and update the MetaData.
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector(wordSet));
fillWordSelector();
frame.basePanel().markNonUndoableBaseChanged();
//wordTf.selectAll();
wordTf.setText("");
wordTf.requestFocus();
}
}
private void addField() {
currentField = fieldTf.getText().trim().toLowerCase();
if (metaData.getData(Globals.SELECTOR_META_PREFIX+currentField) == null) {
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector());
frame.basePanel().markNonUndoableBaseChanged();
setupFieldSelector();
updateWordPanel();
}
}
private void removeWord() {
String word = wordTf.getText().trim().toLowerCase();
if (wordSet.contains(word)) {
wordSet.remove(word);
// Create a new Vector for this word list, and update the MetaData.
metaData.putData(Globals.SELECTOR_META_PREFIX+currentField,
new Vector(wordSet));
fillWordSelector();
frame.basePanel().markNonUndoableBaseChanged();
//wordTf.selectAll();
wordTf.setText("");
wordTf.requestFocus();
}
}
void fieldSelector_actionPerformed(ActionEvent e) {
if (fieldSelector.getSelectedIndex() > 0) {
//fieldTf.setText((String)fieldSelector.getSelectedItem());
currentField = (String)fieldSelector.getSelectedItem();
updateWordPanel();
}
}
private void jbInit() throws Exception {
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142)),Globals.lang("Selector enabled fields"));
titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142)),Globals.lang("Item list for field"));
//jPanel1.setBackground(GUIGlobals.lightGray);
//jPanel2.setBackground(GUIGlobals.lightGray);
//panel1.setBackground(GUIGlobals.lightGray);
panel1.setLayout(gridBagLayout1);
Close.setText(Globals.lang("Close"));
Close.addActionListener(new ContentSelectorDialog_Close_actionAdapter(this));
lab.setRequestFocusEnabled(true);
lab.setText(Globals.lang("Field name")+":");
fieldTf.setSelectionEnd(8);
add.setText(Globals.lang("Add"));
remove.setText(Globals.lang("Remove"));
jPanel1.setLayout(gridBagLayout2);
jPanel1.setBorder(titledBorder1);
jPanel3.setBorder(titledBorder2);
jPanel3.setLayout(gridBagLayout4);
jPanel4.setLayout(gridBagLayout3);
jLabel1.setText(Globals.lang("Word")+":");
jPanel5.setLayout(gridBagLayout5);
addWord.setText(Globals.lang("Add"));
removeWord.setText(Globals.lang("Remove"));
jPanel6.setLayout(gridBagLayout6);
select.setText(Globals.lang("Select"));
fieldSelector.addActionListener(new ContentSelectorDialog_fieldSelector_actionAdapter(this));
getContentPane().add(panel1);
this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
//JToolBar tlb = new JToolBar();
//tlb.setLayout(new GridLayout(1,1));
//tlb.setPreferredSize(new Dimension(28, 28));
//tlb.setFloatable(false);
//tlb.add(help);
jPanel2.add(help, null);
jPanel2.add(Close, null);
panel1.add(jPanel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(lab, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(fieldTf, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 1, 0));
panel1.add(jPanel3, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(fieldSelector, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
jPanel1.add(jPanel4, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel4.add(add, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
jPanel4.add(remove, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
jPanel3.add(wordSelector, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(wordTf, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
jPanel3.add(jPanel5, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel3.add(jPanel6, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel6.add(addWord, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
jPanel6.add(removeWord, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
jPanel1.add(select, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addField();
}
});
wordTf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addWord();
}
});
addWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addWord();
}
});
removeWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeWord();
}
});
wordSelector.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (wordSelector.getSelectedIndex() > 0) {
wordTf.setText((String)wordSelector.getSelectedItem());
wordTf.requestFocus();
}
}
});
setupFieldSelector();
}
void Close_actionPerformed(ActionEvent e) {
dispose();
}
}
|
diff --git a/CookieSlap/src/rageteam/cookieslap/games/GameManager.java b/CookieSlap/src/rageteam/cookieslap/games/GameManager.java
index f103a94..b65ded3 100644
--- a/CookieSlap/src/rageteam/cookieslap/games/GameManager.java
+++ b/CookieSlap/src/rageteam/cookieslap/games/GameManager.java
@@ -1,135 +1,135 @@
package rageteam.cookieslap.games;
import java.util.Arrays;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import rageteam.cookieslap.main.CookieSlap;
import rageteam.cookieslap.main.ScoreboardUtils;
import rageteam.cookieslap.maps.Map;
import rageteam.cookieslap.players.CookieSlapPlayer;
import rageteam.cookieslap.players.UtilPlayer;
public class GameManager {
CookieSlap cookieslap;
UtilPlayer u;
public GameManager(CookieSlap cookieslap){
this.cookieslap = cookieslap;
}
public void startGame(Game game){
cookieslap.chat.log("New game commencing..");
game.startGameTimer();
Bukkit.getScheduler().cancelTask(game.counter);
game.status = Status.INGAME;
game.time = 240;
game.setLobbyCount(cookieslap.getConfig().getInt("auto-start.time"));
int c = 1;
game.loadFloors();
cookieslap.chat.bc("You are playing on &2 " + game.getMap().getName() + " &6.", game);
Map map = game.getMap();
ScoreboardUtils.get().hideScoreAll(game, "Starting in");
ScoreboardUtils.get().hideScoreAll(game, "Queue");
for(CookieSlapPlayer cp : game.players.values()){
cp.getPlayer().setLevel(0);
cp.getUtilPlayer().setAlive(true);
if(c > map.getSpawnCount()){
c = 1;
}
cp.getPlayer().teleport(map.getSpawn(c));
c++;
cp.getPlayer().setLevel(0);
cp.getPlayer().setGameMode(GameMode.ADVENTURE);
//give items
- for(int i = 0; i < 2; i++){
+ for(int i = 0; i < 1; i++){
cp.getPlayer().getInventory().setItem(i, getCookie());
}
}
game.getSign().update(map, false);
cookieslap.chat.bc("Use your cookie to knock other players off of the map", game);
}
public void stopGame(Game game, int r){
cookieslap.chat.log("Commencing Shutdown of " + game.getMap().getName() + ".");
game.status = Status.ENDING;
game.stopGameTimer();
game.setLobbyCount(31);
game.time = 240;
game.setStatus(Status.LOBBY);
game.resetArena();
game.data.clear();
game.floor.clear();
game.setStarting(false);
HashMap<String, CookieSlapPlayer> h = new HashMap<String, CookieSlapPlayer>(game.players);
game.players.clear();
for(CookieSlapPlayer cp : h.values()){
game.leaveGame(cp.getUtilPlayer());
}
if(r != 5){
cookieslap.chat.bc("CookieSlap has ended on the map " + game.getMap().getName() + ".");
}
if(!cookieslap.disabling){
game.getSign().update(game.map, true);
}
cookieslap.chat.log("Game has reset.");
}
public String getDigitTIme(int count){
int minutes = count / 60;
int seconds = count % 60;
String disMinu = (minutes < 10 ? "0" : "") + minutes;
String disSec = (seconds < 10 ? "0" : "") + seconds;
String formattedTime = disMinu + ":" + disSec;
return formattedTime;
}
public void inGameTime(int count, HashMap<String, CookieSlapPlayer> players){
for(CookieSlapPlayer cp : players.values()){
cookieslap.chat.sendMessage(cp.getPlayer(), "CookieSlap is ending in �5�1" + cookieslap.game.getDigitTIme(count));
}
}
public ItemStack getCookie(){
ItemStack cookie = new ItemStack(Material.COOKIE);
cookie.addUnsafeEnchantment(Enchantment.KNOCKBACK, 25);
ItemMeta cookieMeta = cookie.getItemMeta();
cookieMeta.setDisplayName("The Magical Cookie");
cookieMeta.setLore(Arrays.asList(new String[] { "�3Left-Click to knock players off the edge" }));
cookie.setItemMeta(cookieMeta);
return cookie;
}
}
| true | true | public void startGame(Game game){
cookieslap.chat.log("New game commencing..");
game.startGameTimer();
Bukkit.getScheduler().cancelTask(game.counter);
game.status = Status.INGAME;
game.time = 240;
game.setLobbyCount(cookieslap.getConfig().getInt("auto-start.time"));
int c = 1;
game.loadFloors();
cookieslap.chat.bc("You are playing on &2 " + game.getMap().getName() + " &6.", game);
Map map = game.getMap();
ScoreboardUtils.get().hideScoreAll(game, "Starting in");
ScoreboardUtils.get().hideScoreAll(game, "Queue");
for(CookieSlapPlayer cp : game.players.values()){
cp.getPlayer().setLevel(0);
cp.getUtilPlayer().setAlive(true);
if(c > map.getSpawnCount()){
c = 1;
}
cp.getPlayer().teleport(map.getSpawn(c));
c++;
cp.getPlayer().setLevel(0);
cp.getPlayer().setGameMode(GameMode.ADVENTURE);
//give items
for(int i = 0; i < 2; i++){
cp.getPlayer().getInventory().setItem(i, getCookie());
}
}
game.getSign().update(map, false);
cookieslap.chat.bc("Use your cookie to knock other players off of the map", game);
}
| public void startGame(Game game){
cookieslap.chat.log("New game commencing..");
game.startGameTimer();
Bukkit.getScheduler().cancelTask(game.counter);
game.status = Status.INGAME;
game.time = 240;
game.setLobbyCount(cookieslap.getConfig().getInt("auto-start.time"));
int c = 1;
game.loadFloors();
cookieslap.chat.bc("You are playing on &2 " + game.getMap().getName() + " &6.", game);
Map map = game.getMap();
ScoreboardUtils.get().hideScoreAll(game, "Starting in");
ScoreboardUtils.get().hideScoreAll(game, "Queue");
for(CookieSlapPlayer cp : game.players.values()){
cp.getPlayer().setLevel(0);
cp.getUtilPlayer().setAlive(true);
if(c > map.getSpawnCount()){
c = 1;
}
cp.getPlayer().teleport(map.getSpawn(c));
c++;
cp.getPlayer().setLevel(0);
cp.getPlayer().setGameMode(GameMode.ADVENTURE);
//give items
for(int i = 0; i < 1; i++){
cp.getPlayer().getInventory().setItem(i, getCookie());
}
}
game.getSign().update(map, false);
cookieslap.chat.bc("Use your cookie to knock other players off of the map", game);
}
|
diff --git a/modules/dm4-core/src/main/java/de/deepamehta/core/impl/TypeStorageImpl.java b/modules/dm4-core/src/main/java/de/deepamehta/core/impl/TypeStorageImpl.java
index 203442d15..249e352dc 100644
--- a/modules/dm4-core/src/main/java/de/deepamehta/core/impl/TypeStorageImpl.java
+++ b/modules/dm4-core/src/main/java/de/deepamehta/core/impl/TypeStorageImpl.java
@@ -1,671 +1,671 @@
package de.deepamehta.core.impl;
import de.deepamehta.core.Association;
import de.deepamehta.core.AssociationType;
import de.deepamehta.core.AssociationDefinition;
import de.deepamehta.core.RelatedAssociation;
import de.deepamehta.core.RelatedTopic;
import de.deepamehta.core.ResultSet;
import de.deepamehta.core.Topic;
import de.deepamehta.core.TopicType;
import de.deepamehta.core.Type;
import de.deepamehta.core.model.AssociationDefinitionModel;
import de.deepamehta.core.model.AssociationModel;
import de.deepamehta.core.model.AssociationRoleModel;
import de.deepamehta.core.model.AssociationTypeModel;
import de.deepamehta.core.model.IndexMode;
import de.deepamehta.core.model.RelatedAssociationModel;
import de.deepamehta.core.model.RelatedTopicModel;
import de.deepamehta.core.model.RoleModel;
import de.deepamehta.core.model.SimpleValue;
import de.deepamehta.core.model.TopicModel;
import de.deepamehta.core.model.TopicRoleModel;
import de.deepamehta.core.model.TopicTypeModel;
import de.deepamehta.core.model.TypeModel;
import de.deepamehta.core.model.ViewConfigurationModel;
import de.deepamehta.core.service.Directives;
import de.deepamehta.core.service.TypeStorage;
import de.deepamehta.core.util.DeepaMehtaUtils;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
/**
* Helper for storing and fetching type models.
* ### TODO: rename class.
*/
class TypeStorageImpl implements TypeStorage {
// ---------------------------------------------------------------------------------------------- Instance Variables
private Map<String, TypeModel> typeCache = new HashMap();
private EmbeddedService dms;
private Logger logger = Logger.getLogger(getClass().getName());
// ---------------------------------------------------------------------------------------------------- Constructors
TypeStorageImpl(EmbeddedService dms) {
this.dms = dms;
}
// --------------------------------------------------------------------------------------------------------- Methods
// === Type Cache ===
private TypeModel getType(String typeUri) {
return typeCache.get(typeUri);
}
private void putInTypeCache(TypeModel type) {
typeCache.put(type.getUri(), type);
}
// ---
TopicTypeModel getTopicType(String topicTypeUri) {
TopicTypeModel topicType = (TopicTypeModel) getType(topicTypeUri);
return topicType != null ? topicType : fetchTopicType(topicTypeUri);
}
AssociationTypeModel getAssociationType(String assocTypeUri) {
AssociationTypeModel assocType = (AssociationTypeModel) getType(assocTypeUri);
return assocType != null ? assocType : fetchAssociationType(assocTypeUri);
}
// === Types ===
// --- Fetch ---
// ### TODO: unify with next method
private TopicTypeModel fetchTopicType(String topicTypeUri) {
Topic typeTopic = dms.getTopic("uri", new SimpleValue(topicTypeUri), false, null);
checkTopicType(topicTypeUri, typeTopic);
//
// 1) fetch type components
String dataTypeUri = fetchDataTypeTopic(typeTopic.getId(), topicTypeUri, "topic type").getUri();
Set<IndexMode> indexModes = fetchIndexModes(typeTopic.getId());
List<AssociationDefinitionModel> assocDefs = fetchAssociationDefinitions(typeTopic);
List<String> labelConfig = fetchLabelConfig(assocDefs);
ViewConfigurationModel viewConfig = fetchTypeViewConfig(typeTopic);
//
// 2) build type model
TopicTypeModel topicType = new TopicTypeModel(typeTopic.getModel(), dataTypeUri, indexModes,
assocDefs, labelConfig, viewConfig);
//
// 3) put in type cache
putInTypeCache(topicType);
//
return topicType;
}
// ### TODO: unify with previous method
private AssociationTypeModel fetchAssociationType(String assocTypeUri) {
Topic typeTopic = dms.getTopic("uri", new SimpleValue(assocTypeUri), false, null);
checkAssociationType(assocTypeUri, typeTopic);
//
// 1) fetch type components
String dataTypeUri = fetchDataTypeTopic(typeTopic.getId(), assocTypeUri, "association type").getUri();
Set<IndexMode> indexModes = fetchIndexModes(typeTopic.getId());
List<AssociationDefinitionModel> assocDefs = fetchAssociationDefinitions(typeTopic);
List<String> labelConfig = fetchLabelConfig(assocDefs);
ViewConfigurationModel viewConfig = fetchTypeViewConfig(typeTopic);
//
// 2) build type model
AssociationTypeModel assocType = new AssociationTypeModel(typeTopic.getModel(), dataTypeUri, indexModes,
assocDefs, labelConfig, viewConfig);
//
// 3) put in type cache
putInTypeCache(assocType);
//
return assocType;
}
// ---
private void checkTopicType(String topicTypeUri, Topic typeTopic) {
if (typeTopic == null) {
throw new RuntimeException("Topic type \"" + topicTypeUri + "\" not found");
} else if (!typeTopic.getTypeUri().equals("dm4.core.topic_type") &&
!typeTopic.getTypeUri().equals("dm4.core.meta_type") &&
!typeTopic.getTypeUri().equals("dm4.core.meta_meta_type")) {
throw new RuntimeException("URI \"" + topicTypeUri + "\" refers to a \"" + typeTopic.getTypeUri() +
"\" when the caller expects a \"dm4.core.topic_type\"");
}
}
private void checkAssociationType(String assocTypeUri, Topic typeTopic) {
if (typeTopic == null) {
throw new RuntimeException("Association type \"" + assocTypeUri + "\" not found");
} else if (!typeTopic.getTypeUri().equals("dm4.core.assoc_type")) {
throw new RuntimeException("URI \"" + assocTypeUri + "\" refers to a \"" + typeTopic.getTypeUri() +
"\" when the caller expects a \"dm4.core.assoc_type\"");
}
}
// --- Store ---
void storeType(TypeModel type) {
// 1) put in type cache
// Note: an association type must be put in type cache *before* storing its association definitions.
// Consider creation of association type "Composition Definition": it has a composition definition itself.
putInTypeCache(type);
//
// 2) store type-specific parts
associateDataType(type.getUri(), type.getDataTypeUri());
storeIndexModes(type.getUri(), type.getIndexModes());
storeAssocDefs(type.getUri(), type.getAssocDefs());
storeLabelConfig(type.getLabelConfig(), type.getAssocDefs());
storeViewConfig(createConfigurableType(type.getId()), type.getViewConfigModel());
}
// === Data Type ===
// --- Fetch ---
private RelatedTopicModel fetchDataTypeTopic(long typeId, String typeUri, String className) {
try {
RelatedTopicModel dataType = dms.storage.fetchTopicRelatedTopic(typeId, "dm4.core.aggregation",
"dm4.core.type", null, "dm4.core.data_type"); // ### FIXME: null
if (dataType == null) {
throw new RuntimeException("No data type topic is associated to " + className + " \"" + typeUri + "\"");
}
return dataType;
} catch (Exception e) {
throw new RuntimeException("Fetching the data type topic of " + className + " \"" + typeUri + "\" failed",
e);
}
}
// --- Store ---
void storeDataTypeUri(long typeId, String typeUri, String className, String dataTypeUri) {
// remove current assignment
long assocId = fetchDataTypeTopic(typeId, typeUri, className).getRelatingAssociation().getId();
dms.deleteAssociation(assocId, null); // clientState=null
// create new assignment
associateDataType(typeUri, dataTypeUri);
}
// ### TODO: drop in favor of _associateDataType() below?
private void associateDataType(String typeUri, String dataTypeUri) {
try {
dms.createAssociation("dm4.core.aggregation",
new TopicRoleModel(typeUri, "dm4.core.type"),
new TopicRoleModel(dataTypeUri, "dm4.core.default"));
} catch (Exception e) {
throw new RuntimeException("Associating type \"" + typeUri + "\" with data type \"" +
dataTypeUri + "\" failed", e);
}
}
// ---
/**
* Low-level method. Used for bootstrapping.
*/
void _associateDataType(String typeUri, String dataTypeUri) {
AssociationModel assoc = new AssociationModel("dm4.core.aggregation",
new TopicRoleModel(typeUri, "dm4.core.type"),
new TopicRoleModel(dataTypeUri, "dm4.core.default"));
dms.storage.storeAssociation(assoc);
dms.storage.storeAssociationValue(assoc.getId(), assoc.getSimpleValue());
}
// === Index Modes ===
// --- Fetch ---
private Set<IndexMode> fetchIndexModes(long typeId) {
ResultSet<RelatedTopicModel> indexModes = dms.storage.fetchTopicRelatedTopics(typeId, "dm4.core.aggregation",
"dm4.core.type", null, "dm4.core.index_mode", 0); // ### FIXME: null
return IndexMode.fromTopics(indexModes.getItems());
}
// --- Store ---
void storeIndexModes(String typeUri, Set<IndexMode> indexModes) {
for (IndexMode indexMode : indexModes) {
dms.createAssociation("dm4.core.aggregation",
new TopicRoleModel(typeUri, "dm4.core.type"),
new TopicRoleModel(indexMode.toUri(), "dm4.core.default"));
}
}
// === Association Definitions ===
// --- Fetch ---
private List<AssociationDefinitionModel> fetchAssociationDefinitions(Topic typeTopic) {
Map<Long, AssociationDefinitionModel> assocDefs = fetchAssociationDefinitionsUnsorted(typeTopic);
List<RelatedAssociationModel> sequence = fetchSequence(typeTopic);
// error check
if (assocDefs.size() != sequence.size()) {
throw new RuntimeException("DB inconsistency: type \"" + typeTopic.getUri() + "\" has " +
assocDefs.size() + " association definitions but in sequence are " + sequence.size());
}
//
return sortAssocDefs(assocDefs, DeepaMehtaUtils.idList(sequence));
}
private Map<Long, AssociationDefinitionModel> fetchAssociationDefinitionsUnsorted(Topic typeTopic) {
Map<Long, AssociationDefinitionModel> assocDefs = new HashMap();
//
- // 1) fetch part topic types
+ // 1) fetch child topic types
// Note: we must set fetchRelatingComposite to false here. Fetching the composite of association type
// Composition Definition would cause an endless recursion. Composition Definition is defined through
// Composition Definition itself (child types "Include in Label", "Ordered").
// Note: "othersTopicTypeUri" is set to null. We want consider "dm4.core.topic_type" and "dm4.core.meta_type"
// as well (the latter required e.g. by dm4-mail) ### TODO: add a getRelatedTopics() method that takes a list
// of topic types.
ResultSet<RelatedTopic> childTypes = typeTopic.getRelatedTopics(asList("dm4.core.aggregation_def",
"dm4.core.composition_def"), "dm4.core.parent_type", "dm4.core.child_type", null, false, false, 0, null);
// othersTopicTypeUri=null, fetchComposite=false, fetchRelatingComposite=false, clientState=null
//
// 2) create association definitions
// Note: the returned map is an intermediate, hashed by ID. The actual type model is
// subsequently build from it by sorting the assoc def's according to the sequence IDs.
for (RelatedTopic childType : childTypes) {
AssociationDefinitionModel assocDef = fetchAssociationDefinition(childType.getRelatingAssociation(),
typeTopic.getUri(), childType.getUri());
assocDefs.put(assocDef.getId(), assocDef);
}
return assocDefs;
}
// ---
@Override
public AssociationDefinitionModel fetchAssociationDefinition(Association assoc) {
return fetchAssociationDefinition(assoc, fetchParentType(assoc).getUri(), fetchChildType(assoc).getUri());
}
private AssociationDefinitionModel fetchAssociationDefinition(Association assoc, String parentTypeUri,
String childTypeUri) {
try {
long assocId = assoc.getId();
return new AssociationDefinitionModel(
assocId, assoc.getUri(), assoc.getTypeUri(),
parentTypeUri, childTypeUri,
fetchParentCardinality(assocId).getUri(), fetchChildCardinality(assocId).getUri(),
fetchAssocDefViewConfig(assoc)
);
} catch (Exception e) {
throw new RuntimeException("Fetching association definition failed (parentTypeUri=\"" + parentTypeUri +
"\", childTypeUri=" + childTypeUri + ", " + assoc + ")", e);
}
}
// ---
private List<AssociationDefinitionModel> sortAssocDefs(Map<Long, AssociationDefinitionModel> assocDefs,
List<Long> sequence) {
List<AssociationDefinitionModel> sortedAssocDefs = new ArrayList();
for (long assocDefId : sequence) {
AssociationDefinitionModel assocDef = assocDefs.get(assocDefId);
// error check
if (assocDef == null) {
throw new RuntimeException("DB inconsistency: ID " + assocDefId +
" is in sequence but not in the type's association definitions");
}
sortedAssocDefs.add(assocDef);
}
return sortedAssocDefs;
}
// --- Store ---
private void storeAssocDefs(String typeUri, Collection<AssociationDefinitionModel> assocDefs) {
for (AssociationDefinitionModel assocDef : assocDefs) {
storeAssociationDefinition(assocDef);
}
storeSequence(typeUri, assocDefs);
}
void storeAssociationDefinition(AssociationDefinitionModel assocDef) {
try {
// Note: creating the underlying association is conditional. It exists already for
// an interactively created association definition. Its ID is already set.
if (assocDef.getId() == -1) {
dms.createAssociation(assocDef, null); // clientState=null
}
// Note: the assoc def ID is known only after creating the association
long assocDefId = assocDef.getId();
// cardinality
associateParentCardinality(assocDefId, assocDef.getParentCardinalityUri());
associateChildCardinality(assocDefId, assocDef.getChildCardinalityUri());
//
storeViewConfig(createConfigurableAssocDef(assocDefId), assocDef.getViewConfigModel());
} catch (Exception e) {
throw new RuntimeException("Storing association definition \"" + assocDef.getChildTypeUri() +
"\" of type \"" + assocDef.getParentTypeUri() + "\" failed", e);
}
}
// === Parent Type / Child Type ===
// --- Fetch ---
@Override
public Topic fetchParentType(Association assoc) {
Topic parentTypeTopic = assoc.getTopic("dm4.core.parent_type");
// error check
if (parentTypeTopic == null) {
throw new RuntimeException("Invalid association definition: topic role dm4.core.parent_type " +
"is missing in " + assoc);
}
//
return parentTypeTopic;
}
@Override
public Topic fetchChildType(Association assoc) {
Topic childTypeTopic = assoc.getTopic("dm4.core.child_type");
// error check
if (childTypeTopic == null) {
throw new RuntimeException("Invalid association definition: topic role dm4.core.child_type " +
"is missing in " + assoc);
}
//
return childTypeTopic;
}
// === Cardinality ===
// --- Fetch ---
// ### TODO: pass Association instead ID?
private RelatedTopicModel fetchParentCardinality(long assocDefId) {
RelatedTopicModel parentCard = dms.storage.fetchAssociationRelatedTopic(assocDefId, "dm4.core.aggregation",
"dm4.core.assoc_def", "dm4.core.parent_cardinality", "dm4.core.cardinality");
// error check
if (parentCard == null) {
throw new RuntimeException("Invalid association definition: parent cardinality is missing (assocDefId=" +
assocDefId + ")");
}
//
return parentCard;
}
// ### TODO: pass Association instead ID?
private RelatedTopicModel fetchChildCardinality(long assocDefId) {
RelatedTopicModel childCard = dms.storage.fetchAssociationRelatedTopic(assocDefId, "dm4.core.aggregation",
"dm4.core.assoc_def", "dm4.core.child_cardinality", "dm4.core.cardinality");
// error check
if (childCard == null) {
throw new RuntimeException("Invalid association definition: child cardinality is missing (assocDefId=" +
assocDefId + ")");
}
//
return childCard;
}
// --- Store ---
void storeParentCardinalityUri(long assocDefId, String parentCardinalityUri) {
// remove current assignment
long assocId = fetchParentCardinality(assocDefId).getRelatingAssociation().getId();
dms.deleteAssociation(assocId, null); // clientState=null
// create new assignment
associateParentCardinality(assocDefId, parentCardinalityUri);
}
void storeChildCardinalityUri(long assocDefId, String childCardinalityUri) {
// remove current assignment
long assocId = fetchChildCardinality(assocDefId).getRelatingAssociation().getId();
dms.deleteAssociation(assocId, null); // clientState=null
// create new assignment
associateChildCardinality(assocDefId, childCardinalityUri);
}
// ---
private void associateParentCardinality(long assocDefId, String parentCardinalityUri) {
dms.createAssociation("dm4.core.aggregation",
new TopicRoleModel(parentCardinalityUri, "dm4.core.parent_cardinality"),
new AssociationRoleModel(assocDefId, "dm4.core.assoc_def"));
}
private void associateChildCardinality(long assocDefId, String childCardinalityUri) {
dms.createAssociation("dm4.core.aggregation",
new TopicRoleModel(childCardinalityUri, "dm4.core.child_cardinality"),
new AssociationRoleModel(assocDefId, "dm4.core.assoc_def"));
}
// === Sequence ===
// --- Fetch ---
List<RelatedAssociationModel> fetchSequence(Topic typeTopic) {
try {
List<RelatedAssociationModel> sequence = new ArrayList();
// find sequence start
RelatedAssociation assocDef = typeTopic.getRelatedAssociation("dm4.core.aggregation", "dm4.core.type",
"dm4.core.sequence_start", null, false, false); // othersAssocTypeUri=null
// fetch sequence segments
if (assocDef != null) {
sequence.add(assocDef.getModel());
while ((assocDef = assocDef.getRelatedAssociation("dm4.core.sequence", "dm4.core.predecessor",
"dm4.core.successor")) != null) {
//
sequence.add(assocDef.getModel());
}
}
//
return sequence;
} catch (Exception e) {
throw new RuntimeException("Fetching sequence for type \"" + typeTopic.getUri() + "\" failed", e);
}
}
// --- Store ---
private void storeSequence(String typeUri, Collection<AssociationDefinitionModel> assocDefs) {
logger.fine("Storing " + assocDefs.size() + " sequence segments for type \"" + typeUri + "\"");
AssociationDefinitionModel predecessor = null;
for (AssociationDefinitionModel assocDef : assocDefs) {
appendToSequence(typeUri, assocDef, predecessor);
predecessor = assocDef;
}
}
void appendToSequence(String typeUri, AssociationDefinitionModel assocDef, AssociationDefinitionModel predecessor) {
if (predecessor == null) {
storeSequenceStart(typeUri, assocDef.getId());
} else {
storeSequenceSegment(predecessor.getId(), assocDef.getId());
}
}
private void storeSequenceStart(String typeUri, long assocDefId) {
dms.createAssociation("dm4.core.aggregation",
new TopicRoleModel(typeUri, "dm4.core.type"),
new AssociationRoleModel(assocDefId, "dm4.core.sequence_start"));
}
private void storeSequenceSegment(long predAssocDefId, long succAssocDefId) {
dms.createAssociation("dm4.core.sequence",
new AssociationRoleModel(predAssocDefId, "dm4.core.predecessor"),
new AssociationRoleModel(succAssocDefId, "dm4.core.successor"));
}
// ---
void rebuildSequence(Type type) {
deleteSequence(type);
storeSequence(type.getUri(), type.getModel().getAssocDefs());
}
private void deleteSequence(Topic typeTopic) {
List<RelatedAssociationModel> sequence = fetchSequence(typeTopic);
logger.info("### Deleting " + sequence.size() + " sequence segments of type \"" + typeTopic.getUri() + "\"");
for (RelatedAssociationModel assoc : sequence) {
long assocId = assoc.getRelatingAssociation().getId();
dms.deleteAssociation(assocId, null); // clientState=null
}
}
// === Label Configuration ===
// --- Fetch ---
private List<String> fetchLabelConfig(List<AssociationDefinitionModel> assocDefs) {
List<String> labelConfig = new ArrayList();
for (AssociationDefinitionModel assocDef : assocDefs) {
RelatedTopicModel includeInLabel = fetchLabelConfigTopic(assocDef.getId());
if (includeInLabel != null && includeInLabel.getSimpleValue().booleanValue()) {
labelConfig.add(assocDef.getChildTypeUri());
}
}
return labelConfig;
}
private RelatedTopicModel fetchLabelConfigTopic(long assocDefId) {
return dms.storage.fetchAssociationRelatedTopic(assocDefId, "dm4.core.composition",
"dm4.core.parent", "dm4.core.child", "dm4.core.include_in_label");
}
// --- Store ---
void storeLabelConfig(List<String> labelConfig, Collection<AssociationDefinitionModel> assocDefs) {
for (AssociationDefinitionModel assocDef : assocDefs) {
boolean includeInLabel = labelConfig.contains(assocDef.getChildTypeUri());
new AttachedAssociationDefinition(assocDef, dms).getCompositeValue()
.set("dm4.core.include_in_label", includeInLabel, null, new Directives());
}
}
// === View Configurations ===
// --- Fetch ---
private ViewConfigurationModel fetchTypeViewConfig(Topic typeTopic) {
try {
// Note: othersTopicTypeUri=null, the view config's topic type is unknown (it is client-specific)
ResultSet<RelatedTopic> configTopics = typeTopic.getRelatedTopics("dm4.core.aggregation",
"dm4.core.type", "dm4.core.view_config", null, true, false, 0, null);
return new ViewConfigurationModel(DeepaMehtaUtils.toTopicModels(configTopics.getItems()));
} catch (Exception e) {
throw new RuntimeException("Fetching view configuration for type \"" + typeTopic.getUri() +
"\" failed", e);
}
}
private ViewConfigurationModel fetchAssocDefViewConfig(Association assocDef) {
try {
// Note: othersTopicTypeUri=null, the view config's topic type is unknown (it is client-specific)
ResultSet<RelatedTopic> configTopics = assocDef.getRelatedTopics("dm4.core.aggregation",
"dm4.core.assoc_def", "dm4.core.view_config", null, true, false, 0, null);
return new ViewConfigurationModel(DeepaMehtaUtils.toTopicModels(configTopics.getItems()));
} catch (Exception e) {
throw new RuntimeException("Fetching view configuration for association definition " + assocDef.getId() +
" failed", e);
}
}
// ---
private RelatedTopicModel fetchTypeViewConfigTopic(long typeId, String configTypeUri) {
// Note: the composite is not fetched as it is not needed
return dms.storage.fetchTopicRelatedTopic(typeId, "dm4.core.aggregation",
"dm4.core.type", "dm4.core.view_config", configTypeUri);
}
private RelatedTopicModel fetchAssocDefViewConfigTopic(long assocDefId, String configTypeUri) {
// Note: the composite is not fetched as it is not needed
return dms.storage.fetchAssociationRelatedTopic(assocDefId, "dm4.core.aggregation",
"dm4.core.assoc_def", "dm4.core.view_config", configTypeUri);
}
// ---
private TopicModel fetchViewConfigTopic(RoleModel configurable, String configTypeUri) {
if (configurable instanceof TopicRoleModel) {
long typeId = configurable.getPlayerId();
return fetchTypeViewConfigTopic(typeId, configTypeUri);
} else if (configurable instanceof AssociationRoleModel) {
long assocDefId = configurable.getPlayerId();
return fetchAssocDefViewConfigTopic(assocDefId, configTypeUri);
} else {
throw new RuntimeException("Unexpected configurable: " + configurable);
}
}
// --- Store ---
private void storeViewConfig(RoleModel configurable, ViewConfigurationModel viewConfig) {
try {
for (TopicModel configTopic : viewConfig.getConfigTopics()) {
storeConfigTopic(configurable, configTopic);
}
} catch (Exception e) {
throw new RuntimeException("Storing view configuration failed (configurable=" + configurable + ")", e);
}
}
// ---
private void storeConfigTopic(RoleModel configurable, TopicModel configTopic) {
// Note: null is passed as clientState. Called only (indirectly) from a migration ### FIXME: is this true?
// and in a migration we have no clientState anyway.
Topic topic = dms.createTopic(configTopic, null); // clientState=null
dms.createAssociation("dm4.core.aggregation", configurable,
new TopicRoleModel(topic.getId(), "dm4.core.view_config"));
}
// ---
void storeViewConfigSetting(RoleModel configurable, String configTypeUri, String settingUri, Object value) {
try {
TopicModel configTopic = fetchViewConfigTopic(configurable, configTypeUri);
if (configTopic == null) {
configTopic = new TopicModel(configTypeUri);
storeConfigTopic(configurable, configTopic);
}
new AttachedTopic(configTopic, dms).getCompositeValue().set(settingUri, value, null, new Directives());
} catch (Exception e) {
throw new RuntimeException("Storing view configuration setting failed (configurable=" + configurable +
", configTypeUri=\"" + configTypeUri + "\", settingUri=\"" + settingUri + "\", value=\"" + value +
"\")", e);
}
}
// --- Helper ---
RoleModel createConfigurableType(long typeId) {
return new TopicRoleModel(typeId, "dm4.core.type");
}
RoleModel createConfigurableAssocDef(long assocDefId) {
return new AssociationRoleModel(assocDefId, "dm4.core.assoc_def");
}
}
| true | true | private Map<Long, AssociationDefinitionModel> fetchAssociationDefinitionsUnsorted(Topic typeTopic) {
Map<Long, AssociationDefinitionModel> assocDefs = new HashMap();
//
// 1) fetch part topic types
// Note: we must set fetchRelatingComposite to false here. Fetching the composite of association type
// Composition Definition would cause an endless recursion. Composition Definition is defined through
// Composition Definition itself (child types "Include in Label", "Ordered").
// Note: "othersTopicTypeUri" is set to null. We want consider "dm4.core.topic_type" and "dm4.core.meta_type"
// as well (the latter required e.g. by dm4-mail) ### TODO: add a getRelatedTopics() method that takes a list
// of topic types.
ResultSet<RelatedTopic> childTypes = typeTopic.getRelatedTopics(asList("dm4.core.aggregation_def",
"dm4.core.composition_def"), "dm4.core.parent_type", "dm4.core.child_type", null, false, false, 0, null);
// othersTopicTypeUri=null, fetchComposite=false, fetchRelatingComposite=false, clientState=null
//
// 2) create association definitions
// Note: the returned map is an intermediate, hashed by ID. The actual type model is
// subsequently build from it by sorting the assoc def's according to the sequence IDs.
for (RelatedTopic childType : childTypes) {
AssociationDefinitionModel assocDef = fetchAssociationDefinition(childType.getRelatingAssociation(),
typeTopic.getUri(), childType.getUri());
assocDefs.put(assocDef.getId(), assocDef);
}
return assocDefs;
}
| private Map<Long, AssociationDefinitionModel> fetchAssociationDefinitionsUnsorted(Topic typeTopic) {
Map<Long, AssociationDefinitionModel> assocDefs = new HashMap();
//
// 1) fetch child topic types
// Note: we must set fetchRelatingComposite to false here. Fetching the composite of association type
// Composition Definition would cause an endless recursion. Composition Definition is defined through
// Composition Definition itself (child types "Include in Label", "Ordered").
// Note: "othersTopicTypeUri" is set to null. We want consider "dm4.core.topic_type" and "dm4.core.meta_type"
// as well (the latter required e.g. by dm4-mail) ### TODO: add a getRelatedTopics() method that takes a list
// of topic types.
ResultSet<RelatedTopic> childTypes = typeTopic.getRelatedTopics(asList("dm4.core.aggregation_def",
"dm4.core.composition_def"), "dm4.core.parent_type", "dm4.core.child_type", null, false, false, 0, null);
// othersTopicTypeUri=null, fetchComposite=false, fetchRelatingComposite=false, clientState=null
//
// 2) create association definitions
// Note: the returned map is an intermediate, hashed by ID. The actual type model is
// subsequently build from it by sorting the assoc def's according to the sequence IDs.
for (RelatedTopic childType : childTypes) {
AssociationDefinitionModel assocDef = fetchAssociationDefinition(childType.getRelatingAssociation(),
typeTopic.getUri(), childType.getUri());
assocDefs.put(assocDef.getId(), assocDef);
}
return assocDefs;
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxModuleBuilder.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxModuleBuilder.java
index f51d8f389..7a99bdea7 100644
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxModuleBuilder.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxModuleBuilder.java
@@ -1,225 +1,231 @@
/*
* Copyright 1999-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.TypeTags.BOT;
import static com.sun.tools.javac.code.TypeTags.VOID;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Name.Table;
import com.sun.tools.javafx.tree.*;
import static com.sun.tools.javafx.tree.JavafxTag.*;
import java.io.File;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Set;
public class JavafxModuleBuilder extends JavafxTreeScanner {
protected static final Context.Key<JavafxModuleBuilder> javafxModuleBuilderKey =
new Context.Key<JavafxModuleBuilder>();
public static final String runMethodName = "javafx$run$";
private Table names;
private JavafxTreeMaker make;
private Log log;
private Set<Name> topLevelNamesSet;
public static JavafxModuleBuilder instance(Context context) {
JavafxModuleBuilder instance = context.get(javafxModuleBuilderKey);
if (instance == null)
instance = new JavafxModuleBuilder(context);
return instance;
}
protected JavafxModuleBuilder(Context context) {
names = Table.instance(context);
make = (JavafxTreeMaker)JavafxTreeMaker.instance(context);
log = Log.instance(context);
}
@Override
public void visitTopLevel(JCCompilationUnit tree) {
try {
preProcessJfxTopLevel(tree);
} finally {
topLevelNamesSet = null;
}
}
private void preProcessJfxTopLevel(JCCompilationUnit module) {
Name moduleClassName = moduleName(module);
// Divide module defs between run method body, Java compilation unit, and module class
ListBuffer<JCTree> topLevelDefs = new ListBuffer<JCTree>();
ListBuffer<JCTree> moduleClassDefs = new ListBuffer<JCTree>();
ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
JFXClassDeclaration moduleClass = null;
for (JCTree tree : module.defs) {
switch (tree.getTag()) {
case IMPORT:
topLevelDefs.append(tree);
break;
case CLASSDECL: {
JFXClassDeclaration decl = (JFXClassDeclaration)tree;
Name name = decl.name;
checkName(tree.pos, name);
if (name == moduleClassName) {
moduleClass = decl;
} else {
decl.mods.flags |= STATIC;
moduleClassDefs.append(tree);
}
break;
}
case OPERATIONDEF: {
- JFXOperationDefinition decl = (JFXOperationDefinition)tree;
+ JFXOperationDefinition decl = null;
+ if (tree instanceof JFXFunctionDefinitionStatement) {
+ decl = ((JFXFunctionDefinitionStatement)tree).funcDef;
+ }
+ else {
+ decl = (JFXOperationDefinition)tree;
+ }
decl.mods.flags |= STATIC;
Name name = decl.name;
checkName(tree.pos, name);
moduleClassDefs.append(tree);
break;
}
case VARDECL:
checkName(tree.pos, ((JFXVar)tree).getName());
stats.append((JCStatement)tree);
break;
default:
stats.append((JCStatement)tree);
break;
}
}
List<JCTree> emptyVarList = List.nil();
// Add run() method...
moduleClassDefs.prepend(makeModuleMethod(runMethodName, emptyVarList, false, stats.toList()));
if (moduleClass == null) {
moduleClass = make.ClassDeclaration(
make.Modifiers(0), //TODO: maybe? make.Modifiers(PUBLIC),
moduleClassName,
List.<JCExpression>nil(), // no supertypes
moduleClassDefs.toList());
} else {
moduleClass.defs = moduleClass.defs.appendList(moduleClassDefs);
}
moduleClass.isModuleClass = true;
topLevelDefs.append(moduleClass);
module.defs = topLevelDefs.toList();
}
@Override
public void visitMemberSelector(JFXMemberSelector that) {
// TODO:
}
@Override
public void visitDoLater(JFXDoLater that) {
// TODO:
}
@Override
public void visitTypeAny(JFXTypeAny that) {
// TODO:
}
@Override
public void visitTypeClass(JFXTypeClass that) {
// TODO:
}
@Override
public void visitTypeFunctional(JFXTypeFunctional that) {
// TODO:
}
@Override
public void visitTypeUnknown(JFXTypeUnknown that) {
// TODO:
}
@Override
public void visitVar(JFXVar that) {
}
private JFXOperationDefinition makeModuleMethod(String name, List<JCTree> paramList, boolean isStatic, List<JCStatement> stats) {
JFXBlockExpression body = make.BlockExpression(0, stats, null);
return make.OperationDefinition(
make.Modifiers(isStatic? PUBLIC | STATIC : PUBLIC),
Name.fromString(names, name),
make.TypeClass(make.Ident(Name.fromString(names, "Void")), JFXType.CARDINALITY_OPTIONAL),
paramList,
body);
}
private Name moduleName(JCCompilationUnit tree) {
String fileObjName = null;
try {
fileObjName = new File(tree.getSourceFile().toUri().toURL().getFile()).getName();
int lastDotIdx = fileObjName.lastIndexOf('.');
if (lastDotIdx != -1) {
fileObjName = fileObjName.substring(0, lastDotIdx);
}
} catch (MalformedURLException e) {
assert false : "URL Exception!!!";
}
return Name.fromString(names, fileObjName);
}
@Override
public boolean shouldVisitRemoved() {
return false;
}
@Override
public boolean shouldVisitSynthetic() {
return true;
}
private void checkName(int pos, Name name) {
if (topLevelNamesSet == null) {
topLevelNamesSet = new HashSet<Name>();
}
if (topLevelNamesSet.contains(name)) {
log.error(pos, "javafx.duplicate.module.member", name.toString());
}
topLevelNamesSet.add(name);
}
}
| true | true | private void preProcessJfxTopLevel(JCCompilationUnit module) {
Name moduleClassName = moduleName(module);
// Divide module defs between run method body, Java compilation unit, and module class
ListBuffer<JCTree> topLevelDefs = new ListBuffer<JCTree>();
ListBuffer<JCTree> moduleClassDefs = new ListBuffer<JCTree>();
ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
JFXClassDeclaration moduleClass = null;
for (JCTree tree : module.defs) {
switch (tree.getTag()) {
case IMPORT:
topLevelDefs.append(tree);
break;
case CLASSDECL: {
JFXClassDeclaration decl = (JFXClassDeclaration)tree;
Name name = decl.name;
checkName(tree.pos, name);
if (name == moduleClassName) {
moduleClass = decl;
} else {
decl.mods.flags |= STATIC;
moduleClassDefs.append(tree);
}
break;
}
case OPERATIONDEF: {
JFXOperationDefinition decl = (JFXOperationDefinition)tree;
decl.mods.flags |= STATIC;
Name name = decl.name;
checkName(tree.pos, name);
moduleClassDefs.append(tree);
break;
}
case VARDECL:
checkName(tree.pos, ((JFXVar)tree).getName());
stats.append((JCStatement)tree);
break;
default:
stats.append((JCStatement)tree);
break;
}
}
List<JCTree> emptyVarList = List.nil();
// Add run() method...
moduleClassDefs.prepend(makeModuleMethod(runMethodName, emptyVarList, false, stats.toList()));
if (moduleClass == null) {
moduleClass = make.ClassDeclaration(
make.Modifiers(0), //TODO: maybe? make.Modifiers(PUBLIC),
moduleClassName,
List.<JCExpression>nil(), // no supertypes
moduleClassDefs.toList());
} else {
moduleClass.defs = moduleClass.defs.appendList(moduleClassDefs);
}
moduleClass.isModuleClass = true;
topLevelDefs.append(moduleClass);
module.defs = topLevelDefs.toList();
}
| private void preProcessJfxTopLevel(JCCompilationUnit module) {
Name moduleClassName = moduleName(module);
// Divide module defs between run method body, Java compilation unit, and module class
ListBuffer<JCTree> topLevelDefs = new ListBuffer<JCTree>();
ListBuffer<JCTree> moduleClassDefs = new ListBuffer<JCTree>();
ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
JFXClassDeclaration moduleClass = null;
for (JCTree tree : module.defs) {
switch (tree.getTag()) {
case IMPORT:
topLevelDefs.append(tree);
break;
case CLASSDECL: {
JFXClassDeclaration decl = (JFXClassDeclaration)tree;
Name name = decl.name;
checkName(tree.pos, name);
if (name == moduleClassName) {
moduleClass = decl;
} else {
decl.mods.flags |= STATIC;
moduleClassDefs.append(tree);
}
break;
}
case OPERATIONDEF: {
JFXOperationDefinition decl = null;
if (tree instanceof JFXFunctionDefinitionStatement) {
decl = ((JFXFunctionDefinitionStatement)tree).funcDef;
}
else {
decl = (JFXOperationDefinition)tree;
}
decl.mods.flags |= STATIC;
Name name = decl.name;
checkName(tree.pos, name);
moduleClassDefs.append(tree);
break;
}
case VARDECL:
checkName(tree.pos, ((JFXVar)tree).getName());
stats.append((JCStatement)tree);
break;
default:
stats.append((JCStatement)tree);
break;
}
}
List<JCTree> emptyVarList = List.nil();
// Add run() method...
moduleClassDefs.prepend(makeModuleMethod(runMethodName, emptyVarList, false, stats.toList()));
if (moduleClass == null) {
moduleClass = make.ClassDeclaration(
make.Modifiers(0), //TODO: maybe? make.Modifiers(PUBLIC),
moduleClassName,
List.<JCExpression>nil(), // no supertypes
moduleClassDefs.toList());
} else {
moduleClass.defs = moduleClass.defs.appendList(moduleClassDefs);
}
moduleClass.isModuleClass = true;
topLevelDefs.append(moduleClass);
module.defs = topLevelDefs.toList();
}
|
diff --git a/src/nayuki/sortdemo/algo/CocktailSort.java b/src/nayuki/sortdemo/algo/CocktailSort.java
index 799f4ca..8f52cc7 100644
--- a/src/nayuki/sortdemo/algo/CocktailSort.java
+++ b/src/nayuki/sortdemo/algo/CocktailSort.java
@@ -1,35 +1,37 @@
package nayuki.sortdemo.algo;
import nayuki.sortdemo.SortAlgorithm;
import nayuki.sortdemo.SortArray;
public final class CocktailSort extends SortAlgorithm {
public void sort(SortArray array) {
int left = 0;
int right = array.length();
int i = left;
- while (left != right) {
+ while (left < right) {
// Scan right
for (; i + 1 < right; i++)
array.compareAndSwap(i, i + 1);
array.setDone(i);
right--;
i--;
+ if (left == right)
+ break;
// Scan left
for (; i > left; i--)
array.compareAndSwap(i - 1, i);
array.setDone(i);
left++;
i++;
}
}
public String getName() {
return "Cocktail sort";
}
}
| false | true | public void sort(SortArray array) {
int left = 0;
int right = array.length();
int i = left;
while (left != right) {
// Scan right
for (; i + 1 < right; i++)
array.compareAndSwap(i, i + 1);
array.setDone(i);
right--;
i--;
// Scan left
for (; i > left; i--)
array.compareAndSwap(i - 1, i);
array.setDone(i);
left++;
i++;
}
}
| public void sort(SortArray array) {
int left = 0;
int right = array.length();
int i = left;
while (left < right) {
// Scan right
for (; i + 1 < right; i++)
array.compareAndSwap(i, i + 1);
array.setDone(i);
right--;
i--;
if (left == right)
break;
// Scan left
for (; i > left; i--)
array.compareAndSwap(i - 1, i);
array.setDone(i);
left++;
i++;
}
}
|
diff --git a/bundleplugin/src/main/java/org/apache/felix/bundleplugin/ManifestPlugin.java b/bundleplugin/src/main/java/org/apache/felix/bundleplugin/ManifestPlugin.java
index 41e878037..bdba88540 100644
--- a/bundleplugin/src/main/java/org/apache/felix/bundleplugin/ManifestPlugin.java
+++ b/bundleplugin/src/main/java/org/apache/felix/bundleplugin/ManifestPlugin.java
@@ -1,161 +1,164 @@
/*
* 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.felix.bundleplugin;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.jar.Manifest;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import aQute.lib.osgi.Analyzer;
import aQute.lib.osgi.Jar;
/**
* Generate an OSGi manifest for this project
*
* @goal manifest
* @phase process-classes
* @requiresDependencyResolution runtime
*/
public class ManifestPlugin
extends BundlePlugin
{
/**
* Directory where the manifest will be written
* @parameter expression="${project.build.outputDirectory}/META-INF"
*/
private String manifestLocation;
protected void execute( MavenProject project, Map instructions, Properties properties, Jar[] classpath )
throws MojoExecutionException
{
Manifest manifest;
try
{
manifest = getManifest( project, instructions, properties, classpath );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error trying to generate Manifest", e );
}
File outputFile = new File( manifestLocation + "/MANIFEST.MF" );
try
{
writeManifest( manifest, outputFile );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error trying to write Manifest to file " + outputFile, e );
}
}
public Manifest getManifest( MavenProject project, Jar[] classpath )
throws IOException
{
return getManifest( project, null, null, classpath );
}
public Manifest getManifest( MavenProject project, Map instructions, Properties properties, Jar[] classpath )
throws IOException
{
return getAnalyzer( project, instructions, properties, classpath ).getJar().getManifest();
}
protected Analyzer getAnalyzer( MavenProject project, Jar[] classpath )
throws IOException
{
return getAnalyzer( project, new HashMap(), new Properties(), classpath );
}
protected Analyzer getAnalyzer( MavenProject project, Map instructions, Properties properties, Jar[] classpath )
throws IOException
{
PackageVersionAnalyzer analyzer = new PackageVersionAnalyzer();
Properties props = getDefaultProperties( project );
props.putAll( properties );
if ( !instructions.containsKey( Analyzer.IMPORT_PACKAGE ) )
{
props.put( Analyzer.IMPORT_PACKAGE, "*" );
}
props.putAll( transformDirectives( instructions ) );
analyzer.setProperties( props );
if ( project.getArtifact().getFile() == null )
{
- throw new NullPointerException( "Artifact file is null" );
+ analyzer.setJar( getOutputDirectory() );
+ }
+ else
+ {
+ analyzer.setJar( project.getArtifact().getFile() );
}
- analyzer.setJar( project.getArtifact().getFile() );
if ( classpath != null )
analyzer.setClasspath( classpath );
if ( !instructions.containsKey( Analyzer.PRIVATE_PACKAGE )
&& !instructions.containsKey( Analyzer.EXPORT_PACKAGE ) )
{
String export = analyzer.calculateExportsFromContents( analyzer.getJar() );
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, export );
}
analyzer.mergeManifest( analyzer.getJar().getManifest() );
analyzer.calcManifest();
return analyzer;
}
public void writeManifest( Manifest manifest, File outputFile )
throws IOException
{
outputFile.getParentFile().mkdirs();
FileOutputStream os;
os = new FileOutputStream( outputFile );
try
{
manifest.write( os );
}
finally
{
if ( os != null )
{
try
{
os.close();
}
catch ( IOException e )
{
//nothing we can do here
}
}
}
}
}
| false | true | protected Analyzer getAnalyzer( MavenProject project, Map instructions, Properties properties, Jar[] classpath )
throws IOException
{
PackageVersionAnalyzer analyzer = new PackageVersionAnalyzer();
Properties props = getDefaultProperties( project );
props.putAll( properties );
if ( !instructions.containsKey( Analyzer.IMPORT_PACKAGE ) )
{
props.put( Analyzer.IMPORT_PACKAGE, "*" );
}
props.putAll( transformDirectives( instructions ) );
analyzer.setProperties( props );
if ( project.getArtifact().getFile() == null )
{
throw new NullPointerException( "Artifact file is null" );
}
analyzer.setJar( project.getArtifact().getFile() );
if ( classpath != null )
analyzer.setClasspath( classpath );
if ( !instructions.containsKey( Analyzer.PRIVATE_PACKAGE )
&& !instructions.containsKey( Analyzer.EXPORT_PACKAGE ) )
{
String export = analyzer.calculateExportsFromContents( analyzer.getJar() );
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, export );
}
analyzer.mergeManifest( analyzer.getJar().getManifest() );
analyzer.calcManifest();
return analyzer;
}
| protected Analyzer getAnalyzer( MavenProject project, Map instructions, Properties properties, Jar[] classpath )
throws IOException
{
PackageVersionAnalyzer analyzer = new PackageVersionAnalyzer();
Properties props = getDefaultProperties( project );
props.putAll( properties );
if ( !instructions.containsKey( Analyzer.IMPORT_PACKAGE ) )
{
props.put( Analyzer.IMPORT_PACKAGE, "*" );
}
props.putAll( transformDirectives( instructions ) );
analyzer.setProperties( props );
if ( project.getArtifact().getFile() == null )
{
analyzer.setJar( getOutputDirectory() );
}
else
{
analyzer.setJar( project.getArtifact().getFile() );
}
if ( classpath != null )
analyzer.setClasspath( classpath );
if ( !instructions.containsKey( Analyzer.PRIVATE_PACKAGE )
&& !instructions.containsKey( Analyzer.EXPORT_PACKAGE ) )
{
String export = analyzer.calculateExportsFromContents( analyzer.getJar() );
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, export );
}
analyzer.mergeManifest( analyzer.getJar().getManifest() );
analyzer.calcManifest();
return analyzer;
}
|
diff --git a/src/main/java/net/unit8/sastruts/easyapi/converter/RequestConverter.java b/src/main/java/net/unit8/sastruts/easyapi/converter/RequestConverter.java
index fb8787c..bab2fb9 100644
--- a/src/main/java/net/unit8/sastruts/easyapi/converter/RequestConverter.java
+++ b/src/main/java/net/unit8/sastruts/easyapi/converter/RequestConverter.java
@@ -1,58 +1,58 @@
package net.unit8.sastruts.easyapi.converter;
import org.seasar.framework.util.StringUtil;
import net.unit8.sastruts.easyapi.dto.EasyApiMessageDto;
import net.unit8.sastruts.easyapi.dto.HeaderDto;
import net.unit8.sastruts.easyapi.dto.RequestDto;
import net.unit8.sastruts.easyapi.dto.ResponseDto;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
public class RequestConverter implements Converter {
public ThreadLocal<Class<?>> bodyDtoClass = new ThreadLocal<Class<?>>();
@SuppressWarnings("rawtypes")
public boolean canConvert(Class clazz) {
return EasyApiMessageDto.class.isAssignableFrom(clazz);
}
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
EasyApiMessageDto dto = (EasyApiMessageDto) source;
writer.startNode("head");
context.convertAnother(dto.header);
writer.endNode();
writer.startNode("body");
context.convertAnother(dto.body);
writer.endNode();
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
EasyApiMessageDto dto = null;
String nodeName = reader.getNodeName();
if (StringUtil.equals(nodeName, "request")) {
dto = new RequestDto();
} else if (StringUtil.equals(nodeName, "response")) {
dto = new ResponseDto();
} else {
throw new XStreamException("unknown node name");
}
while (reader.hasMoreChildren()) {
reader.moveDown();
- if (StringUtil.equals(reader.getNodeName(), "header")) {
+ if (StringUtil.equals(reader.getNodeName(), "head")) {
dto.header = (HeaderDto)context.convertAnother(dto, HeaderDto.class);
} else if (StringUtil.equals(reader.getNodeName(), "body")) {
dto.body = context.convertAnother(dto, bodyDtoClass.get());
}
reader.moveUp();
}
return dto;
}
}
| true | true | public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
EasyApiMessageDto dto = null;
String nodeName = reader.getNodeName();
if (StringUtil.equals(nodeName, "request")) {
dto = new RequestDto();
} else if (StringUtil.equals(nodeName, "response")) {
dto = new ResponseDto();
} else {
throw new XStreamException("unknown node name");
}
while (reader.hasMoreChildren()) {
reader.moveDown();
if (StringUtil.equals(reader.getNodeName(), "header")) {
dto.header = (HeaderDto)context.convertAnother(dto, HeaderDto.class);
} else if (StringUtil.equals(reader.getNodeName(), "body")) {
dto.body = context.convertAnother(dto, bodyDtoClass.get());
}
reader.moveUp();
}
return dto;
}
| public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
EasyApiMessageDto dto = null;
String nodeName = reader.getNodeName();
if (StringUtil.equals(nodeName, "request")) {
dto = new RequestDto();
} else if (StringUtil.equals(nodeName, "response")) {
dto = new ResponseDto();
} else {
throw new XStreamException("unknown node name");
}
while (reader.hasMoreChildren()) {
reader.moveDown();
if (StringUtil.equals(reader.getNodeName(), "head")) {
dto.header = (HeaderDto)context.convertAnother(dto, HeaderDto.class);
} else if (StringUtil.equals(reader.getNodeName(), "body")) {
dto.body = context.convertAnother(dto, bodyDtoClass.get());
}
reader.moveUp();
}
return dto;
}
|
diff --git a/src/com/android/phone/MyPhoneNumber.java b/src/com/android/phone/MyPhoneNumber.java
index d4008b0..e18c465 100644
--- a/src/com/android/phone/MyPhoneNumber.java
+++ b/src/com/android/phone/MyPhoneNumber.java
@@ -1,55 +1,59 @@
package com.android.phone;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.Log;
public class MyPhoneNumber extends BroadcastReceiver {
private final String LOG_TAG = "MyPhoneNumber";
private final boolean DBG = false;
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences prefs = context.getSharedPreferences(MyPhoneNumber.class.getPackage().getName() + "_preferences", Context.MODE_PRIVATE);
String phoneNum = mTelephonyMgr.getLine1Number();
String savedNum = prefs.getString(MSISDNEditPreference.PHONE_NUMBER, null);
boolean airplaneModeOn = intent.getBooleanExtra("state", false);
+ int simState = intent.getIntExtra("ss", -1);
if (airplaneModeOn) {
if (DBG)
Log.d(LOG_TAG, "Airplane Mode On. No modification to phone number.");
}
- else if (phoneNum == null) {
+ else if (phoneNum == null &&
+ (simState == 4 || simState == 6 || simState < 0) ) {
+ /* If we were triggered by a SIM_STATE change, it has to be
+ * 4 (SIM_READY) or 6 (RUIM_READY) */
if (DBG)
Log.d(LOG_TAG, "Trying to read the phone number from file");
if (savedNum != null) {
Phone mPhone = PhoneFactory.getDefaultPhone();
String alphaTag = mPhone.getLine1AlphaTag();
if (alphaTag == null || "".equals(alphaTag)) {
// No tag, set it.
alphaTag = "Voice Line 1";
}
mPhone.setLine1Number(alphaTag, savedNum, null);
if (DBG)
Log.d(LOG_TAG, "Phone number set to: " + savedNum);
} else if (DBG) {
Log.d(LOG_TAG, "No phone number set yet");
}
} else if (DBG) {
Log.d(LOG_TAG, "Phone number exists. No need to read it from file.");
}
}
}
| false | true | public void onReceive(Context context, Intent intent) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences prefs = context.getSharedPreferences(MyPhoneNumber.class.getPackage().getName() + "_preferences", Context.MODE_PRIVATE);
String phoneNum = mTelephonyMgr.getLine1Number();
String savedNum = prefs.getString(MSISDNEditPreference.PHONE_NUMBER, null);
boolean airplaneModeOn = intent.getBooleanExtra("state", false);
if (airplaneModeOn) {
if (DBG)
Log.d(LOG_TAG, "Airplane Mode On. No modification to phone number.");
}
else if (phoneNum == null) {
if (DBG)
Log.d(LOG_TAG, "Trying to read the phone number from file");
if (savedNum != null) {
Phone mPhone = PhoneFactory.getDefaultPhone();
String alphaTag = mPhone.getLine1AlphaTag();
if (alphaTag == null || "".equals(alphaTag)) {
// No tag, set it.
alphaTag = "Voice Line 1";
}
mPhone.setLine1Number(alphaTag, savedNum, null);
if (DBG)
Log.d(LOG_TAG, "Phone number set to: " + savedNum);
} else if (DBG) {
Log.d(LOG_TAG, "No phone number set yet");
}
} else if (DBG) {
Log.d(LOG_TAG, "Phone number exists. No need to read it from file.");
}
}
| public void onReceive(Context context, Intent intent) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences prefs = context.getSharedPreferences(MyPhoneNumber.class.getPackage().getName() + "_preferences", Context.MODE_PRIVATE);
String phoneNum = mTelephonyMgr.getLine1Number();
String savedNum = prefs.getString(MSISDNEditPreference.PHONE_NUMBER, null);
boolean airplaneModeOn = intent.getBooleanExtra("state", false);
int simState = intent.getIntExtra("ss", -1);
if (airplaneModeOn) {
if (DBG)
Log.d(LOG_TAG, "Airplane Mode On. No modification to phone number.");
}
else if (phoneNum == null &&
(simState == 4 || simState == 6 || simState < 0) ) {
/* If we were triggered by a SIM_STATE change, it has to be
* 4 (SIM_READY) or 6 (RUIM_READY) */
if (DBG)
Log.d(LOG_TAG, "Trying to read the phone number from file");
if (savedNum != null) {
Phone mPhone = PhoneFactory.getDefaultPhone();
String alphaTag = mPhone.getLine1AlphaTag();
if (alphaTag == null || "".equals(alphaTag)) {
// No tag, set it.
alphaTag = "Voice Line 1";
}
mPhone.setLine1Number(alphaTag, savedNum, null);
if (DBG)
Log.d(LOG_TAG, "Phone number set to: " + savedNum);
} else if (DBG) {
Log.d(LOG_TAG, "No phone number set yet");
}
} else if (DBG) {
Log.d(LOG_TAG, "Phone number exists. No need to read it from file.");
}
}
|
diff --git a/src/ultraextreme/view/SpriteFactory.java b/src/ultraextreme/view/SpriteFactory.java
index 173c0ff..611ba99 100644
--- a/src/ultraextreme/view/SpriteFactory.java
+++ b/src/ultraextreme/view/SpriteFactory.java
@@ -1,458 +1,458 @@
/* ============================================================
* Copyright 2012 Bjorn Persson Mattsson, Johan Gronvall, Daniel Jonsson,
* Viktor Anderling
*
* This file is part of UltraExtreme.
*
* UltraExtreme 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.
*
* UltraExtreme 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 UltraExtreme. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
package ultraextreme.view;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import javax.vecmath.Vector2d;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import ultraextreme.model.entity.AbstractBullet;
import ultraextreme.model.entity.IEntity;
import ultraextreme.model.util.Dimension;
import ultraextreme.model.util.ObjectName;
import ultraextreme.model.util.PlayerID;
/**
* Class in charge of creating new GameObjectSprites as well as instantiating
* them
*
* @author Johan Gronvall
* @author Daniel Jonsson
*
*/
public final class SpriteFactory {
public static void initialize(SimpleBaseGameActivity activity) {
instance = new SpriteFactory(activity);
}
private static final String BACKGROUND = "background";
private Map<ObjectName, ITextureRegion> textureMap = new HashMap<ObjectName, ITextureRegion>();
private Map<ObjectName, ITextureRegion> enemyBulletTextureMap = new HashMap<ObjectName, ITextureRegion>();
private Map<ObjectName, Vector2d> offsetMap = new HashMap<ObjectName, Vector2d>();
/**
* The items' textures.
*/
private Map<ObjectName, ITextureRegion> itemTextures = new HashMap<ObjectName, ITextureRegion>();
/**
* The item bar's texture.
*/
private ITextureRegion itemBarTexture;
/**
* The item bar's marker texture.
*/
private ITextureRegion itemBarMarkerTexture;
/**
* A map containing the main menu's textures, which are its background and
* buttons.
*/
private Map<String, ITextureRegion> mainMenuTextures;
/**
* A map containing the game over scene's textures, which are its background
* and buttons.
*/
private Map<String, ITextureRegion> gameOverTextures;
/**
* A map containing the options scene's textures, which are its background
* and buttons.
*/
private Map<OptionsTexture, ITextureRegion> optionsTextures;
public static enum OptionsTexture {
BACKGROUND, NORMAL_DIFFICULTY, HARD_DIFFICULTY, EXTREME_DIFFICULTY, ULTRAEXTREME_DIFFICULTY, RESET_BUTTON, RETURN_BUTTON
};
private TiledTextureRegion textInputBackground;
/**
* Reference to a sprite factory, making this a singleton.
*/
private static SpriteFactory instance;
/**
* Creates a spriteFactory OBS: should be called during a loadResources
* because this constructor might get heavy
*/
private SpriteFactory(final SimpleBaseGameActivity activity) {
Dimension screenDimension = new Dimension(activity.getResources()
.getDisplayMetrics().widthPixels, activity.getResources()
.getDisplayMetrics().heightPixels);
GameObjectSprite.setScreenDimension(screenDimension);
textureMap = new HashMap<ObjectName, ITextureRegion>();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
final TextureManager textureManager = activity.getTextureManager();
BitmapTextureAtlas textureAtlas = new BitmapTextureAtlas(
textureManager, 502, 119,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
// init enemies, bullets and the player
final TextureRegion playerShip = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "ship_blue_42px.png",
40, 0);
putProperties(ObjectName.PLAYERSHIP, playerShip,
new Vector2d(16.5, 13), false);
final TextureRegion playerBullet = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "laserGreen.png", 0,
34);
putProperties(ObjectName.BASIC_BULLET, playerBullet, new Vector2d(4.5,
16.5), false);
// create a texture for enemy bullets
final TextureRegion enemyBullet = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "laserRed.png", 0, 0);
putProperties(ObjectName.BASIC_BULLET, enemyBullet, new Vector2d(4.5,
16.5), true);
final TextureRegion basicEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_1.png",
165, 0);
putProperties(ObjectName.BASIC_ENEMYSHIP, basicEnemy, new Vector2d(27,
40), false);
final TextureRegion hitAndRunEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_2.png",
221, 0);
putProperties(ObjectName.HITANDRUN_ENEMYSHIP, hitAndRunEnemy,
new Vector2d(27, 40), false);
final TextureRegion parabolaEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_3.png", 275, 0);
putProperties(ObjectName.PARABOLA_ENEMYSHIP, parabolaEnemy,
new Vector2d(56, 59), false);
// init pickupables
final TextureRegion basicWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "cannon.png", 73, 31);
putProperties(ObjectName.BASIC_WEAPON, basicWeapon,
new Vector2d(15, 15), false);
itemTextures.put(ObjectName.BASIC_WEAPON, basicWeapon);
final TextureRegion spinningWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "spin.png", 9, 31);
putProperties(ObjectName.SPINNING_WEAPON, spinningWeapon, new Vector2d(
15, 15), false);
itemTextures.put(ObjectName.SPINNING_WEAPON, spinningWeapon);
final TextureRegion spreadWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "spread.png", 73, 0);
putProperties(ObjectName.SPREAD_WEAPON, spreadWeapon, new Vector2d(15,
15), false);
itemTextures.put(ObjectName.SPREAD_WEAPON, spinningWeapon);
// Init the item bar texture
itemBarTexture = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "itembar.png", 0, 68);
// Init the item bar marker
itemBarMarkerTexture = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "itembar_marker.png",
104, 0);
// Init the textinput background
textInputBackground = BitmapTextureAtlasTextureRegionFactory
.createTiledFromAsset(textureAtlas, activity, "button_1.png",
331, 0, 1, 1);
textureManager.loadTexture(textureAtlas);
// Init main menu atlas and texture map
mainMenuTextures = new HashMap<String, ITextureRegion>();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/menus/");
BitmapTextureAtlas textureAtlasMainMenu = new BitmapTextureAtlas(
textureManager, 800, 1854, TextureOptions.DEFAULT);
// Init the main menu background
mainMenuTextures.put(BACKGROUND, BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasMainMenu, activity,
"main_menu_bg.jpg", 0, 0));
// Init main menu's start button
mainMenuTextures.put("startButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_start_button.png", 0, 1281));
// Init main menu's high scores button
mainMenuTextures.put("highScoresButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_high_scores_button.png", 0, 1431));
// Init main menu's exit button
mainMenuTextures.put("exitButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_exit_button.png", 0, 1581));
// Init main menu's options button
mainMenuTextures.put("optionsButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_options_button.png", 0, 1711));
textureManager.loadTexture(textureAtlasMainMenu);
// Init game over scene atlas and texture map
gameOverTextures = new HashMap<String, ITextureRegion>();
BitmapTextureAtlas textureAtlasGameOver = new BitmapTextureAtlas(
textureManager, 800, 1984, TextureOptions.DEFAULT);
// Init the game over scene background
gameOverTextures.put(BACKGROUND, BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasGameOver, activity,
"game_over_bg.jpg", 0, 0));
// Init game over text
gameOverTextures.put("text", BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasGameOver, activity,
"game_over_text.png", 0, 1281));
// Init game over save button
gameOverTextures.put("saveButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasGameOver, activity,
"game_over_save_button.png", 0, 1770));
textureManager.loadTexture(textureAtlasGameOver);
// Init options scene atlas and texture map
optionsTextures = new EnumMap<OptionsTexture, ITextureRegion>(
OptionsTexture.class);
// FIXME: AndEngine can't handle a atlas with this enormous size...
// BitmapTextureAtlas textureAtlasOptions = new BitmapTextureAtlas(
// textureManager, 800, 2696, TextureOptions.DEFAULT);
BitmapTextureAtlas textureAtlasOptions = new BitmapTextureAtlas(
- textureManager, 800, 1753, TextureOptions.DEFAULT);
+ textureManager, 800, 1754, TextureOptions.DEFAULT);
BitmapTextureAtlas textureAtlasOptions2 = new BitmapTextureAtlas(
textureManager, 800, 944, TextureOptions.DEFAULT);
optionsTextures.put(OptionsTexture.BACKGROUND,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity, "options_bg.jpg", 0, 0));
optionsTextures.put(OptionsTexture.NORMAL_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity,
"options_difficulty_normal.png", 0, 1281));
optionsTextures.put(OptionsTexture.HARD_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity,
- "options_difficulty_hard.png", 0, 1517));
+ "options_difficulty_hard.png", 0, 1518));
optionsTextures.put(OptionsTexture.EXTREME_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_difficulty_extreme.png", 0, 0));
optionsTextures.put(OptionsTexture.ULTRAEXTREME_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_difficulty_ultraextreme.png", 0, 236));
optionsTextures.put(OptionsTexture.RESET_BUTTON,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_reset_button.png", 0, 472));
optionsTextures.put(OptionsTexture.RETURN_BUTTON,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_return_button.png", 0, 708));
textureManager.loadTexture(textureAtlasOptions);
textureManager.loadTexture(textureAtlasOptions2);
}
/**
*
* @return The texture of the item bar's marker.
*/
public static ITextureRegion getItemBarMarkerTexture() {
return instance.itemBarMarkerTexture;
}
/**
*
* @return The texture of the item bar.
*/
public static ITextureRegion getItemBarTexture() {
return instance.itemBarTexture;
}
/**
*
* @param item
* The item you want an image of.
* @return An texture of an item that you want to show in the item bar.
*/
public static ITextureRegion getItemTexture(ObjectName item) {
ITextureRegion output = instance.itemTextures.get(item);
if (output == null) {
throw new IllegalArgumentException(
"No texture is associated with that kind of object");
}
return output;
}
/**
*
* @return The texture of the main menu scene's background.
*/
public static ITextureRegion getMainMenuBackgroundTexture() {
return instance.mainMenuTextures.get(BACKGROUND);
}
/**
*
* @return The texture of the main menu scene's exit button.
*/
public static ITextureRegion getMainMenuExitButtonTexture() {
return instance.mainMenuTextures.get("exitButton");
}
/**
*
* @return The texture of the main menu scene's high scores button.
*/
public static ITextureRegion getMainMenuHighScoresButtonTexture() {
return instance.mainMenuTextures.get("highScoresButton");
}
/**
*
* @return The texture of the main menu scene's start button.
*/
public static ITextureRegion getMainMenuStartButtonTexture() {
return instance.mainMenuTextures.get("startButton");
}
/**
*
* @return The texture of the main menu scene's start button.
*/
public static ITextureRegion getMainMenuOptionsButtonTexture() {
return instance.mainMenuTextures.get("optionsButton");
}
/**
*
* @return The texture of the game over scene's background.
*/
public static ITextureRegion getGameOverBackgroundTexture() {
return instance.gameOverTextures.get(BACKGROUND);
}
/**
*
* @return The texture of the game over scene's text.
*/
public static ITextureRegion getGameOverTextTexture() {
return instance.gameOverTextures.get("text");
}
/**
*
* @return The texture of the game over scene's save button.
*/
public static ITextureRegion getGameOverSaveButtonTexture() {
return instance.gameOverTextures.get("saveButton");
}
public static ITextureRegion getOptionsTexture(OptionsTexture texture) {
return instance.optionsTextures.get(texture);
}
/**
* Creates and returns a sprite of the specified type
*
* @param entity
* The entity which this sprite is to follow
* @param vbom
* the VertexBufferOBjectManager
* @param objectName
* what kind of sprite (picture) is desired
* @return a new GameOBjectSprite
*/
public static GameObjectSprite getNewSprite(final IEntity entity,
final VertexBufferObjectManager vbom) {
ObjectName objName = entity.getObjectName();
ITextureRegion texture = instance.textureMap.get(objName);
Vector2d offset = instance.offsetMap.get(objName);
if (entity instanceof AbstractBullet) {
if (((AbstractBullet) entity).getPlayerId().equals(PlayerID.ENEMY)) {
texture = instance.enemyBulletTextureMap.get(objName);
}
}
if (texture == null) {
throw new IllegalArgumentException(
"No texture is associated with that kind of object");
}
if (offset == null) {
offset = new Vector2d();
}
return new GameObjectSprite(entity, vbom, texture, offset);
}
/**
* @return the textInputBackground
*/
public static TiledTextureRegion getTextInputBackground() {
return instance.textInputBackground;
}
/**
* Puts the properties into textureMap and offsetMap. Also multiplies the
* offset with the sprite scaling factor.
*
* @param objectName
* The key in the maps.
* @param texture
* The texture that goes into textureMap.
* @param textureOffset
* The offset that goes into offsetMap, multiplied with the
* sprite scaling factor.
* @param enemyBulletTexture
* Whether this texture is of an enemyBullet, in which case
* certain changes will be made
*/
private void putProperties(ObjectName objectName, TextureRegion texture,
Vector2d textureOffset, boolean enemyBulletTexture) {
textureOffset.scale(ultraextreme.util.Constants.SPRITE_SCALE_FACTOR);
if (enemyBulletTexture) {
enemyBulletTextureMap.put(objectName, texture);
} else {
textureMap.put(objectName, texture);
offsetMap.put(objectName, textureOffset);
}
}
}
| false | true | private SpriteFactory(final SimpleBaseGameActivity activity) {
Dimension screenDimension = new Dimension(activity.getResources()
.getDisplayMetrics().widthPixels, activity.getResources()
.getDisplayMetrics().heightPixels);
GameObjectSprite.setScreenDimension(screenDimension);
textureMap = new HashMap<ObjectName, ITextureRegion>();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
final TextureManager textureManager = activity.getTextureManager();
BitmapTextureAtlas textureAtlas = new BitmapTextureAtlas(
textureManager, 502, 119,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
// init enemies, bullets and the player
final TextureRegion playerShip = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "ship_blue_42px.png",
40, 0);
putProperties(ObjectName.PLAYERSHIP, playerShip,
new Vector2d(16.5, 13), false);
final TextureRegion playerBullet = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "laserGreen.png", 0,
34);
putProperties(ObjectName.BASIC_BULLET, playerBullet, new Vector2d(4.5,
16.5), false);
// create a texture for enemy bullets
final TextureRegion enemyBullet = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "laserRed.png", 0, 0);
putProperties(ObjectName.BASIC_BULLET, enemyBullet, new Vector2d(4.5,
16.5), true);
final TextureRegion basicEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_1.png",
165, 0);
putProperties(ObjectName.BASIC_ENEMYSHIP, basicEnemy, new Vector2d(27,
40), false);
final TextureRegion hitAndRunEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_2.png",
221, 0);
putProperties(ObjectName.HITANDRUN_ENEMYSHIP, hitAndRunEnemy,
new Vector2d(27, 40), false);
final TextureRegion parabolaEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_3.png", 275, 0);
putProperties(ObjectName.PARABOLA_ENEMYSHIP, parabolaEnemy,
new Vector2d(56, 59), false);
// init pickupables
final TextureRegion basicWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "cannon.png", 73, 31);
putProperties(ObjectName.BASIC_WEAPON, basicWeapon,
new Vector2d(15, 15), false);
itemTextures.put(ObjectName.BASIC_WEAPON, basicWeapon);
final TextureRegion spinningWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "spin.png", 9, 31);
putProperties(ObjectName.SPINNING_WEAPON, spinningWeapon, new Vector2d(
15, 15), false);
itemTextures.put(ObjectName.SPINNING_WEAPON, spinningWeapon);
final TextureRegion spreadWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "spread.png", 73, 0);
putProperties(ObjectName.SPREAD_WEAPON, spreadWeapon, new Vector2d(15,
15), false);
itemTextures.put(ObjectName.SPREAD_WEAPON, spinningWeapon);
// Init the item bar texture
itemBarTexture = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "itembar.png", 0, 68);
// Init the item bar marker
itemBarMarkerTexture = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "itembar_marker.png",
104, 0);
// Init the textinput background
textInputBackground = BitmapTextureAtlasTextureRegionFactory
.createTiledFromAsset(textureAtlas, activity, "button_1.png",
331, 0, 1, 1);
textureManager.loadTexture(textureAtlas);
// Init main menu atlas and texture map
mainMenuTextures = new HashMap<String, ITextureRegion>();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/menus/");
BitmapTextureAtlas textureAtlasMainMenu = new BitmapTextureAtlas(
textureManager, 800, 1854, TextureOptions.DEFAULT);
// Init the main menu background
mainMenuTextures.put(BACKGROUND, BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasMainMenu, activity,
"main_menu_bg.jpg", 0, 0));
// Init main menu's start button
mainMenuTextures.put("startButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_start_button.png", 0, 1281));
// Init main menu's high scores button
mainMenuTextures.put("highScoresButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_high_scores_button.png", 0, 1431));
// Init main menu's exit button
mainMenuTextures.put("exitButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_exit_button.png", 0, 1581));
// Init main menu's options button
mainMenuTextures.put("optionsButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_options_button.png", 0, 1711));
textureManager.loadTexture(textureAtlasMainMenu);
// Init game over scene atlas and texture map
gameOverTextures = new HashMap<String, ITextureRegion>();
BitmapTextureAtlas textureAtlasGameOver = new BitmapTextureAtlas(
textureManager, 800, 1984, TextureOptions.DEFAULT);
// Init the game over scene background
gameOverTextures.put(BACKGROUND, BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasGameOver, activity,
"game_over_bg.jpg", 0, 0));
// Init game over text
gameOverTextures.put("text", BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasGameOver, activity,
"game_over_text.png", 0, 1281));
// Init game over save button
gameOverTextures.put("saveButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasGameOver, activity,
"game_over_save_button.png", 0, 1770));
textureManager.loadTexture(textureAtlasGameOver);
// Init options scene atlas and texture map
optionsTextures = new EnumMap<OptionsTexture, ITextureRegion>(
OptionsTexture.class);
// FIXME: AndEngine can't handle a atlas with this enormous size...
// BitmapTextureAtlas textureAtlasOptions = new BitmapTextureAtlas(
// textureManager, 800, 2696, TextureOptions.DEFAULT);
BitmapTextureAtlas textureAtlasOptions = new BitmapTextureAtlas(
textureManager, 800, 1753, TextureOptions.DEFAULT);
BitmapTextureAtlas textureAtlasOptions2 = new BitmapTextureAtlas(
textureManager, 800, 944, TextureOptions.DEFAULT);
optionsTextures.put(OptionsTexture.BACKGROUND,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity, "options_bg.jpg", 0, 0));
optionsTextures.put(OptionsTexture.NORMAL_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity,
"options_difficulty_normal.png", 0, 1281));
optionsTextures.put(OptionsTexture.HARD_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity,
"options_difficulty_hard.png", 0, 1517));
optionsTextures.put(OptionsTexture.EXTREME_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_difficulty_extreme.png", 0, 0));
optionsTextures.put(OptionsTexture.ULTRAEXTREME_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_difficulty_ultraextreme.png", 0, 236));
optionsTextures.put(OptionsTexture.RESET_BUTTON,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_reset_button.png", 0, 472));
optionsTextures.put(OptionsTexture.RETURN_BUTTON,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_return_button.png", 0, 708));
textureManager.loadTexture(textureAtlasOptions);
textureManager.loadTexture(textureAtlasOptions2);
}
| private SpriteFactory(final SimpleBaseGameActivity activity) {
Dimension screenDimension = new Dimension(activity.getResources()
.getDisplayMetrics().widthPixels, activity.getResources()
.getDisplayMetrics().heightPixels);
GameObjectSprite.setScreenDimension(screenDimension);
textureMap = new HashMap<ObjectName, ITextureRegion>();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
final TextureManager textureManager = activity.getTextureManager();
BitmapTextureAtlas textureAtlas = new BitmapTextureAtlas(
textureManager, 502, 119,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
// init enemies, bullets and the player
final TextureRegion playerShip = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "ship_blue_42px.png",
40, 0);
putProperties(ObjectName.PLAYERSHIP, playerShip,
new Vector2d(16.5, 13), false);
final TextureRegion playerBullet = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "laserGreen.png", 0,
34);
putProperties(ObjectName.BASIC_BULLET, playerBullet, new Vector2d(4.5,
16.5), false);
// create a texture for enemy bullets
final TextureRegion enemyBullet = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "laserRed.png", 0, 0);
putProperties(ObjectName.BASIC_BULLET, enemyBullet, new Vector2d(4.5,
16.5), true);
final TextureRegion basicEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_1.png",
165, 0);
putProperties(ObjectName.BASIC_ENEMYSHIP, basicEnemy, new Vector2d(27,
40), false);
final TextureRegion hitAndRunEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_2.png",
221, 0);
putProperties(ObjectName.HITANDRUN_ENEMYSHIP, hitAndRunEnemy,
new Vector2d(27, 40), false);
final TextureRegion parabolaEnemy = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "evil_ship_3.png", 275, 0);
putProperties(ObjectName.PARABOLA_ENEMYSHIP, parabolaEnemy,
new Vector2d(56, 59), false);
// init pickupables
final TextureRegion basicWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "cannon.png", 73, 31);
putProperties(ObjectName.BASIC_WEAPON, basicWeapon,
new Vector2d(15, 15), false);
itemTextures.put(ObjectName.BASIC_WEAPON, basicWeapon);
final TextureRegion spinningWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "spin.png", 9, 31);
putProperties(ObjectName.SPINNING_WEAPON, spinningWeapon, new Vector2d(
15, 15), false);
itemTextures.put(ObjectName.SPINNING_WEAPON, spinningWeapon);
final TextureRegion spreadWeapon = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "spread.png", 73, 0);
putProperties(ObjectName.SPREAD_WEAPON, spreadWeapon, new Vector2d(15,
15), false);
itemTextures.put(ObjectName.SPREAD_WEAPON, spinningWeapon);
// Init the item bar texture
itemBarTexture = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "itembar.png", 0, 68);
// Init the item bar marker
itemBarMarkerTexture = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlas, activity, "itembar_marker.png",
104, 0);
// Init the textinput background
textInputBackground = BitmapTextureAtlasTextureRegionFactory
.createTiledFromAsset(textureAtlas, activity, "button_1.png",
331, 0, 1, 1);
textureManager.loadTexture(textureAtlas);
// Init main menu atlas and texture map
mainMenuTextures = new HashMap<String, ITextureRegion>();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/menus/");
BitmapTextureAtlas textureAtlasMainMenu = new BitmapTextureAtlas(
textureManager, 800, 1854, TextureOptions.DEFAULT);
// Init the main menu background
mainMenuTextures.put(BACKGROUND, BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasMainMenu, activity,
"main_menu_bg.jpg", 0, 0));
// Init main menu's start button
mainMenuTextures.put("startButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_start_button.png", 0, 1281));
// Init main menu's high scores button
mainMenuTextures.put("highScoresButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_high_scores_button.png", 0, 1431));
// Init main menu's exit button
mainMenuTextures.put("exitButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_exit_button.png", 0, 1581));
// Init main menu's options button
mainMenuTextures.put("optionsButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasMainMenu, activity,
"main_menu_options_button.png", 0, 1711));
textureManager.loadTexture(textureAtlasMainMenu);
// Init game over scene atlas and texture map
gameOverTextures = new HashMap<String, ITextureRegion>();
BitmapTextureAtlas textureAtlasGameOver = new BitmapTextureAtlas(
textureManager, 800, 1984, TextureOptions.DEFAULT);
// Init the game over scene background
gameOverTextures.put(BACKGROUND, BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasGameOver, activity,
"game_over_bg.jpg", 0, 0));
// Init game over text
gameOverTextures.put("text", BitmapTextureAtlasTextureRegionFactory
.createFromAsset(textureAtlasGameOver, activity,
"game_over_text.png", 0, 1281));
// Init game over save button
gameOverTextures.put("saveButton",
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasGameOver, activity,
"game_over_save_button.png", 0, 1770));
textureManager.loadTexture(textureAtlasGameOver);
// Init options scene atlas and texture map
optionsTextures = new EnumMap<OptionsTexture, ITextureRegion>(
OptionsTexture.class);
// FIXME: AndEngine can't handle a atlas with this enormous size...
// BitmapTextureAtlas textureAtlasOptions = new BitmapTextureAtlas(
// textureManager, 800, 2696, TextureOptions.DEFAULT);
BitmapTextureAtlas textureAtlasOptions = new BitmapTextureAtlas(
textureManager, 800, 1754, TextureOptions.DEFAULT);
BitmapTextureAtlas textureAtlasOptions2 = new BitmapTextureAtlas(
textureManager, 800, 944, TextureOptions.DEFAULT);
optionsTextures.put(OptionsTexture.BACKGROUND,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity, "options_bg.jpg", 0, 0));
optionsTextures.put(OptionsTexture.NORMAL_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity,
"options_difficulty_normal.png", 0, 1281));
optionsTextures.put(OptionsTexture.HARD_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions, activity,
"options_difficulty_hard.png", 0, 1518));
optionsTextures.put(OptionsTexture.EXTREME_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_difficulty_extreme.png", 0, 0));
optionsTextures.put(OptionsTexture.ULTRAEXTREME_DIFFICULTY,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_difficulty_ultraextreme.png", 0, 236));
optionsTextures.put(OptionsTexture.RESET_BUTTON,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_reset_button.png", 0, 472));
optionsTextures.put(OptionsTexture.RETURN_BUTTON,
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
textureAtlasOptions2, activity,
"options_return_button.png", 0, 708));
textureManager.loadTexture(textureAtlasOptions);
textureManager.loadTexture(textureAtlasOptions2);
}
|
diff --git a/src/main/java/hudson/maven/reporters/SurefireArchiver.java b/src/main/java/hudson/maven/reporters/SurefireArchiver.java
index 361a9f0..443f39b 100644
--- a/src/main/java/hudson/maven/reporters/SurefireArchiver.java
+++ b/src/main/java/hudson/maven/reporters/SurefireArchiver.java
@@ -1,214 +1,214 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jason Chaffee, Maciek Starzyk
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.maven.reporters;
import hudson.Util;
import hudson.Extension;
import hudson.maven.MavenBuild;
import hudson.maven.MavenBuildProxy;
import hudson.maven.MavenBuildProxy.BuildCallable;
import hudson.maven.MavenBuilder;
import hudson.maven.MavenModule;
import hudson.maven.MavenProjectActionBuilder;
import hudson.maven.MavenReporter;
import hudson.maven.MavenReporterDescriptor;
import hudson.maven.MojoInfo;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.junit.TestResult;
import hudson.tasks.test.TestResultProjectAction;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
/**
* Records the surefire test result.
* @author Kohsuke Kawaguchi
*/
public class SurefireArchiver extends MavenReporter {
private TestResult result;
public boolean preExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException {
if (isSurefireTest(mojo)) {
// tell surefire:test to keep going even if there was a failure,
// so that we can record this as yellow.
// note that because of the way Maven works, just updating system property at this point is too late
XmlPlexusConfiguration c = (XmlPlexusConfiguration) mojo.configuration.getChild("testFailureIgnore");
if(c!=null && c.getValue().equals("${maven.test.failure.ignore}") && System.getProperty("maven.test.failure.ignore")==null)
c.setValue("true");
}
return true;
}
public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException {
if (!isSurefireTest(mojo)) return true;
listener.getLogger().println(Messages.SurefireArchiver_Recording());
File reportsDir;
if (mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")) {
try {
reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir()));
build.setResult(Result.FAILURE);
return true;
}
}
else {
reportsDir = new File(pom.getBasedir(), "target/surefire-reports");
}
if(reportsDir.exists()) {
// surefire:test just skips itself when the current project is not a java project
FileSet fs = Util.createFileSet(reportsDir,"*.xml","testng-results.xml,testng-failed.xml");
DirectoryScanner ds = fs.getDirectoryScanner();
if(ds.getIncludedFiles().length==0)
// no test in this module
return true;
if(result==null) {
long t = System.currentTimeMillis() - build.getMilliSecsSinceBuildStart();
- result = new TestResult(t - 1000/*error margin*/, ds);
+ result = new TestResult(t - 1000/*error margin*/, ds, true);
} else
result.parse(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
int failCount = build.execute(new BuildCallable<Integer, IOException>() {
public Integer call(MavenBuild build) throws IOException, InterruptedException {
SurefireReport sr = build.getAction(SurefireReport.class);
if(sr==null)
build.getActions().add(new SurefireReport(build, result, listener));
else
sr.setResult(result,listener);
if(result.getFailCount()>0)
build.setResult(Result.UNSTABLE);
build.registerAsProjectAction(new FactoryImpl());
return result.getFailCount();
}
});
// if surefire plugin is going to kill maven because of a test failure,
// intercept that (or otherwise build will be marked as failure)
if(failCount>0 && error instanceof MojoFailureException) {
MavenBuilder.markAsSuccess = true;
}
}
return true;
}
/**
* Up to 1.372, there was a bug that causes Hudson to persist {@link SurefireArchiver} with the entire test result
* in it. If we are loading those, fix it up in memory to reduce the memory footprint.
*
* It'd be nice we can save the record to remove problematic portion, but that might have
* additional side effect.
*/
public static void fixUp(List<MavenProjectActionBuilder> builders) {
if (builders==null) return;
for (ListIterator<MavenProjectActionBuilder> itr = builders.listIterator(); itr.hasNext();) {
MavenProjectActionBuilder b = itr.next();
if (b instanceof SurefireArchiver)
itr.set(new FactoryImpl());
}
}
/**
* Part of the serialization data attached to {@link MavenBuild}.
*/
static final class FactoryImpl implements MavenProjectActionBuilder {
public Collection<? extends Action> getProjectActions(MavenModule module) {
return Collections.singleton(new TestResultProjectAction(module));
}
}
private boolean isSurefireTest(MojoInfo mojo) {
if ((!mojo.is("com.sun.maven", "maven-junit-plugin", "test"))
&& (!mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")))
return false;
try {
if (mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")) {
Boolean skip = mojo.getConfigurationValue("skip", Boolean.class);
if (((skip != null) && (skip))) {
return false;
}
if (mojo.pluginName.version.compareTo("2.3") >= 0) {
Boolean skipExec = mojo.getConfigurationValue("skipExec", Boolean.class);
if (((skipExec != null) && (skipExec))) {
return false;
}
}
if (mojo.pluginName.version.compareTo("2.4") >= 0) {
Boolean skipTests = mojo.getConfigurationValue("skipTests", Boolean.class);
if (((skipTests != null) && (skipTests))) {
return false;
}
}
}
else if (mojo.is("com.sun.maven", "maven-junit-plugin", "test")) {
Boolean skipTests = mojo.getConfigurationValue("skipTests", Boolean.class);
if (((skipTests != null) && (skipTests))) {
return false;
}
}
} catch (ComponentConfigurationException e) {
return false;
}
return true;
}
@Extension
public static final class DescriptorImpl extends MavenReporterDescriptor {
public String getDisplayName() {
return Messages.SurefireArchiver_DisplayName();
}
public SurefireArchiver newAutoInstance(MavenModule module) {
return new SurefireArchiver();
}
}
private static final long serialVersionUID = 1L;
}
| true | true | public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException {
if (!isSurefireTest(mojo)) return true;
listener.getLogger().println(Messages.SurefireArchiver_Recording());
File reportsDir;
if (mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")) {
try {
reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir()));
build.setResult(Result.FAILURE);
return true;
}
}
else {
reportsDir = new File(pom.getBasedir(), "target/surefire-reports");
}
if(reportsDir.exists()) {
// surefire:test just skips itself when the current project is not a java project
FileSet fs = Util.createFileSet(reportsDir,"*.xml","testng-results.xml,testng-failed.xml");
DirectoryScanner ds = fs.getDirectoryScanner();
if(ds.getIncludedFiles().length==0)
// no test in this module
return true;
if(result==null) {
long t = System.currentTimeMillis() - build.getMilliSecsSinceBuildStart();
result = new TestResult(t - 1000/*error margin*/, ds);
} else
result.parse(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
int failCount = build.execute(new BuildCallable<Integer, IOException>() {
public Integer call(MavenBuild build) throws IOException, InterruptedException {
SurefireReport sr = build.getAction(SurefireReport.class);
if(sr==null)
build.getActions().add(new SurefireReport(build, result, listener));
else
sr.setResult(result,listener);
if(result.getFailCount()>0)
build.setResult(Result.UNSTABLE);
build.registerAsProjectAction(new FactoryImpl());
return result.getFailCount();
}
});
// if surefire plugin is going to kill maven because of a test failure,
// intercept that (or otherwise build will be marked as failure)
if(failCount>0 && error instanceof MojoFailureException) {
MavenBuilder.markAsSuccess = true;
}
}
return true;
}
| public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException {
if (!isSurefireTest(mojo)) return true;
listener.getLogger().println(Messages.SurefireArchiver_Recording());
File reportsDir;
if (mojo.is("org.apache.maven.plugins", "maven-surefire-plugin", "test")) {
try {
reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir()));
build.setResult(Result.FAILURE);
return true;
}
}
else {
reportsDir = new File(pom.getBasedir(), "target/surefire-reports");
}
if(reportsDir.exists()) {
// surefire:test just skips itself when the current project is not a java project
FileSet fs = Util.createFileSet(reportsDir,"*.xml","testng-results.xml,testng-failed.xml");
DirectoryScanner ds = fs.getDirectoryScanner();
if(ds.getIncludedFiles().length==0)
// no test in this module
return true;
if(result==null) {
long t = System.currentTimeMillis() - build.getMilliSecsSinceBuildStart();
result = new TestResult(t - 1000/*error margin*/, ds, true);
} else
result.parse(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
int failCount = build.execute(new BuildCallable<Integer, IOException>() {
public Integer call(MavenBuild build) throws IOException, InterruptedException {
SurefireReport sr = build.getAction(SurefireReport.class);
if(sr==null)
build.getActions().add(new SurefireReport(build, result, listener));
else
sr.setResult(result,listener);
if(result.getFailCount()>0)
build.setResult(Result.UNSTABLE);
build.registerAsProjectAction(new FactoryImpl());
return result.getFailCount();
}
});
// if surefire plugin is going to kill maven because of a test failure,
// intercept that (or otherwise build will be marked as failure)
if(failCount>0 && error instanceof MojoFailureException) {
MavenBuilder.markAsSuccess = true;
}
}
return true;
}
|
diff --git a/java/servers/src/org/xtreemfs/mrc/osdselection/DCMapPolicyBase.java b/java/servers/src/org/xtreemfs/mrc/osdselection/DCMapPolicyBase.java
index 16dce9d3..213c487c 100644
--- a/java/servers/src/org/xtreemfs/mrc/osdselection/DCMapPolicyBase.java
+++ b/java/servers/src/org/xtreemfs/mrc/osdselection/DCMapPolicyBase.java
@@ -1,187 +1,188 @@
/*
* Copyright (c) 2009-2011 by Jan Stender, Bjoern Kolbeck,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.mrc.osdselection;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Properties;
import org.xtreemfs.foundation.LRUCache;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
/**
* Base class for policies that use datacenter maps.
*
* @author bjko, stender
*/
public abstract class DCMapPolicyBase implements OSDSelectionPolicy {
public static final String CONFIG_FILE_PATH = "/etc/xos/xtreemfs/datacentermap";
protected int[][] distMap;
protected Inet4AddressMatcher[][] matchers;
protected LRUCache<Inet4Address, Integer> matchingDCcache;
private boolean initialized;
public DCMapPolicyBase() {
try {
File f = new File(CONFIG_FILE_PATH);
Properties p = new Properties();
p.load(new FileInputStream(f));
readConfig(p);
int maxCacheSize = Integer.valueOf(p.getProperty("max_cache_size", "1000").trim());
matchingDCcache = new LRUCache<Inet4Address, Integer>(maxCacheSize);
initialized = true;
} catch (IOException ex) {
Logging.logMessage(Logging.LEVEL_WARN, Category.misc, this,
"cannot load %s, DCMap replica selection policy will not work", CONFIG_FILE_PATH);
Logging.logError(Logging.LEVEL_WARN, this, ex);
initialized = false;
}
}
public DCMapPolicyBase(Properties p) {
readConfig(p);
int maxCacheSize = Integer.valueOf(p.getProperty("max_cache_size", "1000"));
matchingDCcache = new LRUCache<Inet4Address, Integer>(maxCacheSize);
initialized = true;
}
private void readConfig(Properties p) {
String tmp = p.getProperty("datacenters");
if (tmp == null) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": a list of datacenters must be specified in the configuration");
}
final String[] dcs = tmp.split(",");
if (dcs.length == 0) {
Logging.logMessage(Logging.LEVEL_WARN, this, "no datacenters specified");
return;
}
for (int i = 0; i < dcs.length; i++) {
if (!dcs[i].matches("[a-zA-Z0-9_]+")) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": datacenter name '" + dcs[i] + "' is invalid");
}
}
distMap = new int[dcs.length][dcs.length];
matchers = new Inet4AddressMatcher[dcs.length][];
for (int i = 0; i < dcs.length; i++) {
for (int j = i + 1; j < dcs.length; j++) {
String distStr = p.getProperty("distance." + dcs[i] + "-" + dcs[j]);
if (distStr == null) {
distStr = p.getProperty("distance." + dcs[j] + "-" + dcs[i]);
}
if (distStr == null) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": distance between datacenter '" + dcs[i] + "' and '" + dcs[j]
+ "' is not specified");
}
try {
distMap[i][j] = distMap[j][i] = Integer.valueOf(distStr);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": distance '" + distStr + "' between datacenter '" + dcs[i] + "' and '" + dcs[j]
+ "' is not a valid integer");
}
}
String dcMatch = p.getProperty(dcs[i] + ".addresses");
if (dcMatch != null) {
String entries[] = dcMatch.split(",");
matchers[i] = new Inet4AddressMatcher[entries.length];
for (int e = 0; e < entries.length; e++) {
final String entry = entries[e];
if (entry.contains("/")) {
// network match
try {
String ipAddr = entry.substring(0, entry.indexOf("/"));
String prefix = entry.substring(entry.indexOf("/") + 1);
Inet4Address ia = (Inet4Address) InetAddress.getByName(ipAddr);
matchers[i][e] = new Inet4AddressMatcher(ia, Integer.valueOf(prefix));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": netmask in '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid integer");
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": address '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address");
}
} else {
// IP match
try {
Inet4Address ia = (Inet4Address) InetAddress.getByName(entry);
matchers[i][e] = new Inet4AddressMatcher(ia);
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": address '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address");
}
}
}
} else {
+ matchers[i] = new Inet4AddressMatcher[0];
// allow empty datacenters
Logging.logMessage(Logging.LEVEL_WARN, this, "datacenter '" + dcs[i] + "' has no entries!");
}
}
}
protected int getDistance(Inet4Address addr1, Inet4Address addr2) {
if(!initialized)
return 0;
final int dc1 = getMatchingDC(addr1);
final int dc2 = getMatchingDC(addr2);
if ((dc1 != -1) && (dc2 != -1)) {
return distMap[dc1][dc2];
} else {
return Integer.MAX_VALUE;
}
}
protected int getMatchingDC(Inet4Address addr) {
if(!initialized)
return -1;
Integer cached = matchingDCcache.get(addr);
if (cached == null) {
for (int i = 0; i < matchers.length; i++) {
for (int j = 0; j < matchers[i].length; j++) {
if (matchers[i][j].matches(addr)) {
matchingDCcache.put(addr, i);
return i;
}
}
}
matchingDCcache.put(addr, -1);
return -1;
} else {
return cached;
}
}
}
| true | true | private void readConfig(Properties p) {
String tmp = p.getProperty("datacenters");
if (tmp == null) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": a list of datacenters must be specified in the configuration");
}
final String[] dcs = tmp.split(",");
if (dcs.length == 0) {
Logging.logMessage(Logging.LEVEL_WARN, this, "no datacenters specified");
return;
}
for (int i = 0; i < dcs.length; i++) {
if (!dcs[i].matches("[a-zA-Z0-9_]+")) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": datacenter name '" + dcs[i] + "' is invalid");
}
}
distMap = new int[dcs.length][dcs.length];
matchers = new Inet4AddressMatcher[dcs.length][];
for (int i = 0; i < dcs.length; i++) {
for (int j = i + 1; j < dcs.length; j++) {
String distStr = p.getProperty("distance." + dcs[i] + "-" + dcs[j]);
if (distStr == null) {
distStr = p.getProperty("distance." + dcs[j] + "-" + dcs[i]);
}
if (distStr == null) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": distance between datacenter '" + dcs[i] + "' and '" + dcs[j]
+ "' is not specified");
}
try {
distMap[i][j] = distMap[j][i] = Integer.valueOf(distStr);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": distance '" + distStr + "' between datacenter '" + dcs[i] + "' and '" + dcs[j]
+ "' is not a valid integer");
}
}
String dcMatch = p.getProperty(dcs[i] + ".addresses");
if (dcMatch != null) {
String entries[] = dcMatch.split(",");
matchers[i] = new Inet4AddressMatcher[entries.length];
for (int e = 0; e < entries.length; e++) {
final String entry = entries[e];
if (entry.contains("/")) {
// network match
try {
String ipAddr = entry.substring(0, entry.indexOf("/"));
String prefix = entry.substring(entry.indexOf("/") + 1);
Inet4Address ia = (Inet4Address) InetAddress.getByName(ipAddr);
matchers[i][e] = new Inet4AddressMatcher(ia, Integer.valueOf(prefix));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": netmask in '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid integer");
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": address '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address");
}
} else {
// IP match
try {
Inet4Address ia = (Inet4Address) InetAddress.getByName(entry);
matchers[i][e] = new Inet4AddressMatcher(ia);
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": address '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address");
}
}
}
} else {
// allow empty datacenters
Logging.logMessage(Logging.LEVEL_WARN, this, "datacenter '" + dcs[i] + "' has no entries!");
}
}
}
| private void readConfig(Properties p) {
String tmp = p.getProperty("datacenters");
if (tmp == null) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": a list of datacenters must be specified in the configuration");
}
final String[] dcs = tmp.split(",");
if (dcs.length == 0) {
Logging.logMessage(Logging.LEVEL_WARN, this, "no datacenters specified");
return;
}
for (int i = 0; i < dcs.length; i++) {
if (!dcs[i].matches("[a-zA-Z0-9_]+")) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": datacenter name '" + dcs[i] + "' is invalid");
}
}
distMap = new int[dcs.length][dcs.length];
matchers = new Inet4AddressMatcher[dcs.length][];
for (int i = 0; i < dcs.length; i++) {
for (int j = i + 1; j < dcs.length; j++) {
String distStr = p.getProperty("distance." + dcs[i] + "-" + dcs[j]);
if (distStr == null) {
distStr = p.getProperty("distance." + dcs[j] + "-" + dcs[i]);
}
if (distStr == null) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": distance between datacenter '" + dcs[i] + "' and '" + dcs[j]
+ "' is not specified");
}
try {
distMap[i][j] = distMap[j][i] = Integer.valueOf(distStr);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName()
+ ": distance '" + distStr + "' between datacenter '" + dcs[i] + "' and '" + dcs[j]
+ "' is not a valid integer");
}
}
String dcMatch = p.getProperty(dcs[i] + ".addresses");
if (dcMatch != null) {
String entries[] = dcMatch.split(",");
matchers[i] = new Inet4AddressMatcher[entries.length];
for (int e = 0; e < entries.length; e++) {
final String entry = entries[e];
if (entry.contains("/")) {
// network match
try {
String ipAddr = entry.substring(0, entry.indexOf("/"));
String prefix = entry.substring(entry.indexOf("/") + 1);
Inet4Address ia = (Inet4Address) InetAddress.getByName(ipAddr);
matchers[i][e] = new Inet4AddressMatcher(ia, Integer.valueOf(prefix));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": netmask in '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid integer");
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": address '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address");
}
} else {
// IP match
try {
Inet4Address ia = (Inet4Address) InetAddress.getByName(entry);
matchers[i][e] = new Inet4AddressMatcher(ia);
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot initialize "
+ this.getClass().getSimpleName() + ": address '" + entry
+ "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address");
}
}
}
} else {
matchers[i] = new Inet4AddressMatcher[0];
// allow empty datacenters
Logging.logMessage(Logging.LEVEL_WARN, this, "datacenter '" + dcs[i] + "' has no entries!");
}
}
}
|
diff --git a/src/pl/synth/pinry/PinryContentProvider.java b/src/pl/synth/pinry/PinryContentProvider.java
index ea4cdf6..3e4d82f 100644
--- a/src/pl/synth/pinry/PinryContentProvider.java
+++ b/src/pl/synth/pinry/PinryContentProvider.java
@@ -1,180 +1,180 @@
package pl.synth.pinry;
import android.accounts.Account;
import android.content.*;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import java.util.HashMap;
public class PinryContentProvider extends ContentProvider {
private static final String TAG = "PinryContentProvider";
private static final String DATABASE_NAME = "pinry.db";
private static final int DATABASE_VERSION = 1;
private static final int PINS = 1;
private static final int PIN_ID = 2;
private static final UriMatcher uriMatcher;
private static HashMap<String, String> pinsProjectionMap;
private DatabaseHelper openHelper;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(Pinry.AUTHORITY, "pins", PINS);
uriMatcher.addURI(Pinry.AUTHORITY, "pins/#", PIN_ID);
pinsProjectionMap = new HashMap<String, String>();
pinsProjectionMap.put(Pinry.Pins._ID, Pinry.Pins._ID);
pinsProjectionMap.put(Pinry.Pins.COLUMN_NAME_DESCRIPTION, Pinry.Pins.COLUMN_NAME_DESCRIPTION);
pinsProjectionMap.put(Pinry.Pins.COLUMN_NAME_SOURCE_URL, Pinry.Pins.COLUMN_NAME_SOURCE_URL);
pinsProjectionMap.put(Pinry.Pins.COLUMN_NAME_PUBLISHED, Pinry.Pins.COLUMN_NAME_PUBLISHED);
pinsProjectionMap.put(Pinry.Pins.COLUMN_NAME_IMAGE_PATH, Pinry.Pins.COLUMN_NAME_IMAGE_PATH);
pinsProjectionMap.put(Pinry.Pins.COLUMN_NAME_IMAGE_URL, Pinry.Pins.COLUMN_NAME_IMAGE_URL);
pinsProjectionMap.put(Pinry.Pins.COLUMN_NAME_THUMBNAIL_PATH, Pinry.Pins.COLUMN_NAME_THUMBNAIL_PATH);
}
@Override
public boolean onCreate() {
openHelper = new DatabaseHelper(getContext());
return true; /* failures reported by thrown exceptions */
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Pinry.Pins.TABLE_NAME);
switch(uriMatcher.match(uri)) {
case PINS:
queryBuilder.setProjectionMap(pinsProjectionMap);
break;
case PIN_ID:
queryBuilder.setProjectionMap(pinsProjectionMap);
queryBuilder.appendWhere(
Pinry.Pins._ID +
"=" +
uri.getPathSegments().get(Pinry.Pins.PIN_ID_PATH_POSITION));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
String orderBy = Pinry.Pins.DEFAULT_SORT_ORDER;
SQLiteDatabase db = openHelper.getReadableDatabase();
Cursor c = queryBuilder.query(db, projection, selection, selectionArgs, null, null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case PINS:
return Pinry.Pins.CONTENT_TYPE;
case PIN_ID:
return Pinry.Pins.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues initial) {
if (uriMatcher.match(uri) != PINS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initial != null) {
values = new ContentValues(initial);
} else {
values = new ContentValues();
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_PUBLISHED)) {
values.put(Pinry.Pins.COLUMN_NAME_PUBLISHED, 0);
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_DESCRIPTION)) {
values.put(Pinry.Pins.COLUMN_NAME_DESCRIPTION, "");
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_SYNC_STATE)) {
values.put(Pinry.Pins.COLUMN_NAME_SYNC_STATE, Pinry.Pins.SyncState.WAITING);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
long rowId = db.insert(
Pinry.Pins.TABLE_NAME,
null,
values);
if (rowId > 0) {
Uri pinUri = ContentUris.withAppendedId(Pinry.Pins.CONTENT_ID_URI_BASE, rowId);
getContext().getContentResolver().notifyChange(pinUri, null);
- if (values.getAsString("synced") != Pinry.Pins.SyncState.SYNCED) {
+ if (values.getAsString(Pinry.Pins.COLUMN_NAME_SYNC_STATE) != Pinry.Pins.SyncState.SYNCED) {
ContentResolver.requestSync(null, Pinry.AUTHORITY, new Bundle());
}
return pinUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = openHelper.getWritableDatabase();
return db.delete(Pinry.Pins.TABLE_NAME, selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = openHelper.getWritableDatabase();
return db.update(Pinry.Pins.TABLE_NAME, values, selection, selectionArgs);
}
static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Pinry.Pins.TABLE_NAME + " ("
+ Pinry.Pins._ID + " INTEGER PRIMARY KEY,"
+ Pinry.Pins.COLUMN_NAME_SOURCE_URL + " TEXT,"
+ Pinry.Pins.COLUMN_NAME_PUBLISHED + " INTEGER,"
+ Pinry.Pins.COLUMN_NAME_DESCRIPTION + " TEXT,"
+ Pinry.Pins.COLUMN_NAME_IMAGE_PATH + " TEXT,"
+ Pinry.Pins.COLUMN_NAME_IMAGE_URL + " TEXT,"
+ Pinry.Pins.COLUMN_NAME_THUMBNAIL_PATH + " TEXT,"
+ Pinry.Pins.COLUMN_NAME_SYNC_STATE + " TEXT"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
| true | true | public Uri insert(Uri uri, ContentValues initial) {
if (uriMatcher.match(uri) != PINS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initial != null) {
values = new ContentValues(initial);
} else {
values = new ContentValues();
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_PUBLISHED)) {
values.put(Pinry.Pins.COLUMN_NAME_PUBLISHED, 0);
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_DESCRIPTION)) {
values.put(Pinry.Pins.COLUMN_NAME_DESCRIPTION, "");
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_SYNC_STATE)) {
values.put(Pinry.Pins.COLUMN_NAME_SYNC_STATE, Pinry.Pins.SyncState.WAITING);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
long rowId = db.insert(
Pinry.Pins.TABLE_NAME,
null,
values);
if (rowId > 0) {
Uri pinUri = ContentUris.withAppendedId(Pinry.Pins.CONTENT_ID_URI_BASE, rowId);
getContext().getContentResolver().notifyChange(pinUri, null);
if (values.getAsString("synced") != Pinry.Pins.SyncState.SYNCED) {
ContentResolver.requestSync(null, Pinry.AUTHORITY, new Bundle());
}
return pinUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
| public Uri insert(Uri uri, ContentValues initial) {
if (uriMatcher.match(uri) != PINS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initial != null) {
values = new ContentValues(initial);
} else {
values = new ContentValues();
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_PUBLISHED)) {
values.put(Pinry.Pins.COLUMN_NAME_PUBLISHED, 0);
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_DESCRIPTION)) {
values.put(Pinry.Pins.COLUMN_NAME_DESCRIPTION, "");
}
if (!values.containsKey(Pinry.Pins.COLUMN_NAME_SYNC_STATE)) {
values.put(Pinry.Pins.COLUMN_NAME_SYNC_STATE, Pinry.Pins.SyncState.WAITING);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
long rowId = db.insert(
Pinry.Pins.TABLE_NAME,
null,
values);
if (rowId > 0) {
Uri pinUri = ContentUris.withAppendedId(Pinry.Pins.CONTENT_ID_URI_BASE, rowId);
getContext().getContentResolver().notifyChange(pinUri, null);
if (values.getAsString(Pinry.Pins.COLUMN_NAME_SYNC_STATE) != Pinry.Pins.SyncState.SYNCED) {
ContentResolver.requestSync(null, Pinry.AUTHORITY, new Bundle());
}
return pinUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
|
diff --git a/src/gtna/plot/Plotting.java b/src/gtna/plot/Plotting.java
index b9816579..b6297d17 100644
--- a/src/gtna/plot/Plotting.java
+++ b/src/gtna/plot/Plotting.java
@@ -1,325 +1,326 @@
/* ===========================================================
* GTNA : Graph-Theoretic Network Analyzer
* ===========================================================
*
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/
*
* GTNA 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.
*
* GTNA 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/>.
*
* ---------------------------------------
* Plotting.java
* ---------------------------------------
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Original Author: benni;
* Contributors: -;
*
* Changes since 2011-05-17
* ---------------------------------------
*
*/
package gtna.plot;
import gtna.data.Series;
import gtna.data.Single;
import gtna.data.SingleList;
import gtna.metrics.Metric;
import gtna.plot.Data.Type;
import gtna.plot.Gnuplot.Style;
import gtna.util.Config;
import gtna.util.Timer;
import gtna.util.parameter.DoubleParameter;
import gtna.util.parameter.IntParameter;
import gtna.util.parameter.Parameter;
import java.io.File;
import java.util.ArrayList;
/**
* @author benni
*
*/
public class Plotting {
public static boolean single(Series[][] s, Metric[] metrics, String folder,
Type type, Style style) {
Timer timer = new Timer("single (" + s.length + "|" + s[0].length
+ ") (" + type + "|" + style + ")");
double[][] x = new double[s.length][];
ArrayList<String> labels = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
- String diff = s[i][0].getNetwork()
- .getDiffParameter(s[i][1 % s[i].length].getNetwork())
- .getKey();
- if (diff == null) {
+ Parameter diffP = s[i][0].getNetwork().getDiffParameter(
+ s[i][1 % s[i].length].getNetwork());
+ if (diffP == null || diffP.getKey() == null) {
+ System.err.println("no diff param found");
return false;
}
String label = s[i][0].getNetwork().getDiffParameterName(
s[i][1 % s[i].length].getNetwork());
if (!labels.contains(label)) {
labels.add(label);
}
x[i] = new double[s[i].length];
for (int j = 0; j < s[i].length; j++) {
Parameter p = s[i][j].getNetwork().getDiffParameter(
s[i][(j + 1) % s[i].length].getNetwork());
if (p instanceof IntParameter) {
x[i][j] = ((IntParameter) p).getIntValue();
} else if (p instanceof DoubleParameter) {
x[i][j] = ((DoubleParameter) p).getDoubleValue();
} else {
+ System.err.println("diff param not of type int or long");
return false;
}
}
}
StringBuffer xLabel = new StringBuffer();
for (String l : labels) {
if (xLabel.length() == 0) {
xLabel.append(l);
} else {
xLabel.append(", " + l);
}
}
boolean success = Plotting.singleMetrics(s, metrics, folder, type,
style, x, xLabel.toString());
timer.end();
return success;
}
public static boolean singleBy(Series[][] s, Metric[] metrics,
String folder, Metric metricX, String keyX, Type type, Style style) {
Timer timer = new Timer("single (" + s.length + "|" + s[0].length
+ ") (" + type + "|" + style + ") by " + keyX);
double[][] x = new double[s.length][];
for (int i = 0; i < s.length; i++) {
x[i] = new double[s[i].length];
for (int j = 0; j < s[i].length; j++) {
Single single = s[i][j].getSingle(metricX, metricX.getKey()
+ "_" + keyX);
if (single == null) {
System.err.println("cannot find " + keyX + " for "
+ metricX.getFolderName() + " in "
+ s[i][j].getNetwork().getFolderName());
return false;
}
x[i][j] = single.getValue();
}
}
String xLabel = Config.get(metricX.getKey() + "_" + keyX
+ "_SINGLE_NAME");
boolean success = Plotting.singleMetrics(s, metrics, folder, type,
style, x, xLabel);
timer.end();
return success;
}
private static boolean singleMetrics(Series[][] s, Metric[] metrics,
String folder, Type type, Style style, double[][] x, String xLabel) {
if (x == null) {
return false;
}
boolean subfolders = Config.getBoolean("PLOT_SUBFOLDERS");
boolean success = true;
for (Metric m : metrics) {
for (String key : m.getSinglePlotKeys()) {
String pre = Config.get("MAIN_PLOT_FOLDER") + folder
+ (subfolders ? m.getFolder() : m.getFolderName());
(new File(pre)).mkdirs();
success &= Plotting.singleMetric(s, m, key, pre, type, style,
x, xLabel);
}
}
return success;
}
private static boolean singleMetric(Series[][] s, Metric m, String plotKey,
String pre, Type type, Style style, double[][] x, String xLabel) {
String[] dataKeys = Config.keys(plotKey + "_PLOT_DATA");
Data[] data = new Data[s.length * dataKeys.length];
int index = 0;
for (int i = 0; i < s.length; i++) {
for (String key : dataKeys) {
double[][] d = new double[s[i].length][];
for (int j = 0; j < s[i].length; j++) {
SingleList sl = SingleList.read(m,
s[i][j].getSinglesFilename(m));
Single single = sl.get(key);
d[j] = new double[single.getData().length + 1];
d[j][0] = x[i][j];
for (int k = 0; k < single.getData().length; k++) {
d[j][k + 1] = single.getData()[k];
}
}
String filename = Gnuplot.writeTempData(m, plotKey, index, d);
if (filename == null) {
return false;
}
String title = s[i][0].getNetwork().getDiffDescriptionShort(
s[i][1 % s[i].length].getNetwork());
data[index++] = Data.get(filename, style, title, type);
}
}
String terminal = Config.get("GNUPLOT_TERMINAL");
String output = pre + Config.get(plotKey + "_PLOT_FILENAME")
+ Config.get("PLOT_EXTENSION");
Plot plot = new Plot(data, terminal, output);
plot.setTitle(Config.get(plotKey + "_PLOT_TITLE"));
plot.setxLabel(xLabel);
plot.setyLabel(Config.get(plotKey + "_PLOT_Y"));
return Gnuplot.plot(plot, m, plotKey);
}
public static boolean multi(Series[] s, Metric[] metrics, String folder,
Type type, Style style) {
Timer timer = new Timer("multi (" + s.length + ") " + type + " / "
+ style);
boolean subfolders = Config.getBoolean("PLOT_SUBFOLDERS");
boolean success = true;
for (Metric m : metrics) {
for (String key : m.getDataPlotKeys()) {
String pre = Config.get("MAIN_PLOT_FOLDER") + folder
+ (subfolders ? m.getFolder() : m.getFolderName());
(new File(pre)).mkdirs();
success &= Plotting.multi(s, m, key, pre, type, style);
}
}
timer.end();
return success;
}
private static boolean multi(Series[] s, Metric m, String plotKey,
String pre, Type type, Style style) {
String[] dataKeys = Config.keys(plotKey + "_PLOT_DATA");
Data[] data = new Data[s.length * dataKeys.length];
int index = 0;
for (Series S : s) {
for (String key : dataKeys) {
data[index++] = Data.get(S.getMultiFilename(m, key), style, S
.getNetwork().getDescriptionShort(), type);
}
}
String terminal = Config.get("GNUPLOT_TERMINAL");
String output = pre + Config.get(plotKey + "_PLOT_FILENAME")
+ Config.get("PLOT_EXTENSION");
Plot plot = new Plot(data, terminal, output);
plot.setTitle(Config.get(plotKey + "_PLOT_TITLE"));
plot.setxLabel(Config.get(plotKey + "_PLOT_X"));
plot.setyLabel(Config.get(plotKey + "_PLOT_Y"));
if (Config.getBoolean(dataKeys[0] + "_DATA_IS_CDF")) {
plot.setKey(Config.get("GNUPLOT_KEY_CDF"));
} else {
plot.setKey(Config.get("GNUPLOT_KEY"));
}
return Gnuplot.plot(plot, m, plotKey);
}
public static boolean single(Series s, Metric[] metrics, String folder) {
return Plotting.single(s, metrics, folder, Type.average,
Style.linespoint);
}
public static boolean single(Series[] s, Metric[] metrics, String folder) {
return Plotting.single(s, metrics, folder, Type.average,
Style.linespoint);
}
public static boolean single(Series[][] s, Metric[] metrics, String folder) {
return Plotting.single(s, metrics, folder, Type.average,
Style.linespoint);
}
public static boolean single(Series s, Metric[] metrics, String folder,
Type type, Style style) {
return Plotting
.single(new Series[] { s }, metrics, folder, type, style);
}
public static boolean single(Series[] s, Metric[] metrics, String folder,
Type type, Style style) {
return Plotting.single(new Series[][] { s }, metrics, folder, type,
style);
}
public static boolean singleBy(Series s, Metric[] metrics, String folder,
Metric metricX, String keyX) {
return Plotting.singleBy(s, metrics, folder, metricX, keyX,
Type.average, Style.linespoint);
}
public static boolean singleBy(Series[] s, Metric[] metrics, String folder,
Metric metricX, String keyX) {
return Plotting.singleBy(s, metrics, folder, metricX, keyX,
Type.average, Style.linespoint);
}
public static boolean singleBy(Series[][] s, Metric[] metrics,
String folder, Metric metricX, String keyX) {
return Plotting.singleBy(s, metrics, folder, metricX, keyX,
Type.average, Style.linespoint);
}
public static boolean singleBy(Series s, Metric[] metrics, String folder,
Metric metricX, String keyX, Type type, Style style) {
return Plotting.singleBy(new Series[] { s }, metrics, folder, metricX,
keyX, type, style);
}
public static boolean singleBy(Series[] s, Metric[] metrics, String folder,
Metric metricX, String keyX, Type type, Style style) {
return Plotting.singleBy(new Series[][] { s }, metrics, folder,
metricX, keyX, type, style);
}
public static boolean multi(Series s, Metric[] metrics, String folder) {
return Plotting.multi(s, metrics, folder, Type.average,
Style.linespoint);
}
public static boolean multi(Series[] s, Metric[] metrics, String folder) {
return Plotting.multi(s, metrics, folder, Type.average,
Style.linespoint);
}
public static boolean multi(Series[][] s, Metric[] metrics, String folder) {
return Plotting.multi(s, metrics, folder, Type.average,
Style.linespoint);
}
public static boolean multi(Series s, Metric[] metrics, String folder,
Type type, Style style) {
return Plotting.multi(new Series[] { s }, metrics, folder, type, style);
}
public static boolean multi(Series[][] s, Metric[] metrics, String folder,
Type type, Style style) {
int index = 0;
for (Series[] s1 : s) {
index += s1.length;
}
Series[] S = new Series[index];
index = 0;
for (Series[] s1 : s) {
for (Series s2 : s1) {
S[index++] = s2;
}
}
return Plotting.multi(S, metrics, folder, type, style);
}
}
| false | true | public static boolean single(Series[][] s, Metric[] metrics, String folder,
Type type, Style style) {
Timer timer = new Timer("single (" + s.length + "|" + s[0].length
+ ") (" + type + "|" + style + ")");
double[][] x = new double[s.length][];
ArrayList<String> labels = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
String diff = s[i][0].getNetwork()
.getDiffParameter(s[i][1 % s[i].length].getNetwork())
.getKey();
if (diff == null) {
return false;
}
String label = s[i][0].getNetwork().getDiffParameterName(
s[i][1 % s[i].length].getNetwork());
if (!labels.contains(label)) {
labels.add(label);
}
x[i] = new double[s[i].length];
for (int j = 0; j < s[i].length; j++) {
Parameter p = s[i][j].getNetwork().getDiffParameter(
s[i][(j + 1) % s[i].length].getNetwork());
if (p instanceof IntParameter) {
x[i][j] = ((IntParameter) p).getIntValue();
} else if (p instanceof DoubleParameter) {
x[i][j] = ((DoubleParameter) p).getDoubleValue();
} else {
return false;
}
}
}
StringBuffer xLabel = new StringBuffer();
for (String l : labels) {
if (xLabel.length() == 0) {
xLabel.append(l);
} else {
xLabel.append(", " + l);
}
}
boolean success = Plotting.singleMetrics(s, metrics, folder, type,
style, x, xLabel.toString());
timer.end();
return success;
}
| public static boolean single(Series[][] s, Metric[] metrics, String folder,
Type type, Style style) {
Timer timer = new Timer("single (" + s.length + "|" + s[0].length
+ ") (" + type + "|" + style + ")");
double[][] x = new double[s.length][];
ArrayList<String> labels = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
Parameter diffP = s[i][0].getNetwork().getDiffParameter(
s[i][1 % s[i].length].getNetwork());
if (diffP == null || diffP.getKey() == null) {
System.err.println("no diff param found");
return false;
}
String label = s[i][0].getNetwork().getDiffParameterName(
s[i][1 % s[i].length].getNetwork());
if (!labels.contains(label)) {
labels.add(label);
}
x[i] = new double[s[i].length];
for (int j = 0; j < s[i].length; j++) {
Parameter p = s[i][j].getNetwork().getDiffParameter(
s[i][(j + 1) % s[i].length].getNetwork());
if (p instanceof IntParameter) {
x[i][j] = ((IntParameter) p).getIntValue();
} else if (p instanceof DoubleParameter) {
x[i][j] = ((DoubleParameter) p).getDoubleValue();
} else {
System.err.println("diff param not of type int or long");
return false;
}
}
}
StringBuffer xLabel = new StringBuffer();
for (String l : labels) {
if (xLabel.length() == 0) {
xLabel.append(l);
} else {
xLabel.append(", " + l);
}
}
boolean success = Plotting.singleMetrics(s, metrics, folder, type,
style, x, xLabel.toString());
timer.end();
return success;
}
|
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/pages/profile/settings/GroupProfileSettingsTabContent.java b/web/src/main/java/org/eurekastreams/web/client/ui/pages/profile/settings/GroupProfileSettingsTabContent.java
index 9768aeedb..0c5f9cd91 100644
--- a/web/src/main/java/org/eurekastreams/web/client/ui/pages/profile/settings/GroupProfileSettingsTabContent.java
+++ b/web/src/main/java/org/eurekastreams/web/client/ui/pages/profile/settings/GroupProfileSettingsTabContent.java
@@ -1,349 +1,348 @@
/*
* Copyright (c) 2010-2011 Lockheed Martin Corporation
*
* 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.eurekastreams.web.client.ui.pages.profile.settings;
import java.io.Serializable;
import org.eurekastreams.server.domain.DomainFormatUtility;
import org.eurekastreams.server.domain.DomainGroup;
import org.eurekastreams.server.domain.EntityType;
import org.eurekastreams.server.domain.Page;
import org.eurekastreams.server.search.modelview.DomainGroupModelView;
import org.eurekastreams.web.client.events.EventBus;
import org.eurekastreams.web.client.events.Observer;
import org.eurekastreams.web.client.events.SetBannerEvent;
import org.eurekastreams.web.client.events.ShowNotificationEvent;
import org.eurekastreams.web.client.events.UpdateHistoryEvent;
import org.eurekastreams.web.client.events.data.AuthorizeUpdateGroupResponseEvent;
import org.eurekastreams.web.client.events.data.GotGroupModelViewInformationResponseEvent;
import org.eurekastreams.web.client.events.data.UpdatedGroupResponseEvent;
import org.eurekastreams.web.client.history.CreateUrlRequest;
import org.eurekastreams.web.client.jsni.WidgetJSNIFacadeImpl;
import org.eurekastreams.web.client.model.GroupModel;
import org.eurekastreams.web.client.ui.Session;
import org.eurekastreams.web.client.ui.common.autocomplete.AutoCompleteItemDropDownFormElement;
import org.eurekastreams.web.client.ui.common.form.FormBuilder;
import org.eurekastreams.web.client.ui.common.form.FormBuilder.Method;
import org.eurekastreams.web.client.ui.common.form.elements.BasicCheckBoxFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.BasicRadioButtonGroupFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.BasicTextAreaFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.BasicTextBoxFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.PersonModelViewLookupFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.ValueOnlyFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.avatar.AvatarUploadFormElement;
import org.eurekastreams.web.client.ui.common.form.elements.avatar.strategies.AvatarUploadStrategy;
import org.eurekastreams.web.client.ui.common.notifier.Notification;
import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
/**
* The basic group settings.
*
*/
public class GroupProfileSettingsTabContent extends FlowPanel
{
/** The width of the text editor. */
private static final int TEXT_EDITOR_WIDTH = 430;
/**
* Maximum name length.
*/
private static final int MAX_NAME = 50;
/**
* Maximum keywords length.
*/
private static final int MAX_KEYWORDS = 2000;
/**
* The panel.
*/
private final FlowPanel panel = new FlowPanel();
/**
* The delete-group button.
*/
private final Anchor deleteButton = new Anchor("");
/**
* The processing spinner.
*/
private final Label processingSpinny = new Label("Processing...");
/**
* Default constructor.
*
* @param groupName
* the group name.
*/
public GroupProfileSettingsTabContent(final String groupName)
{
this.add(panel);
EventBus.getInstance().addObserver(GotGroupModelViewInformationResponseEvent.class,
new Observer<GotGroupModelViewInformationResponseEvent>()
{
public void update(final GotGroupModelViewInformationResponseEvent event)
{
setEntity(event.getResponse());
}
});
Session.getInstance().getEventBus().addObserver(AuthorizeUpdateGroupResponseEvent.class,
new Observer<AuthorizeUpdateGroupResponseEvent>()
{
public void update(final AuthorizeUpdateGroupResponseEvent event)
{
if (event.getResponse())
{
GroupModel.getInstance().fetch(groupName, true);
}
}
});
GroupModel.getInstance().authorize(groupName, true);
}
/**
* Setter.
*
* @param entity
* the group whose settings will be changed
*/
public void setEntity(final DomainGroupModelView entity)
{
// Set the banner.
Session.getInstance().getEventBus().notifyObservers(new SetBannerEvent(entity));
final FormBuilder form = new FormBuilder("", GroupModel.getInstance(), Method.UPDATE);
EventBus.getInstance().addObserver(UpdatedGroupResponseEvent.class, new Observer<UpdatedGroupResponseEvent>()
{
public void update(final UpdatedGroupResponseEvent arg1)
{
Session.getInstance().getEventBus().notifyObservers(
new UpdateHistoryEvent(new CreateUrlRequest(Page.GROUPS, arg1.getResponse().getShortName())));
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification("Your group has been successfully saved")));
}
});
form.addFormElement(new ValueOnlyFormElement(DomainGroupModelView.ID_KEY, Long.toString(entity.getId())));
form.addFormElement(new ValueOnlyFormElement(DomainGroupModelView.SHORT_NAME_KEY, entity.getShortName()));
AvatarUploadFormElement avatarFormEl = new AvatarUploadFormElement("Avatar",
- "Select a JPG, PNG or GIF image from your computer. The maxium file size is 4MB"
- + " and will be cropped to 990 x 100 pixels high.",
+ "Select a JPG, PNG or GIF image from your computer. The maxium file size is 4MB",
"/eurekastreams/groupavatarupload?groupName=" + entity.getShortName(), Session.getInstance()
.getActionProcessor(), new AvatarUploadStrategy<DomainGroupModelView>(entity,
"resizeGroupAvatar", EntityType.GROUP));
form.addWidget(avatarFormEl);
form.addFormDivider();
form.addFormElement(new BasicTextBoxFormElement(MAX_NAME, false, "Group Name", DomainGroupModelView.NAME_KEY,
entity.getName(), "", true));
form.addFormDivider();
form.addFormElement(new BasicTextAreaFormElement(DomainGroup.MAX_DESCRIPTION_LENGTH, "Description",
DomainGroupModelView.DESCRIPTION_KEY, entity.getDescription(),
"Enter a few sentences that describe the purpose of your group's stream. "
+ "This description will appear beneath your avatar "
+ "and in the profile search results pages.", false));
form.addFormDivider();
AutoCompleteItemDropDownFormElement keywords = new AutoCompleteItemDropDownFormElement("Keywords",
DomainGroupModelView.KEYWORDS_KEY, DomainFormatUtility.buildCapabilitiesStringFromStrings(entity
.getCapabilities()),
"Add keywords that describe your group and the topics your members will be talking about. Separate "
+ "keywords with a comma. Including keywords helps others find your group when searching "
+ "profiles.", false, "/resources/autocomplete/capability/", "itemNames", ",");
keywords.setMaxLength(MAX_KEYWORDS);
form.addFormElement(keywords);
form.addFormDivider();
form.addFormElement(new BasicTextBoxFormElement("Website URL", "url", entity.getUrl(),
"If your group has a website, you can enter the URL above", false));
form.addFormDivider();
String coordinstructions = "The group coordinators will be responsible for managing the organization profile, "
+ "and moderating the group's activity stream";
form.addFormElement(new PersonModelViewLookupFormElement("Group Coordinators", "Add Coordinator",
coordinstructions, DomainGroupModelView.COORDINATORS_KEY, entity.getCoordinators(), true));
form.addFormDivider();
final Label currentPrivacySettingLabel = new Label();
currentPrivacySettingLabel.setText("Privacy Settings");
currentPrivacySettingLabel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formLabel());
final FlowPanel currentPrivacySettingDescription = new FlowPanel();
final Label currentPrivacySettingDescriptionTitle = new Label();
currentPrivacySettingDescriptionTitle.setText(entity.isPublic() ? "Public" : "Private");
currentPrivacySettingDescriptionTitle.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formStaticValue());
final Label currentPrivacySettingDescriptionInfo = new Label();
if (entity.isPublic())
{
currentPrivacySettingDescriptionInfo.setText("Public groups are visible to all users and accessible "
+ "through a profile search.");
}
else
{
currentPrivacySettingDescriptionInfo.setText("Access to private groups is restricted to employees"
+ " approved by the group's coordinators. Group coordinators can view a list of pending "
+ "requests by going to the admin tab on the group's profile.");
}
currentPrivacySettingDescriptionInfo.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formInstructions());
currentPrivacySettingDescription.add(currentPrivacySettingDescriptionTitle);
currentPrivacySettingDescription.add(currentPrivacySettingDescriptionInfo);
currentPrivacySettingDescription.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettingsValue());
final FlowPanel currentPrivacySettingPanel = new FlowPanel();
currentPrivacySettingPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formElement());
currentPrivacySettingPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettings());
currentPrivacySettingPanel.add(currentPrivacySettingLabel);
currentPrivacySettingPanel.add(currentPrivacySettingDescription);
form.addWidget(currentPrivacySettingPanel);
if (!entity.isPublic())
{
final HTML privateNote = new HTML("<span class=\"form-static-value\">Please Note:</span> "
+ "This group's name and description will be visible whenever employees browse or"
+ " search profiles.");
privateNote.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettingsNote());
privateNote.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formInstructions());
currentPrivacySettingPanel.add(privateNote);
}
form.addFormDivider();
// TODO: evidently this is supposed to go away
BasicCheckBoxFormElement blockWallPost = new BasicCheckBoxFormElement("Stream Moderation",
DomainGroupModelView.STREAM_POSTABLE_KEY, "Allow others to post to your group's stream", false, entity
.isStreamPostable());
BasicCheckBoxFormElement blockCommentPost = new BasicCheckBoxFormElement(null,
DomainGroupModelView.STREAM_COMMENTABLE_KEY,
"Allow others to comment on activity in your group's stream", false, entity.isCommentable());
blockWallPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamModeration());
blockCommentPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamModeration());
blockCommentPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().commentModeration());
form.addFormElement(blockWallPost);
form.addFormElement(blockCommentPost);
form.addFormDivider();
// ---- Action buttons ----
deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formDeleteGroupButton());
deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formButton());
deleteButton.addClickHandler(new ClickHandler()
{
public void onClick(final ClickEvent event)
{
if (new WidgetJSNIFacadeImpl().confirm("Are sure that you want to delete this group? "
+ "Deleting the group will remove the profile from the system along with "
+ "all of the activity that has been posted to its stream."))
{
form.turnOffChangeCheck();
processingSpinny.setVisible(true);
deleteButton.setVisible(false);
// TODO - might should put this in GroupModel (and mark it as Deletable) but there's no
// custom onFailure ability there yet.
Session.getInstance().getActionProcessor().makeRequest("deleteGroupAction", entity.getId(),
new AsyncCallback<Boolean>()
{
public void onSuccess(final Boolean result)
{
// adds notification to top of page
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification("The group '"
+ entity.getName() + "' has been deleted")));
// navigates away from settings page to the parent org profile page
Session.getInstance().getEventBus().notifyObservers(
new UpdateHistoryEvent(new CreateUrlRequest(Page.PEOPLE, Session
.getInstance().getCurrentPerson().getAccountId())));
}
public void onFailure(final Throwable caught)
{
// adds notification to top of page
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification(
"An error has occured and the group '" + entity.getName()
+ "' was not deleted")));
}
});
}
}
});
form.addWidgetToFormContainer(deleteButton);
processingSpinny.setVisible(false);
processingSpinny.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formSubmitSpinny());
form.addWidgetToFormContainer(processingSpinny);
form.setOnCancelHistoryToken(Session.getInstance().generateUrl(
new CreateUrlRequest(Page.GROUPS, entity.getShortName())));
panel.add(form);
}
/**
* innerClass for the radioButtonGroup.
*/
public class GroupPrivacySettings extends BasicRadioButtonGroupFormElement
{
/**
* @param labelVal
* label for group.
* @param inKey
* key for group.
* @param groupName
* name of group.
* @param inInstructions
* instructions for group.
*/
public GroupPrivacySettings(final String labelVal, final String inKey, final String groupName,
final String inInstructions)
{
super(labelVal, inKey, groupName, inInstructions);
}
/**
* @return value of group.
*/
@Override
public Serializable getValue()
{
return Boolean.parseBoolean((String) super.getValue());
}
}
}
| true | true | public void setEntity(final DomainGroupModelView entity)
{
// Set the banner.
Session.getInstance().getEventBus().notifyObservers(new SetBannerEvent(entity));
final FormBuilder form = new FormBuilder("", GroupModel.getInstance(), Method.UPDATE);
EventBus.getInstance().addObserver(UpdatedGroupResponseEvent.class, new Observer<UpdatedGroupResponseEvent>()
{
public void update(final UpdatedGroupResponseEvent arg1)
{
Session.getInstance().getEventBus().notifyObservers(
new UpdateHistoryEvent(new CreateUrlRequest(Page.GROUPS, arg1.getResponse().getShortName())));
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification("Your group has been successfully saved")));
}
});
form.addFormElement(new ValueOnlyFormElement(DomainGroupModelView.ID_KEY, Long.toString(entity.getId())));
form.addFormElement(new ValueOnlyFormElement(DomainGroupModelView.SHORT_NAME_KEY, entity.getShortName()));
AvatarUploadFormElement avatarFormEl = new AvatarUploadFormElement("Avatar",
"Select a JPG, PNG or GIF image from your computer. The maxium file size is 4MB"
+ " and will be cropped to 990 x 100 pixels high.",
"/eurekastreams/groupavatarupload?groupName=" + entity.getShortName(), Session.getInstance()
.getActionProcessor(), new AvatarUploadStrategy<DomainGroupModelView>(entity,
"resizeGroupAvatar", EntityType.GROUP));
form.addWidget(avatarFormEl);
form.addFormDivider();
form.addFormElement(new BasicTextBoxFormElement(MAX_NAME, false, "Group Name", DomainGroupModelView.NAME_KEY,
entity.getName(), "", true));
form.addFormDivider();
form.addFormElement(new BasicTextAreaFormElement(DomainGroup.MAX_DESCRIPTION_LENGTH, "Description",
DomainGroupModelView.DESCRIPTION_KEY, entity.getDescription(),
"Enter a few sentences that describe the purpose of your group's stream. "
+ "This description will appear beneath your avatar "
+ "and in the profile search results pages.", false));
form.addFormDivider();
AutoCompleteItemDropDownFormElement keywords = new AutoCompleteItemDropDownFormElement("Keywords",
DomainGroupModelView.KEYWORDS_KEY, DomainFormatUtility.buildCapabilitiesStringFromStrings(entity
.getCapabilities()),
"Add keywords that describe your group and the topics your members will be talking about. Separate "
+ "keywords with a comma. Including keywords helps others find your group when searching "
+ "profiles.", false, "/resources/autocomplete/capability/", "itemNames", ",");
keywords.setMaxLength(MAX_KEYWORDS);
form.addFormElement(keywords);
form.addFormDivider();
form.addFormElement(new BasicTextBoxFormElement("Website URL", "url", entity.getUrl(),
"If your group has a website, you can enter the URL above", false));
form.addFormDivider();
String coordinstructions = "The group coordinators will be responsible for managing the organization profile, "
+ "and moderating the group's activity stream";
form.addFormElement(new PersonModelViewLookupFormElement("Group Coordinators", "Add Coordinator",
coordinstructions, DomainGroupModelView.COORDINATORS_KEY, entity.getCoordinators(), true));
form.addFormDivider();
final Label currentPrivacySettingLabel = new Label();
currentPrivacySettingLabel.setText("Privacy Settings");
currentPrivacySettingLabel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formLabel());
final FlowPanel currentPrivacySettingDescription = new FlowPanel();
final Label currentPrivacySettingDescriptionTitle = new Label();
currentPrivacySettingDescriptionTitle.setText(entity.isPublic() ? "Public" : "Private");
currentPrivacySettingDescriptionTitle.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formStaticValue());
final Label currentPrivacySettingDescriptionInfo = new Label();
if (entity.isPublic())
{
currentPrivacySettingDescriptionInfo.setText("Public groups are visible to all users and accessible "
+ "through a profile search.");
}
else
{
currentPrivacySettingDescriptionInfo.setText("Access to private groups is restricted to employees"
+ " approved by the group's coordinators. Group coordinators can view a list of pending "
+ "requests by going to the admin tab on the group's profile.");
}
currentPrivacySettingDescriptionInfo.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formInstructions());
currentPrivacySettingDescription.add(currentPrivacySettingDescriptionTitle);
currentPrivacySettingDescription.add(currentPrivacySettingDescriptionInfo);
currentPrivacySettingDescription.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettingsValue());
final FlowPanel currentPrivacySettingPanel = new FlowPanel();
currentPrivacySettingPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formElement());
currentPrivacySettingPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettings());
currentPrivacySettingPanel.add(currentPrivacySettingLabel);
currentPrivacySettingPanel.add(currentPrivacySettingDescription);
form.addWidget(currentPrivacySettingPanel);
if (!entity.isPublic())
{
final HTML privateNote = new HTML("<span class=\"form-static-value\">Please Note:</span> "
+ "This group's name and description will be visible whenever employees browse or"
+ " search profiles.");
privateNote.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettingsNote());
privateNote.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formInstructions());
currentPrivacySettingPanel.add(privateNote);
}
form.addFormDivider();
// TODO: evidently this is supposed to go away
BasicCheckBoxFormElement blockWallPost = new BasicCheckBoxFormElement("Stream Moderation",
DomainGroupModelView.STREAM_POSTABLE_KEY, "Allow others to post to your group's stream", false, entity
.isStreamPostable());
BasicCheckBoxFormElement blockCommentPost = new BasicCheckBoxFormElement(null,
DomainGroupModelView.STREAM_COMMENTABLE_KEY,
"Allow others to comment on activity in your group's stream", false, entity.isCommentable());
blockWallPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamModeration());
blockCommentPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamModeration());
blockCommentPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().commentModeration());
form.addFormElement(blockWallPost);
form.addFormElement(blockCommentPost);
form.addFormDivider();
// ---- Action buttons ----
deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formDeleteGroupButton());
deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formButton());
deleteButton.addClickHandler(new ClickHandler()
{
public void onClick(final ClickEvent event)
{
if (new WidgetJSNIFacadeImpl().confirm("Are sure that you want to delete this group? "
+ "Deleting the group will remove the profile from the system along with "
+ "all of the activity that has been posted to its stream."))
{
form.turnOffChangeCheck();
processingSpinny.setVisible(true);
deleteButton.setVisible(false);
// TODO - might should put this in GroupModel (and mark it as Deletable) but there's no
// custom onFailure ability there yet.
Session.getInstance().getActionProcessor().makeRequest("deleteGroupAction", entity.getId(),
new AsyncCallback<Boolean>()
{
public void onSuccess(final Boolean result)
{
// adds notification to top of page
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification("The group '"
+ entity.getName() + "' has been deleted")));
// navigates away from settings page to the parent org profile page
Session.getInstance().getEventBus().notifyObservers(
new UpdateHistoryEvent(new CreateUrlRequest(Page.PEOPLE, Session
.getInstance().getCurrentPerson().getAccountId())));
}
public void onFailure(final Throwable caught)
{
// adds notification to top of page
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification(
"An error has occured and the group '" + entity.getName()
+ "' was not deleted")));
}
});
}
}
});
form.addWidgetToFormContainer(deleteButton);
processingSpinny.setVisible(false);
processingSpinny.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formSubmitSpinny());
form.addWidgetToFormContainer(processingSpinny);
form.setOnCancelHistoryToken(Session.getInstance().generateUrl(
new CreateUrlRequest(Page.GROUPS, entity.getShortName())));
panel.add(form);
}
| public void setEntity(final DomainGroupModelView entity)
{
// Set the banner.
Session.getInstance().getEventBus().notifyObservers(new SetBannerEvent(entity));
final FormBuilder form = new FormBuilder("", GroupModel.getInstance(), Method.UPDATE);
EventBus.getInstance().addObserver(UpdatedGroupResponseEvent.class, new Observer<UpdatedGroupResponseEvent>()
{
public void update(final UpdatedGroupResponseEvent arg1)
{
Session.getInstance().getEventBus().notifyObservers(
new UpdateHistoryEvent(new CreateUrlRequest(Page.GROUPS, arg1.getResponse().getShortName())));
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification("Your group has been successfully saved")));
}
});
form.addFormElement(new ValueOnlyFormElement(DomainGroupModelView.ID_KEY, Long.toString(entity.getId())));
form.addFormElement(new ValueOnlyFormElement(DomainGroupModelView.SHORT_NAME_KEY, entity.getShortName()));
AvatarUploadFormElement avatarFormEl = new AvatarUploadFormElement("Avatar",
"Select a JPG, PNG or GIF image from your computer. The maxium file size is 4MB",
"/eurekastreams/groupavatarupload?groupName=" + entity.getShortName(), Session.getInstance()
.getActionProcessor(), new AvatarUploadStrategy<DomainGroupModelView>(entity,
"resizeGroupAvatar", EntityType.GROUP));
form.addWidget(avatarFormEl);
form.addFormDivider();
form.addFormElement(new BasicTextBoxFormElement(MAX_NAME, false, "Group Name", DomainGroupModelView.NAME_KEY,
entity.getName(), "", true));
form.addFormDivider();
form.addFormElement(new BasicTextAreaFormElement(DomainGroup.MAX_DESCRIPTION_LENGTH, "Description",
DomainGroupModelView.DESCRIPTION_KEY, entity.getDescription(),
"Enter a few sentences that describe the purpose of your group's stream. "
+ "This description will appear beneath your avatar "
+ "and in the profile search results pages.", false));
form.addFormDivider();
AutoCompleteItemDropDownFormElement keywords = new AutoCompleteItemDropDownFormElement("Keywords",
DomainGroupModelView.KEYWORDS_KEY, DomainFormatUtility.buildCapabilitiesStringFromStrings(entity
.getCapabilities()),
"Add keywords that describe your group and the topics your members will be talking about. Separate "
+ "keywords with a comma. Including keywords helps others find your group when searching "
+ "profiles.", false, "/resources/autocomplete/capability/", "itemNames", ",");
keywords.setMaxLength(MAX_KEYWORDS);
form.addFormElement(keywords);
form.addFormDivider();
form.addFormElement(new BasicTextBoxFormElement("Website URL", "url", entity.getUrl(),
"If your group has a website, you can enter the URL above", false));
form.addFormDivider();
String coordinstructions = "The group coordinators will be responsible for managing the organization profile, "
+ "and moderating the group's activity stream";
form.addFormElement(new PersonModelViewLookupFormElement("Group Coordinators", "Add Coordinator",
coordinstructions, DomainGroupModelView.COORDINATORS_KEY, entity.getCoordinators(), true));
form.addFormDivider();
final Label currentPrivacySettingLabel = new Label();
currentPrivacySettingLabel.setText("Privacy Settings");
currentPrivacySettingLabel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formLabel());
final FlowPanel currentPrivacySettingDescription = new FlowPanel();
final Label currentPrivacySettingDescriptionTitle = new Label();
currentPrivacySettingDescriptionTitle.setText(entity.isPublic() ? "Public" : "Private");
currentPrivacySettingDescriptionTitle.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formStaticValue());
final Label currentPrivacySettingDescriptionInfo = new Label();
if (entity.isPublic())
{
currentPrivacySettingDescriptionInfo.setText("Public groups are visible to all users and accessible "
+ "through a profile search.");
}
else
{
currentPrivacySettingDescriptionInfo.setText("Access to private groups is restricted to employees"
+ " approved by the group's coordinators. Group coordinators can view a list of pending "
+ "requests by going to the admin tab on the group's profile.");
}
currentPrivacySettingDescriptionInfo.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formInstructions());
currentPrivacySettingDescription.add(currentPrivacySettingDescriptionTitle);
currentPrivacySettingDescription.add(currentPrivacySettingDescriptionInfo);
currentPrivacySettingDescription.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettingsValue());
final FlowPanel currentPrivacySettingPanel = new FlowPanel();
currentPrivacySettingPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formElement());
currentPrivacySettingPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettings());
currentPrivacySettingPanel.add(currentPrivacySettingLabel);
currentPrivacySettingPanel.add(currentPrivacySettingDescription);
form.addWidget(currentPrivacySettingPanel);
if (!entity.isPublic())
{
final HTML privateNote = new HTML("<span class=\"form-static-value\">Please Note:</span> "
+ "This group's name and description will be visible whenever employees browse or"
+ " search profiles.");
privateNote.addStyleName(StaticResourceBundle.INSTANCE.coreCss().privacySettingsNote());
privateNote.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formInstructions());
currentPrivacySettingPanel.add(privateNote);
}
form.addFormDivider();
// TODO: evidently this is supposed to go away
BasicCheckBoxFormElement blockWallPost = new BasicCheckBoxFormElement("Stream Moderation",
DomainGroupModelView.STREAM_POSTABLE_KEY, "Allow others to post to your group's stream", false, entity
.isStreamPostable());
BasicCheckBoxFormElement blockCommentPost = new BasicCheckBoxFormElement(null,
DomainGroupModelView.STREAM_COMMENTABLE_KEY,
"Allow others to comment on activity in your group's stream", false, entity.isCommentable());
blockWallPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamModeration());
blockCommentPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamModeration());
blockCommentPost.addStyleName(StaticResourceBundle.INSTANCE.coreCss().commentModeration());
form.addFormElement(blockWallPost);
form.addFormElement(blockCommentPost);
form.addFormDivider();
// ---- Action buttons ----
deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formDeleteGroupButton());
deleteButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formButton());
deleteButton.addClickHandler(new ClickHandler()
{
public void onClick(final ClickEvent event)
{
if (new WidgetJSNIFacadeImpl().confirm("Are sure that you want to delete this group? "
+ "Deleting the group will remove the profile from the system along with "
+ "all of the activity that has been posted to its stream."))
{
form.turnOffChangeCheck();
processingSpinny.setVisible(true);
deleteButton.setVisible(false);
// TODO - might should put this in GroupModel (and mark it as Deletable) but there's no
// custom onFailure ability there yet.
Session.getInstance().getActionProcessor().makeRequest("deleteGroupAction", entity.getId(),
new AsyncCallback<Boolean>()
{
public void onSuccess(final Boolean result)
{
// adds notification to top of page
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification("The group '"
+ entity.getName() + "' has been deleted")));
// navigates away from settings page to the parent org profile page
Session.getInstance().getEventBus().notifyObservers(
new UpdateHistoryEvent(new CreateUrlRequest(Page.PEOPLE, Session
.getInstance().getCurrentPerson().getAccountId())));
}
public void onFailure(final Throwable caught)
{
// adds notification to top of page
Session.getInstance().getEventBus().notifyObservers(
new ShowNotificationEvent(new Notification(
"An error has occured and the group '" + entity.getName()
+ "' was not deleted")));
}
});
}
}
});
form.addWidgetToFormContainer(deleteButton);
processingSpinny.setVisible(false);
processingSpinny.addStyleName(StaticResourceBundle.INSTANCE.coreCss().formSubmitSpinny());
form.addWidgetToFormContainer(processingSpinny);
form.setOnCancelHistoryToken(Session.getInstance().generateUrl(
new CreateUrlRequest(Page.GROUPS, entity.getShortName())));
panel.add(form);
}
|
diff --git a/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java b/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java
index 1a2c014b..d7d448c0 100644
--- a/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java
+++ b/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java
@@ -1,47 +1,49 @@
package uk.ac.cam.db538.dexter.dex.code;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.val;
import uk.ac.cam.db538.dexter.dex.DexAssemblingCache;
import uk.ac.cam.db538.dexter.dex.code.insn.DexInstruction;
public class DexCode_AssemblingState {
@Getter private DexCode code;
@Getter private DexAssemblingCache cache;
private Map<DexRegister, Integer> registerAllocation;
private Map<DexCodeElement, Long> elementOffsets;
public DexCode_AssemblingState(DexCode code, DexAssemblingCache cache, Map<DexRegister, Integer> regAlloc) {
this.cache = cache;
this.registerAllocation = regAlloc;
this.code = code;
// initialise elementOffsets
// start by setting the size of each instruction to 1
// later on, it will get increased iteratively
this.elementOffsets = new HashMap<DexCodeElement, Long>();
- long offset = 0;
- for (val elem : code.getInstructionList()) {
- elementOffsets.put(elem, offset);
- if (elem instanceof DexInstruction)
- offset += 1;
+ if (this.code != null) {
+ long offset = 0;
+ for (val elem : this.code.getInstructionList()) {
+ elementOffsets.put(elem, offset);
+ if (elem instanceof DexInstruction)
+ offset += 1;
+ }
}
}
public Map<DexRegister, Integer> getRegisterAllocation() {
return Collections.unmodifiableMap(registerAllocation);
}
public Map<DexCodeElement, Long> getElementOffsets() {
return Collections.unmodifiableMap(elementOffsets);
}
public void setElementOffset(DexCodeElement elem, long offset) {
elementOffsets.put(elem, offset);
}
}
| true | true | public DexCode_AssemblingState(DexCode code, DexAssemblingCache cache, Map<DexRegister, Integer> regAlloc) {
this.cache = cache;
this.registerAllocation = regAlloc;
this.code = code;
// initialise elementOffsets
// start by setting the size of each instruction to 1
// later on, it will get increased iteratively
this.elementOffsets = new HashMap<DexCodeElement, Long>();
long offset = 0;
for (val elem : code.getInstructionList()) {
elementOffsets.put(elem, offset);
if (elem instanceof DexInstruction)
offset += 1;
}
}
| public DexCode_AssemblingState(DexCode code, DexAssemblingCache cache, Map<DexRegister, Integer> regAlloc) {
this.cache = cache;
this.registerAllocation = regAlloc;
this.code = code;
// initialise elementOffsets
// start by setting the size of each instruction to 1
// later on, it will get increased iteratively
this.elementOffsets = new HashMap<DexCodeElement, Long>();
if (this.code != null) {
long offset = 0;
for (val elem : this.code.getInstructionList()) {
elementOffsets.put(elem, offset);
if (elem instanceof DexInstruction)
offset += 1;
}
}
}
|
diff --git a/src/main/java/com/threerings/getdown/util/ConnectionUtil.java b/src/main/java/com/threerings/getdown/util/ConnectionUtil.java
index ee7857b..04bc1d7 100644
--- a/src/main/java/com/threerings/getdown/util/ConnectionUtil.java
+++ b/src/main/java/com/threerings/getdown/util/ConnectionUtil.java
@@ -1,47 +1,49 @@
//
// Getdown - application installer, patcher and launcher
// Copyright (C) 2004-2013 Three Rings Design, Inc.
// http://code.google.com/p/getdown/source/browse/LICENSE
package com.threerings.getdown.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import org.apache.commons.codec.binary.Base64;
public class ConnectionUtil
{
/**
* Opens a connection to a URL, setting the authentication header if user info is present.
*/
public static URLConnection open (URL url)
throws IOException
{
URLConnection conn = url.openConnection();
// If URL has a username:password@ before hostname, use HTTP basic auth
String userInfo = url.getUserInfo();
if (userInfo != null) {
// Remove any percent-encoding in the username/password
userInfo = URLDecoder.decode(userInfo, "UTF-8");
- conn.setRequestProperty("Authorization", "Basic " +
- Base64.encodeBase64String(userInfo.getBytes("UTF-8")).replaceAll("\\n",""));
+ // Now base64 encode the auth info and make it a single line
+ String encoded = Base64.encodeBase64String(userInfo.getBytes("UTF-8")).
+ replaceAll("\\n","").replaceAll("\\r", "");
+ conn.setRequestProperty("Authorization", "Basic " + encoded);
}
return conn;
}
/**
* Opens a connection to a http or https URL, setting the authentication header if user info
* is present. Throws a class cast exception if the connection returned is not the right type.
*/
public static HttpURLConnection openHttp (URL url)
throws IOException
{
return (HttpURLConnection)open(url);
}
}
| true | true | public static URLConnection open (URL url)
throws IOException
{
URLConnection conn = url.openConnection();
// If URL has a username:password@ before hostname, use HTTP basic auth
String userInfo = url.getUserInfo();
if (userInfo != null) {
// Remove any percent-encoding in the username/password
userInfo = URLDecoder.decode(userInfo, "UTF-8");
conn.setRequestProperty("Authorization", "Basic " +
Base64.encodeBase64String(userInfo.getBytes("UTF-8")).replaceAll("\\n",""));
}
return conn;
}
| public static URLConnection open (URL url)
throws IOException
{
URLConnection conn = url.openConnection();
// If URL has a username:password@ before hostname, use HTTP basic auth
String userInfo = url.getUserInfo();
if (userInfo != null) {
// Remove any percent-encoding in the username/password
userInfo = URLDecoder.decode(userInfo, "UTF-8");
// Now base64 encode the auth info and make it a single line
String encoded = Base64.encodeBase64String(userInfo.getBytes("UTF-8")).
replaceAll("\\n","").replaceAll("\\r", "");
conn.setRequestProperty("Authorization", "Basic " + encoded);
}
return conn;
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java b/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java
index 91f2450f2..0b3cca324 100644
--- a/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java
+++ b/astrid/plugin-src/com/todoroo/astrid/actfm/EditPeopleControlSet.java
@@ -1,608 +1,609 @@
package com.todoroo.astrid.actfm;
import greendroid.widget.AsyncImageView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.ExceptionService;
import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.astrid.actfm.sync.ActFmInvoker;
import com.todoroo.astrid.actfm.sync.ActFmPreferenceService;
import com.todoroo.astrid.actfm.sync.ActFmSyncService;
import com.todoroo.astrid.actfm.sync.ActFmSyncService.JsonHelper;
import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.MetadataService;
import com.todoroo.astrid.service.StatisticsService;
import com.todoroo.astrid.service.TagDataService;
import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.tags.TagService;
import com.todoroo.astrid.ui.PeopleContainer;
import com.todoroo.astrid.ui.PeopleContainer.OnAddNewPersonListener;
import com.todoroo.astrid.utility.Flags;
public class EditPeopleControlSet implements TaskEditControlSet {
public static final String EXTRA_TASK_ID = "task"; //$NON-NLS-1$
private Task task;
private final ArrayList<Metadata> nonSharedTags = new ArrayList<Metadata>();
@Autowired ActFmPreferenceService actFmPreferenceService;
@Autowired ActFmSyncService actFmSyncService;
@Autowired TaskService taskService;
@Autowired MetadataService metadataService;
@Autowired ExceptionService exceptionService;
@Autowired TagDataService tagDataService;
private final PeopleContainer sharedWithContainer;
private final CheckBox cbFacebook;
private final CheckBox cbTwitter;
private final Spinner assignedSpinner;
private final EditText assignedCustom;
private final ArrayList<AssignedToUser> spinnerValues = new ArrayList<AssignedToUser>();
private final Activity activity;
private String saveToast = null;
private final int loginRequestCode;
static {
AstridDependencyInjector.initialize();
}
// --- UI initialization
public EditPeopleControlSet(Activity activity, int loginRequestCode) {
DependencyInjectionService.getInstance().inject(this);
this.activity = activity;
this.loginRequestCode = loginRequestCode;
sharedWithContainer = (PeopleContainer) activity.findViewById(R.id.share_container);
assignedCustom = (EditText) activity.findViewById(R.id.assigned_custom);
assignedSpinner = (Spinner) activity.findViewById(R.id.assigned_spinner);
cbFacebook = (CheckBox) activity.findViewById(R.id.checkbox_facebook);
cbTwitter = (CheckBox) activity.findViewById(R.id.checkbox_twitter);
sharedWithContainer.addPerson(""); //$NON-NLS-1$
setUpListeners();
}
@Override
public void readFromTask(Task sourceTask) {
task = sourceTask;
setUpData();
}
@SuppressWarnings("nls")
private void setUpData() {
try {
JSONObject sharedWith;
if(task.getValue(Task.SHARED_WITH).length() > 0)
sharedWith = new JSONObject(task.getValue(Task.SHARED_WITH));
else
sharedWith = new JSONObject();
cbFacebook.setChecked(sharedWith.optBoolean("fb", false));
cbTwitter.setChecked(sharedWith.optBoolean("tw", false));
final ArrayList<JSONObject> sharedPeople = new ArrayList<JSONObject>();
JSONArray people = sharedWith.optJSONArray("p");
if(people != null) {
for(int i = 0; i < people.length(); i++) {
String person = people.getString(i);
TextView textView = sharedWithContainer.addPerson(person);
textView.setEnabled(false);
sharedPeople.add(PeopleContainer.createUserJson(textView));
}
}
new Thread(new Runnable() {
@Override
public void run() {
ArrayList<JSONObject> collaborators = new ArrayList<JSONObject>();
TodorooCursor<Metadata> tags = TagService.getInstance().getTags(task.getId());
try {
Metadata metadata = new Metadata();
for(tags.moveToFirst(); !tags.isAfterLast(); tags.moveToNext()) {
metadata.readFromCursor(tags);
final String tag = metadata.getValue(TagService.TAG);
TagData tagData = tagDataService.getTag(tag, TagData.MEMBER_COUNT, TagData.MEMBERS, TagData.USER);
if(tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0) {
JSONArray members = new JSONArray(tagData.getValue(TagData.MEMBERS));
for(int i = 0; i < members.length(); i++) {
JSONObject user = members.getJSONObject(i);
user.put("tag", tag);
sharedPeople.add(user);
collaborators.add(user);
}
if(!TextUtils.isEmpty(tagData.getValue(TagData.USER))) {
JSONObject user = new JSONObject(tagData.getValue(TagData.USER));
user.put("tag", tag);
sharedPeople.add(user);
collaborators.add(user);
}
} else {
nonSharedTags.add((Metadata) metadata.clone());
}
}
if(collaborators.size() > 0)
buildCollaborators(collaborators);
buildAssignedToSpinner(sharedPeople);
} catch (JSONException e) {
exceptionService.reportError("json-reading-data", e);
} finally {
tags.close();
}
}
}).start();
} catch (JSONException e) {
exceptionService.reportError("json-reading-data", e);
}
}
@SuppressWarnings("nls")
private void buildCollaborators(final ArrayList<JSONObject> sharedPeople) throws JSONException {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
HashSet<Long> userIds = new HashSet<Long>();
LinearLayout collaborators = (LinearLayout) activity.findViewById(R.id.collaborators);
for(JSONObject person : sharedPeople) {
if(person == null)
continue;
long id = person.optLong("id", -1);
if(id == 0 || id == ActFmPreferenceService.userId() || (id > -1 && userIds.contains(id)))
continue;
userIds.add(id);
System.err.println("inflated person: " + person);
View contact = activity.getLayoutInflater().inflate(R.layout.contact_adapter_row, collaborators, false);
AsyncImageView icon = (AsyncImageView) contact.findViewById(android.R.id.icon);
TextView name = (TextView) contact.findViewById(android.R.id.text1);
TextView tag = (TextView) contact.findViewById(android.R.id.text2);
icon.setUrl(person.optString("picture"));
name.setText(person.optString("name"));
name.setTextAppearance(activity, android.R.style.TextAppearance_Medium);
tag.setText(activity.getString(R.string.actfm_EPA_list, person.optString("tag")));
tag.setTextAppearance(activity, android.R.style.TextAppearance);
collaborators.addView(contact);
}
}
});
}
private class AssignedToUser {
public String label;
public JSONObject user;
public AssignedToUser(String label, JSONObject user) {
super();
this.label = label;
this.user = user;
}
@Override
public String toString() {
return label;
}
}
@SuppressWarnings("nls")
private void buildAssignedToSpinner(ArrayList<JSONObject> sharedPeople) throws JSONException {
HashSet<Long> userIds = new HashSet<Long>();
HashSet<String> emails = new HashSet<String>();
HashMap<String, AssignedToUser> names = new HashMap<String, AssignedToUser>();
if(task.getValue(Task.USER_ID) != 0) {
JSONObject user = new JSONObject(task.getValue(Task.USER));
sharedPeople.add(0, user);
}
JSONObject myself = new JSONObject();
myself.put("id", 0L);
sharedPeople.add(0, myself);
// de-duplicate by user id and/or email
spinnerValues.clear();
for(int i = 0; i < sharedPeople.size(); i++) {
JSONObject person = sharedPeople.get(i);
if(person == null)
continue;
long id = person.optLong("id", -1);
if(id == ActFmPreferenceService.userId() || (id > -1 && userIds.contains(id)))
continue;
userIds.add(id);
String email = person.optString("email");
if(!TextUtils.isEmpty(email) && emails.contains(email))
continue;
emails.add(email);
String name = person.optString("name");
if(id == 0)
name = activity.getString(R.string.actfm_EPA_assign_me);
AssignedToUser atu = new AssignedToUser(name, person);
spinnerValues.add(atu);
if(names.containsKey(name)) {
AssignedToUser user = names.get(name);
if(user != null && user.user.has("email")) {
user.label += " (" + user.user.optString("email") + ")";
names.put(name, null);
}
if(!TextUtils.isEmpty("email"))
atu.label += " (" + email + ")";
} else if(TextUtils.isEmpty(name)) {
if(!TextUtils.isEmpty("email"))
atu.label = email;
else
spinnerValues.remove(atu);
} else
names.put(name, atu);
}
spinnerValues.add(new AssignedToUser(activity.getString(R.string.actfm_EPA_assign_custom), null));
final ArrayAdapter<AssignedToUser> usersAdapter = new ArrayAdapter<AssignedToUser>(activity,
android.R.layout.simple_spinner_item, spinnerValues);
usersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
assignedSpinner.setAdapter(usersAdapter);
}
});
}
private void setUpListeners() {
final View assignedClear = activity.findViewById(R.id.assigned_clear);
assignedSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v,
int index, long id) {
if(index == spinnerValues.size() - 1) {
assignedCustom.setVisibility(View.VISIBLE);
assignedClear.setVisibility(View.VISIBLE);
assignedSpinner.setVisibility(View.GONE);
assignedCustom.requestFocus();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
//
}
});
assignedClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
assignedCustom.setVisibility(View.GONE);
assignedClear.setVisibility(View.GONE);
assignedCustom.setText(""); //$NON-NLS-1$
assignedSpinner.setVisibility(View.VISIBLE);
assignedSpinner.setSelection(0);
}
});
sharedWithContainer.setOnAddNewPerson(new OnAddNewPersonListener() {
@Override
public void textChanged(String text) {
activity.findViewById(R.id.share_additional).setVisibility(View.VISIBLE);
if(text.indexOf('@') > -1) {
activity.findViewById(R.id.tag_label).setVisibility(View.VISIBLE);
activity.findViewById(R.id.tag_name).setVisibility(View.VISIBLE);
}
}
});
}
// --- events
@Override
public String writeToModel(Task model) {
// do nothing, we use a separate method
return null;
}
/**
* Save sharing settings
* @param toast toast to show after saving is finished
* @return false if login is required & save should be halted
*/
@SuppressWarnings("nls")
public boolean saveSharingSettings(String toast) {
if(task == null)
return false;
saveToast = toast;
boolean dirty = false;
try {
JSONObject userJson;
if(assignedCustom.getVisibility() == View.VISIBLE)
userJson = PeopleContainer.createUserJson(assignedCustom);
else
userJson = ((AssignedToUser) assignedSpinner.getSelectedItem()).user;
if(userJson == null || userJson.optLong("id", -1) == 0) {
dirty = task.getValue(Task.USER_ID) == 0L ? dirty : true;
task.setValue(Task.USER_ID, 0L);
task.setValue(Task.USER, "{}");
} else {
String user = userJson.toString();
dirty = task.getValue(Task.USER).equals(user) ? dirty : true;
task.setValue(Task.USER_ID, userJson.optLong("id", -1));
task.setValue(Task.USER, user);
}
JSONObject sharedWith = parseSharedWithAndTags();
dirty = sharedWith.has("p");
task.setValue(Task.SHARED_WITH, sharedWith.toString());
if(dirty)
taskService.save(task);
if(dirty && !actFmPreferenceService.isLoggedIn()) {
activity.startActivityForResult(new Intent(activity, ActFmLoginActivity.class),
loginRequestCode);
return false;
}
if(dirty)
shareTask(sharedWith);
else
showSaveToast();
return true;
} catch (JSONException e) {
exceptionService.displayAndReportError(activity, "save-people", e);
} catch (ParseSharedException e) {
e.view.setTextColor(Color.RED);
e.view.requestFocus();
DialogUtilities.okDialog(activity, e.message, null);
}
return false;
}
private void showSaveToast() {
int length = saveToast.indexOf('\n') > -1 ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(activity, saveToast, length).show();
}
private class ParseSharedException extends Exception {
private static final long serialVersionUID = -4135848250086302970L;
public TextView view;
public String message;
public ParseSharedException(TextView view, String message) {
this.view = view;
this.message = message;
}
}
@SuppressWarnings("nls")
private JSONObject parseSharedWithAndTags() throws
JSONException, ParseSharedException {
JSONObject sharedWith = new JSONObject();
if(cbFacebook.isChecked())
sharedWith.put("fb", true);
if(cbTwitter.isChecked())
sharedWith.put("tw", true);
JSONArray peopleList = new JSONArray();
for(int i = 0; i < sharedWithContainer.getChildCount(); i++) {
TextView textView = sharedWithContainer.getTextView(i);
textView.setTextAppearance(activity, android.R.style.TextAppearance_Medium_Inverse);
String text = textView.getText().toString();
if(text.length() == 0)
continue;
if(text.indexOf('@') == -1)
throw new ParseSharedException(textView,
activity.getString(R.string.actfm_EPA_invalid_email, text));
peopleList.put(text);
}
if(peopleList.length() > 0)
sharedWith.put("p", peopleList);
return sharedWith;
}
@SuppressWarnings("nls")
private void shareTask(final JSONObject sharedWith) {
final JSONArray emails = sharedWith.optJSONArray("p");
final ProgressDialog pd = DialogUtilities.progressDialog(activity,
activity.getString(R.string.DLG_please_wait));
new Thread() {
@Override
public void run() {
ActFmInvoker invoker = new ActFmInvoker(actFmPreferenceService.getToken());
try {
if(task.getValue(Task.REMOTE_ID) == 0) {
actFmSyncService.pushTask(task.getId());
task.setValue(Task.REMOTE_ID, taskService.fetchById(task.getId(),
Task.REMOTE_ID).getValue(Task.REMOTE_ID));
}
if(task.getValue(Task.REMOTE_ID) == 0) {
DialogUtilities.okDialog(activity, "We had an error saving " +
"this task to Astrid.com. Could you let us know why this happened?", null);
return;
}
Object[] args = buildSharingArgs(emails);
JSONObject result = invoker.invoke("task_share", args);
sharedWith.remove("p");
task.setValue(Task.SHARED_WITH, sharedWith.toString());
task.setValue(Task.DETAILS_DATE, 0L);
readTagData(result.getJSONArray("tags"));
JsonHelper.readUser(result.getJSONObject("assignee"),
task, Task.USER_ID, Task.USER);
Flags.set(Flags.SUPPRESS_SYNC);
taskService.save(task);
int count = result.optInt("shared", 0);
if(count > 0) {
saveToast += "\n" +
activity.getString(R.string.actfm_EPA_emailed_toast,
activity.getResources().getQuantityString(R.plurals.Npeople, count, count));
StatisticsService.reportEvent("actfm-task-shared"); //$NON-NLS-1$
}
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH);
ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
activity.runOnUiThread(new Runnable() {
public void run() {
+ DialogUtilities.dismissDialog(activity, pd);
showSaveToast();
activity.finish();
}
});
} catch (IOException e) {
DialogUtilities.okDialog(activity,
activity.getString(R.string.SyP_ioerror),
android.R.drawable.ic_dialog_alert, e.toString(), null);
} catch (JSONException e) {
DialogUtilities.okDialog(activity,
activity.getString(R.string.SyP_ioerror),
android.R.drawable.ic_dialog_alert, e.toString(), null);
} finally {
activity.runOnUiThread(new Runnable() {
public void run() {
- pd.dismiss();
+ DialogUtilities.dismissDialog(activity, pd);
}
});
}
}
}.start();
}
@SuppressWarnings("nls")
private void readTagData(JSONArray tags) throws JSONException {
ArrayList<Metadata> metadata = new ArrayList<Metadata>();
for(int i = 0; i < tags.length(); i++) {
JSONObject tagObject = tags.getJSONObject(i);
TagData tagData = tagDataService.getTag(tagObject.getString("name"), TagData.ID);
if(tagData == null)
tagData = new TagData();
ActFmSyncService.JsonHelper.tagFromJson(tagObject, tagData);
tagDataService.save(tagData);
Metadata tagMeta = new Metadata();
tagMeta.setValue(Metadata.KEY, TagService.KEY);
tagMeta.setValue(TagService.TAG, tagData.getValue(TagData.NAME));
tagMeta.setValue(TagService.REMOTE_ID, tagData.getValue(TagData.REMOTE_ID));
metadata.add(tagMeta);
}
metadataService.synchronizeMetadata(task.getId(), metadata, MetadataCriteria.withKey(TagService.KEY));
}
@SuppressWarnings("nls")
protected Object[] buildSharingArgs(JSONArray emails) throws JSONException {
ArrayList<Object> values = new ArrayList<Object>();
long currentTaskID = task.getValue(Task.REMOTE_ID);
values.add("id");
values.add(currentTaskID);
if(emails != null) {
for(int i = 0; i < emails.length(); i++) {
String email = emails.optString(i);
if(email == null || email.indexOf('@') == -1)
continue;
values.add("emails[]");
values.add(email);
}
}
values.add("assignee");
if(task.getValue(Task.USER_ID) == 0) {
values.add("");
} else {
if(task.getValue(Task.USER_ID) > 0)
values.add(task.getValue(Task.USER_ID));
else {
JSONObject user = new JSONObject(task.getValue(Task.USER));
values.add(user.getString("email"));
}
}
String message = ((TextView) activity.findViewById(R.id.message)).getText().toString();
if(!TextUtils.isEmpty(message) && activity.findViewById(R.id.share_additional).getVisibility() == View.VISIBLE) {
values.add("message");
values.add(message);
}
String tag = ((TextView) activity.findViewById(R.id.tag_name)).getText().toString();
if(!TextUtils.isEmpty(tag)) {
values.add("tag");
values.add(tag);
}
return values.toArray(new Object[values.size()]);
}
/** Resume save
* @param data */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == loginRequestCode && resultCode == Activity.RESULT_OK)
saveSharingSettings(saveToast);
}
}
| false | true | private void shareTask(final JSONObject sharedWith) {
final JSONArray emails = sharedWith.optJSONArray("p");
final ProgressDialog pd = DialogUtilities.progressDialog(activity,
activity.getString(R.string.DLG_please_wait));
new Thread() {
@Override
public void run() {
ActFmInvoker invoker = new ActFmInvoker(actFmPreferenceService.getToken());
try {
if(task.getValue(Task.REMOTE_ID) == 0) {
actFmSyncService.pushTask(task.getId());
task.setValue(Task.REMOTE_ID, taskService.fetchById(task.getId(),
Task.REMOTE_ID).getValue(Task.REMOTE_ID));
}
if(task.getValue(Task.REMOTE_ID) == 0) {
DialogUtilities.okDialog(activity, "We had an error saving " +
"this task to Astrid.com. Could you let us know why this happened?", null);
return;
}
Object[] args = buildSharingArgs(emails);
JSONObject result = invoker.invoke("task_share", args);
sharedWith.remove("p");
task.setValue(Task.SHARED_WITH, sharedWith.toString());
task.setValue(Task.DETAILS_DATE, 0L);
readTagData(result.getJSONArray("tags"));
JsonHelper.readUser(result.getJSONObject("assignee"),
task, Task.USER_ID, Task.USER);
Flags.set(Flags.SUPPRESS_SYNC);
taskService.save(task);
int count = result.optInt("shared", 0);
if(count > 0) {
saveToast += "\n" +
activity.getString(R.string.actfm_EPA_emailed_toast,
activity.getResources().getQuantityString(R.plurals.Npeople, count, count));
StatisticsService.reportEvent("actfm-task-shared"); //$NON-NLS-1$
}
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH);
ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
activity.runOnUiThread(new Runnable() {
public void run() {
showSaveToast();
activity.finish();
}
});
} catch (IOException e) {
DialogUtilities.okDialog(activity,
activity.getString(R.string.SyP_ioerror),
android.R.drawable.ic_dialog_alert, e.toString(), null);
} catch (JSONException e) {
DialogUtilities.okDialog(activity,
activity.getString(R.string.SyP_ioerror),
android.R.drawable.ic_dialog_alert, e.toString(), null);
} finally {
activity.runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
}
}
}.start();
}
| private void shareTask(final JSONObject sharedWith) {
final JSONArray emails = sharedWith.optJSONArray("p");
final ProgressDialog pd = DialogUtilities.progressDialog(activity,
activity.getString(R.string.DLG_please_wait));
new Thread() {
@Override
public void run() {
ActFmInvoker invoker = new ActFmInvoker(actFmPreferenceService.getToken());
try {
if(task.getValue(Task.REMOTE_ID) == 0) {
actFmSyncService.pushTask(task.getId());
task.setValue(Task.REMOTE_ID, taskService.fetchById(task.getId(),
Task.REMOTE_ID).getValue(Task.REMOTE_ID));
}
if(task.getValue(Task.REMOTE_ID) == 0) {
DialogUtilities.okDialog(activity, "We had an error saving " +
"this task to Astrid.com. Could you let us know why this happened?", null);
return;
}
Object[] args = buildSharingArgs(emails);
JSONObject result = invoker.invoke("task_share", args);
sharedWith.remove("p");
task.setValue(Task.SHARED_WITH, sharedWith.toString());
task.setValue(Task.DETAILS_DATE, 0L);
readTagData(result.getJSONArray("tags"));
JsonHelper.readUser(result.getJSONObject("assignee"),
task, Task.USER_ID, Task.USER);
Flags.set(Flags.SUPPRESS_SYNC);
taskService.save(task);
int count = result.optInt("shared", 0);
if(count > 0) {
saveToast += "\n" +
activity.getString(R.string.actfm_EPA_emailed_toast,
activity.getResources().getQuantityString(R.plurals.Npeople, count, count));
StatisticsService.reportEvent("actfm-task-shared"); //$NON-NLS-1$
}
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH);
ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
activity.runOnUiThread(new Runnable() {
public void run() {
DialogUtilities.dismissDialog(activity, pd);
showSaveToast();
activity.finish();
}
});
} catch (IOException e) {
DialogUtilities.okDialog(activity,
activity.getString(R.string.SyP_ioerror),
android.R.drawable.ic_dialog_alert, e.toString(), null);
} catch (JSONException e) {
DialogUtilities.okDialog(activity,
activity.getString(R.string.SyP_ioerror),
android.R.drawable.ic_dialog_alert, e.toString(), null);
} finally {
activity.runOnUiThread(new Runnable() {
public void run() {
DialogUtilities.dismissDialog(activity, pd);
}
});
}
}
}.start();
}
|
diff --git a/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java b/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java
index cf7f8dd4..fff453da 100644
--- a/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java
+++ b/contentconnector-core/src/main/java/com/gentics/cr/CRConfigFileLoader.java
@@ -1,162 +1,162 @@
package com.gentics.cr;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.gentics.cr.configuration.ConfigurationSettings;
import com.gentics.cr.configuration.EnvironmentConfiguration;
import com.gentics.cr.configuration.GenericConfiguration;
import com.gentics.cr.util.CRUtil;
import com.gentics.cr.util.RegexFileFilter;
/**
*
* Last changed: $Date: 2010-04-01 15:24:02 +0200 (Do, 01 Apr 2010) $
* @version $Revision: 541 $
* @author $Author: [email protected] $
*
*/
public class CRConfigFileLoader extends CRConfigUtil {
/**
*
*/
private static final long serialVersionUID = -87744244157623456L;
private static Logger log = Logger.getLogger(CRConfigFileLoader.class);
private String instancename;
private String webapproot;
protected Properties dsprops = new Properties();
protected Properties handle_props = new Properties();
protected Properties cache_props = new Properties();
/**
* Create new instance of CRConfigFileLoader
* @param name of config
* @param webapproot root directory of application (config read fallback)
*/
public CRConfigFileLoader(String name, String webapproot) {
this(name, webapproot, "");
}
/**
* Load config from String with subdir
* @param name
* @param webapproot
* @param subdir
*/
public CRConfigFileLoader(String name, String webapproot, String subdir) {
super();
this.instancename = name;
this.webapproot = webapproot;
//Load Environment Properties
EnvironmentConfiguration.loadEnvironmentProperties();
this.setName(this.instancename);
//LOAD DEFAULT CONFIGURATION
loadConfigFile("${com.gentics.portalnode.confpath}/rest/"+subdir+this.getName()+".properties");
//LOAD ENVIRONMENT SPECIFIC CONFIGURATION
String modePath = ConfigurationSettings.getConfigurationPath();
if (modePath != null && !"".equals(modePath)) {
loadConfigFile("${com.gentics.portalnode.confpath}/rest/"+subdir+modePath+this.getName()+".properties");
}
// INITIALIZE DATASOURCE WITH HANDLE_PROPS AND DSPROPS
initDS();
}
/**
* Load the config file(s) for this instance.
* @param path file system path to the configuration
*/
private void loadConfigFile(final String path) {
String errorMessage = "Could not load configuration file at: "
+ CRUtil.resolveSystemProperties("${" + CRUtil.PORTALNODE_CONFPATH
+ "}/rest/" + this.getName() + ".properties") + "!";
try {
//LOAD SERVLET CONFIGURATION
String confpath = CRUtil.resolveSystemProperties(path);
java.io.File defaultConfigfile = new java.io.File(confpath);
String basename = defaultConfigfile.getName();
String dirname = defaultConfigfile.getParent();
Vector<String> configfiles = new Vector<String>(1);
if (defaultConfigfile.canRead()) {
configfiles.add(confpath);
}
//add all files matching the regex "name.*.properties"
java.io.File directory = new java.io.File(dirname);
FileFilter regexFilter = new RegexFileFilter(
- basename.replaceAll("\\..*", "") + ".[^\\.]+.properties");
+ basename.replaceAll("\\..*", "") + "\\.[^\\.]+\\.properties");
for (java.io.File file : directory.listFiles(regexFilter)) {
configfiles.add(file.getPath());
}
//load all found files into config
for (String file : configfiles) {
loadConfiguration(this, file, webapproot);
}
if (configfiles.size() == 0) {
throw new FileNotFoundException("Cannot find any valid configfile.");
}
} catch (FileNotFoundException e) {
log.error(errorMessage, e);
} catch (IOException e) {
log.error(errorMessage, e);
} catch (NullPointerException e) {
log.error(errorMessage, e);
}
}
/**
* Loads a configuration file into a GenericConfig instance and resolves system variables
* @param emptyConfig
* @param path
* @param webapproot
* @throws IOException
*/
public static void loadConfiguration(GenericConfiguration emptyConfig,String path,String webapproot) throws IOException
{
Properties props = new Properties();
props.load(new FileInputStream(CRUtil.resolveSystemProperties(path)));
for (Entry<Object,Object> entry:props.entrySet()) {
Object value = entry.getValue();
Object key = entry.getKey();
setProperty(emptyConfig,(String)key, (String)value, webapproot);
}
}
private static void setProperty(GenericConfiguration config,String key, String value, String webapproot) {
//Resolve system properties, so that they can be used in config values
value = CRUtil.resolveSystemProperties((String) value);
//Replace webapproot in the properties values, so that this variable can be
//used
if (webapproot != null) {
value = resolveProperty("\\$\\{webapproot\\}",
webapproot.replace('\\', '/'), value);
}
//Set the property
config.set(key, value);
log.debug("CONFIG: " + key + " has been set to " + value);
}
protected static final String resolveProperty(final String pattern,
final String replacement, String value) {
//TODO check if it is really necessary to manipulate the value string or if
//we can make a copy of it.
value = value.replaceAll(pattern, replacement);
return value;
}
}
| true | true | private void loadConfigFile(final String path) {
String errorMessage = "Could not load configuration file at: "
+ CRUtil.resolveSystemProperties("${" + CRUtil.PORTALNODE_CONFPATH
+ "}/rest/" + this.getName() + ".properties") + "!";
try {
//LOAD SERVLET CONFIGURATION
String confpath = CRUtil.resolveSystemProperties(path);
java.io.File defaultConfigfile = new java.io.File(confpath);
String basename = defaultConfigfile.getName();
String dirname = defaultConfigfile.getParent();
Vector<String> configfiles = new Vector<String>(1);
if (defaultConfigfile.canRead()) {
configfiles.add(confpath);
}
//add all files matching the regex "name.*.properties"
java.io.File directory = new java.io.File(dirname);
FileFilter regexFilter = new RegexFileFilter(
basename.replaceAll("\\..*", "") + ".[^\\.]+.properties");
for (java.io.File file : directory.listFiles(regexFilter)) {
configfiles.add(file.getPath());
}
//load all found files into config
for (String file : configfiles) {
loadConfiguration(this, file, webapproot);
}
if (configfiles.size() == 0) {
throw new FileNotFoundException("Cannot find any valid configfile.");
}
} catch (FileNotFoundException e) {
log.error(errorMessage, e);
} catch (IOException e) {
log.error(errorMessage, e);
} catch (NullPointerException e) {
log.error(errorMessage, e);
}
}
| private void loadConfigFile(final String path) {
String errorMessage = "Could not load configuration file at: "
+ CRUtil.resolveSystemProperties("${" + CRUtil.PORTALNODE_CONFPATH
+ "}/rest/" + this.getName() + ".properties") + "!";
try {
//LOAD SERVLET CONFIGURATION
String confpath = CRUtil.resolveSystemProperties(path);
java.io.File defaultConfigfile = new java.io.File(confpath);
String basename = defaultConfigfile.getName();
String dirname = defaultConfigfile.getParent();
Vector<String> configfiles = new Vector<String>(1);
if (defaultConfigfile.canRead()) {
configfiles.add(confpath);
}
//add all files matching the regex "name.*.properties"
java.io.File directory = new java.io.File(dirname);
FileFilter regexFilter = new RegexFileFilter(
basename.replaceAll("\\..*", "") + "\\.[^\\.]+\\.properties");
for (java.io.File file : directory.listFiles(regexFilter)) {
configfiles.add(file.getPath());
}
//load all found files into config
for (String file : configfiles) {
loadConfiguration(this, file, webapproot);
}
if (configfiles.size() == 0) {
throw new FileNotFoundException("Cannot find any valid configfile.");
}
} catch (FileNotFoundException e) {
log.error(errorMessage, e);
} catch (IOException e) {
log.error(errorMessage, e);
} catch (NullPointerException e) {
log.error(errorMessage, e);
}
}
|
diff --git a/src/edu/ucsb/cs290/touch/to/chat/AuthActivity.java b/src/edu/ucsb/cs290/touch/to/chat/AuthActivity.java
index c9abc92..a81cad4 100644
--- a/src/edu/ucsb/cs290/touch/to/chat/AuthActivity.java
+++ b/src/edu/ucsb/cs290/touch/to/chat/AuthActivity.java
@@ -1,23 +1,26 @@
package edu.ucsb.cs290.touch.to.chat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class AuthActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth);
}
public void submitPassword(View view) {
EditText e = (EditText) findViewById(R.id.enter_password);
setResult(RESULT_OK, new Intent().putExtra("edu.ucsb.cs290.touch.to.chat.password", e.getText().toString()));
+ if(e.getText().length() ==0) {
+ return;
+ }
e.setText("Password Stored");
finish();
}
}
| true | true | public void submitPassword(View view) {
EditText e = (EditText) findViewById(R.id.enter_password);
setResult(RESULT_OK, new Intent().putExtra("edu.ucsb.cs290.touch.to.chat.password", e.getText().toString()));
e.setText("Password Stored");
finish();
}
| public void submitPassword(View view) {
EditText e = (EditText) findViewById(R.id.enter_password);
setResult(RESULT_OK, new Intent().putExtra("edu.ucsb.cs290.touch.to.chat.password", e.getText().toString()));
if(e.getText().length() ==0) {
return;
}
e.setText("Password Stored");
finish();
}
|
diff --git a/src/main/java/org/jboss/lectures/auction/LoginManagerBean.java b/src/main/java/org/jboss/lectures/auction/LoginManagerBean.java
index 79115ec..0ee89dd 100644
--- a/src/main/java/org/jboss/lectures/auction/LoginManagerBean.java
+++ b/src/main/java/org/jboss/lectures/auction/LoginManagerBean.java
@@ -1,111 +1,111 @@
package org.jboss.lectures.auction;
import java.io.Serializable;
import java.security.Principal;
import javax.ejb.Stateful;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.security.auth.Subject;
import org.jboss.lectures.auction.entity.User;
import org.jboss.lectures.auction.qualifiers.LoggedIn;
import org.jboss.security.AuthenticationManager;
import org.jboss.security.SimplePrincipal;
import org.picketbox.config.PicketBoxConfiguration;
import org.picketbox.factories.SecurityFactory;
@SessionScoped
@Named("loginManager")
@Stateful
public class LoginManagerBean implements Serializable, LoginManager {
private static final long serialVersionUID = 1L;
@Inject
private EntityManager em;
@Inject
private UserManager userManager;
@Inject
@LoggedIn
private Event<User> loggedInEvent;
private User currentUser;
@Produces
@LoggedIn
@Named
public User getCurrentUser() {
if (currentUser != null && !em.contains(currentUser)) {
currentUser = em.merge(currentUser);
em.refresh(currentUser);
}
return currentUser;
}
public void login(String email, String password) throws InvalidUserException {
// perform authentication
authenticateUser(email, password);
currentUser = userManager.getUserByEmail(email);
if (currentUser == null) {
currentUser = new User(email);
userManager.addUser(currentUser);
}
loggedInEvent.fire(currentUser);
}
public void logout() {
this.currentUser = null;
}
public boolean isLogged() {
return this.currentUser != null;
}
private void authenticateUser(String email, String password)
throws InvalidUserException {
SecurityFactory.prepare();
try {
- String configFile = "config/authentication.conf";
+ String configFile = "security/auth-conf.xml";
PicketBoxConfiguration idtrustConfig = new PicketBoxConfiguration();
idtrustConfig.load(configFile);
AuthenticationManager am = SecurityFactory
.getAuthenticationManager(LoginManager.SECURITY_DOMAIN);
if (am == null) {
throw new InvalidUserException("Authentication Manager is null");
}
Subject subject = new Subject();
Principal principal = new SimplePrincipal(email);
Object credential = password;
boolean result = am.isValid(principal, credential);
if (result == false) {
throw new InvalidUserException("Authentication Failed");
}
result = am.isValid(principal, credential, subject);
if (result == false)
throw new InvalidUserException("Authentication Failed");
if (subject.getPrincipals().size() < 1)
throw new InvalidUserException("Subject has zero principals");
System.out.println("Authentication Successful");
} finally {
SecurityFactory.release();
}
}
}
| true | true | private void authenticateUser(String email, String password)
throws InvalidUserException {
SecurityFactory.prepare();
try {
String configFile = "config/authentication.conf";
PicketBoxConfiguration idtrustConfig = new PicketBoxConfiguration();
idtrustConfig.load(configFile);
AuthenticationManager am = SecurityFactory
.getAuthenticationManager(LoginManager.SECURITY_DOMAIN);
if (am == null) {
throw new InvalidUserException("Authentication Manager is null");
}
Subject subject = new Subject();
Principal principal = new SimplePrincipal(email);
Object credential = password;
boolean result = am.isValid(principal, credential);
if (result == false) {
throw new InvalidUserException("Authentication Failed");
}
result = am.isValid(principal, credential, subject);
if (result == false)
throw new InvalidUserException("Authentication Failed");
if (subject.getPrincipals().size() < 1)
throw new InvalidUserException("Subject has zero principals");
System.out.println("Authentication Successful");
} finally {
SecurityFactory.release();
}
}
| private void authenticateUser(String email, String password)
throws InvalidUserException {
SecurityFactory.prepare();
try {
String configFile = "security/auth-conf.xml";
PicketBoxConfiguration idtrustConfig = new PicketBoxConfiguration();
idtrustConfig.load(configFile);
AuthenticationManager am = SecurityFactory
.getAuthenticationManager(LoginManager.SECURITY_DOMAIN);
if (am == null) {
throw new InvalidUserException("Authentication Manager is null");
}
Subject subject = new Subject();
Principal principal = new SimplePrincipal(email);
Object credential = password;
boolean result = am.isValid(principal, credential);
if (result == false) {
throw new InvalidUserException("Authentication Failed");
}
result = am.isValid(principal, credential, subject);
if (result == false)
throw new InvalidUserException("Authentication Failed");
if (subject.getPrincipals().size() < 1)
throw new InvalidUserException("Subject has zero principals");
System.out.println("Authentication Successful");
} finally {
SecurityFactory.release();
}
}
|
diff --git a/platform-infrastructure/security/PolicyNegotiator/src/main/java/org/societies/security/policynegotiator/provider/ProviderServiceMgr.java b/platform-infrastructure/security/PolicyNegotiator/src/main/java/org/societies/security/policynegotiator/provider/ProviderServiceMgr.java
index 3b78c5ce5..ba746d85d 100644
--- a/platform-infrastructure/security/PolicyNegotiator/src/main/java/org/societies/security/policynegotiator/provider/ProviderServiceMgr.java
+++ b/platform-infrastructure/security/PolicyNegotiator/src/main/java/org/societies/security/policynegotiator/provider/ProviderServiceMgr.java
@@ -1,347 +1,345 @@
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.security.policynegotiator.provider;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.societies.api.identity.IIdentity;
import org.societies.api.internal.domainauthority.IClientJarServerCallback;
import org.societies.api.internal.domainauthority.IClientJarServerRemote;
import org.societies.api.internal.domainauthority.UrlPath;
import org.societies.api.internal.security.policynegotiator.INegotiationProviderRemote;
import org.societies.api.internal.security.policynegotiator.INegotiationProviderSLMCallback;
import org.societies.api.internal.security.policynegotiator.INegotiationProviderServiceMgmt;
import org.societies.api.internal.security.policynegotiator.NegotiationException;
import org.societies.api.schema.servicelifecycle.model.ServiceResourceIdentifier;
import org.societies.api.security.digsig.DigsigException;
import org.societies.api.security.digsig.ISignatureMgr;
import org.societies.security.dao.ServiceDao;
import org.societies.security.model.Service;
import org.societies.security.policynegotiator.util.FileName;
import org.societies.security.policynegotiator.util.Net;
import org.societies.security.policynegotiator.util.UrlParamName;
/**
*
*
* @author Mitja Vardjan
*
*/
public class ProviderServiceMgr implements INegotiationProviderServiceMgmt {
private static Logger LOG = LoggerFactory.getLogger(ProviderServiceMgr.class);
private IClientJarServerRemote clientJarServer;
private ISignatureMgr signatureMgr;
private INegotiationProviderRemote groupMgr;
private ServiceDao serviceDao;
private HashMap<String, Service> services = new HashMap<String, Service>();
public ProviderServiceMgr() {
LOG.info("ProviderServiceMgr");
}
public IClientJarServerRemote getClientJarServer() {
return clientJarServer;
}
public void setClientJarServer(IClientJarServerRemote clientJarServer) {
LOG.debug("setClientJarServer()");
this.clientJarServer = clientJarServer;
}
public ISignatureMgr getSignatureMgr() {
return signatureMgr;
}
public void setSignatureMgr(ISignatureMgr signatureMgr) {
LOG.debug("setSignatureMgr()");
this.signatureMgr = signatureMgr;
}
public INegotiationProviderRemote getGroupMgr() {
return groupMgr;
}
public void setGroupMgr(INegotiationProviderRemote groupMgr) {
LOG.debug("setGroupMgr()");
this.groupMgr = groupMgr;
}
public ServiceDao getServiceDao() {
return serviceDao;
}
public void setServiceDao(ServiceDao serviceDao) {
this.serviceDao = serviceDao;
}
public void init() {
LOG.info("init");
List<Service> serviceList = serviceDao.getAll();
if (serviceList != null) {
LOG.debug("Loading service list from previous run");
for (Service s : serviceList) {
services.put(s.getServiceId(), s);
LOG.debug("Loaded service [{}] {}", s.getId(), s.getServiceId());
}
}
for (Service s : services.values()) {
LOG.debug("Files of service No. {}: {}", s.getId(), s.getFiles());
}
}
@Override
public void addService(ServiceResourceIdentifier serviceId, String slaXml, URI fileServer,
List<String> files, INegotiationProviderSLMCallback callback) throws NegotiationException {
LOG.info("addService({}, ..., {}, " + files + ")", serviceId, fileServer);
IIdentity provider = groupMgr.getIdMgr().getThisNetworkNode();
String signature;
String dataToSign;
String strippedFilePath;
String idStr = serviceId.getIdentifier().toString();
- Service s = new Service(idStr, slaXml, fileServer, files);
- if (files != null && files.size() > 0) {
+ if (files != null && !files.isEmpty()) {
dataToSign = serviceId.getIdentifier().toASCIIString();
for (int k = 0; k < files.size(); k++) {
if (files.get(k).startsWith("/")) {
strippedFilePath = files.get(k).replaceFirst("/", "");
files.set(k, strippedFilePath);
}
dataToSign += files.get(k);
}
try {
signature = signatureMgr.sign(dataToSign, provider);
} catch (DigsigException e) {
throw new NegotiationException(e);
}
IClientJarServerCallback cb = new ClientJarServerCallback(callback);
this.clientJarServer.shareFiles(groupMgr.getIdMgr().getDomainAuthorityNode(),
serviceId.getIdentifier(), provider, getMyCertificate(), signature, files, cb);
- services.put(idStr, s);
- serviceDao.save(s);
}
- else {
- services.put(idStr, s);
- serviceDao.save(s);
+ Service s = new Service(idStr, slaXml, fileServer, files);
+ services.put(idStr, s);
+ serviceDao.save(s);
+ if (files == null || files.isEmpty()) {
callback.notifySuccess();
}
}
@Override
public void addService(ServiceResourceIdentifier serviceId, String slaXml, URI fileServer,
URL[] fileUrls, INegotiationProviderSLMCallback callback) throws NegotiationException {
LOG.info("addService({}, ..., {}, " + fileUrls + ")", serviceId, fileServer);
List<String> files = new ArrayList<String>();
String tmpFile ="3p-service.tmp";
String fileName;
for (URL f : fileUrls) {
fileName = FileName.getBasename(f.getPath());
LOG.debug("addService(): Adding file: URL = {}, fileName = {}", f, fileName);
files.add(fileName);
Net net = new Net(f);
if (!net.download(tmpFile)) {
continue;
}
URI server;
String uploadUri;
uploadUri = uriForFileUpload(fileServer.toASCIIString(), fileName,
serviceId.getIdentifier(), getMyCertificate());
try {
server = new URI(uploadUri);
} catch (URISyntaxException e) {
LOG.warn("Could not generate URI from {}", fileServer);
throw new NegotiationException(e);
}
net.put(tmpFile, server);
}
if (fileUrls != null && fileUrls.length > 0) {
File tmp = new File(tmpFile);
tmp.delete();
}
addService(serviceId, slaXml, fileServer, files, callback);
}
@Override
public void addService(ServiceResourceIdentifier serviceId, String slaXml, URI fileServer,
String clientJarFilePath, INegotiationProviderSLMCallback callback) throws NegotiationException {
LOG.info("addService({}, ..., {}, String file)", serviceId, fileServer);
List<String> files = new ArrayList<String>();
files.add(clientJarFilePath);
addService(serviceId, slaXml, fileServer, files, callback);
}
@Override
public void removeService(ServiceResourceIdentifier serviceId) {
String idStr = serviceId.getIdentifier().toString();
serviceDao.delete(services.get(idStr));
services.remove(idStr);
}
protected HashMap<String, Service> getServices() {
return services;
}
protected Service getService(String id) {
Service s = services.get(id);
if (s == null) {
LOG.warn("getService({}): service not found", id);
}
return s;
}
/**
* Get URIs for all files for given service.
* Signature is appended to each URI as the URL parameter.
*
* @param serviceId ID of the service to get URIs for
* @return All URIs
* @throws NegotiationException When service is not found
*/
protected List<URI> getSignedUris(String serviceId) throws NegotiationException {
List <URI> uri = new ArrayList<URI>();
String uriStr;
String host;
String sig;
List <String> filePath;
Service s = getService(serviceId);
if (s == null) {
throw new NegotiationException("Service " + serviceId + " not found");
}
host = s.getFileServerHost().toString();
filePath = s.getFiles();
for (int k = 0; k < filePath.size(); k++) {
try {
sig = signatureMgr.sign(filePath.get(k), groupMgr.getIdMgr().getThisNetworkNode());
} catch (DigsigException e) {
LOG.error("Failed to sign file " + filePath.get(k) + " of service " + serviceId, e);
throw new NegotiationException(e);
}
uriStr = uriForFileDownload(host, filePath.get(k), serviceId, sig);
try {
uri.add(new URI(uriStr));
} catch (URISyntaxException e) {
throw new NegotiationException(e);
}
}
return uri;
}
private String uriForFileDownload(String host, String filePath, String serviceId, String sig) {
String uriStr;
LOG.debug("uriForFileDownload({}, {}, ...)", host, filePath);
uriStr = host + UrlPath.BASE + UrlPath.PATH_FILES + "/" + filePath.replaceAll(".*/", "") +
"?" + UrlPath.URL_PARAM_FILE + "=" + filePath +
"&" + UrlPath.URL_PARAM_SERVICE_ID + "=" + serviceId +
"&" + UrlPath.URL_PARAM_SIGNATURE + "=" + sig;
LOG.debug("uriForFileDownload(): uri = {}", uriStr);
return uriStr;
}
private String uriForFileUpload(String host, String filePath, URI serviceId, String pubkey) {
String uriStr;
LOG.debug("uriForFileUpload({}, {}, ...)", host, filePath);
pubkey = UrlParamName.base64ToUrl(pubkey);
uriStr = host + UrlPath.BASE + UrlPath.PATH_FILES + "/" + filePath.replaceAll(".*/", "") +
"?" + UrlPath.URL_PARAM_FILE + "=" + filePath +
"&" + UrlPath.URL_PARAM_PUB_KEY + "=" + pubkey +
"&" + UrlPath.URL_PARAM_SERVICE_ID + "=" + serviceId.toASCIIString();
LOG.debug("uriForFileUpload(): uri = {}", uriStr);
return uriStr;
}
private String getMyCertificate() throws NegotiationException {
IIdentity myIdentity = groupMgr.getIdMgr().getThisNetworkNode();
X509Certificate cert = signatureMgr.getCertificate(myIdentity);
String certStr;
try {
certStr = signatureMgr.cert2str(cert);
} catch (DigsigException e) {
LOG.warn("getMyCertificate(): Could not get my own (provider's) certificate");
throw new NegotiationException(e);
}
return certStr;
}
/**
*
* @param id Service ID
* @return SLA / SOP options
* @throws NegotiationException When service is not found
*/
protected String getSlaXmlOptions(String id) throws NegotiationException {
Service s = getService(id);
if (s != null) {
return s.getSlaXmlOptions();
}
else {
throw new NegotiationException("Service " + id + " not found");
}
}
}
| false | true | public void addService(ServiceResourceIdentifier serviceId, String slaXml, URI fileServer,
List<String> files, INegotiationProviderSLMCallback callback) throws NegotiationException {
LOG.info("addService({}, ..., {}, " + files + ")", serviceId, fileServer);
IIdentity provider = groupMgr.getIdMgr().getThisNetworkNode();
String signature;
String dataToSign;
String strippedFilePath;
String idStr = serviceId.getIdentifier().toString();
Service s = new Service(idStr, slaXml, fileServer, files);
if (files != null && files.size() > 0) {
dataToSign = serviceId.getIdentifier().toASCIIString();
for (int k = 0; k < files.size(); k++) {
if (files.get(k).startsWith("/")) {
strippedFilePath = files.get(k).replaceFirst("/", "");
files.set(k, strippedFilePath);
}
dataToSign += files.get(k);
}
try {
signature = signatureMgr.sign(dataToSign, provider);
} catch (DigsigException e) {
throw new NegotiationException(e);
}
IClientJarServerCallback cb = new ClientJarServerCallback(callback);
this.clientJarServer.shareFiles(groupMgr.getIdMgr().getDomainAuthorityNode(),
serviceId.getIdentifier(), provider, getMyCertificate(), signature, files, cb);
services.put(idStr, s);
serviceDao.save(s);
}
else {
services.put(idStr, s);
serviceDao.save(s);
callback.notifySuccess();
}
}
| public void addService(ServiceResourceIdentifier serviceId, String slaXml, URI fileServer,
List<String> files, INegotiationProviderSLMCallback callback) throws NegotiationException {
LOG.info("addService({}, ..., {}, " + files + ")", serviceId, fileServer);
IIdentity provider = groupMgr.getIdMgr().getThisNetworkNode();
String signature;
String dataToSign;
String strippedFilePath;
String idStr = serviceId.getIdentifier().toString();
if (files != null && !files.isEmpty()) {
dataToSign = serviceId.getIdentifier().toASCIIString();
for (int k = 0; k < files.size(); k++) {
if (files.get(k).startsWith("/")) {
strippedFilePath = files.get(k).replaceFirst("/", "");
files.set(k, strippedFilePath);
}
dataToSign += files.get(k);
}
try {
signature = signatureMgr.sign(dataToSign, provider);
} catch (DigsigException e) {
throw new NegotiationException(e);
}
IClientJarServerCallback cb = new ClientJarServerCallback(callback);
this.clientJarServer.shareFiles(groupMgr.getIdMgr().getDomainAuthorityNode(),
serviceId.getIdentifier(), provider, getMyCertificate(), signature, files, cb);
}
Service s = new Service(idStr, slaXml, fileServer, files);
services.put(idStr, s);
serviceDao.save(s);
if (files == null || files.isEmpty()) {
callback.notifySuccess();
}
}
|
diff --git a/Curriculum/src/main/java/ua/dp/primat/curriculum/view/EditPage.java b/Curriculum/src/main/java/ua/dp/primat/curriculum/view/EditPage.java
index 695a8be..a1b2d36 100644
--- a/Curriculum/src/main/java/ua/dp/primat/curriculum/view/EditPage.java
+++ b/Curriculum/src/main/java/ua/dp/primat/curriculum/view/EditPage.java
@@ -1,255 +1,259 @@
package ua.dp.primat.curriculum.view;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.Application;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.markup.html.form.upload.*;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.file.Files;
import org.apache.wicket.util.file.Folder;
import org.apache.wicket.util.lang.*;
import org.apache.wicket.validation.validator.RangeValidator;
import ua.dp.primat.domain.StudentGroup;
import ua.dp.primat.repositories.StudentGroupRepository;
import ua.dp.primat.curriculum.planparser.CurriculumParser;
import ua.dp.primat.curriculum.planparser.CurriculumXLSRow;
import ua.dp.primat.domain.workload.Workload;
import ua.dp.primat.services.WorkloadService;
import ua.dp.primat.utils.view.GroupsLoadableDetachableModel;
/**
* Wicket page for portlet's EDIT mode. It is used for managing curriculums.
* @author fdevelop
*/
public class EditPage extends WebPage {
/**
* Constructor, that adds needed wicket components.
*/
public EditPage() {
super();
final Form form = new FileUploadForm("formUploadXLS");
add(form);
final Form remForm = new RemoveForm("formRemove");
add(remForm);
//add feed back panel for system information output
final FeedbackPanel feedback = new FeedbackPanel("feedback");
add(feedback);
}
/**
* Returns the place for storing curriculums.
* @return wicket's Folder
*/
private Folder getUploadFolder() {
return ((WicketApplication) Application.get()).getUploadFolder();
}
private StudentGroup parseGroup;
@SpringBean
private StudentGroupRepository studentGroupRepository;
@SpringBean
private WorkloadService workloadService;
private static final long serialVersionUID = 2L;
private static final int MIN_YEAR = 1910;
private static final int MAX_YEAR = 2110;
private static final int MAX_GROUP_NUMBER = 20;
private static final int MAX_FILESIZE = 10; //in megabytes
/**
* Form for removing.
*/
private class RemoveForm extends Form<Void> {
private List<StudentGroup> groups;
private StudentGroup chosenGroup;
/**
* Constructor of form.
* @param name
*/
public RemoveForm(String name) {
super(name);
groups = studentGroupRepository.getGroups();
if (!groups.isEmpty()) {
chosenGroup = groups.get(0);
}
final DropDownChoice<StudentGroup> groupChoise = new DropDownChoice<StudentGroup>("group",
new PropertyModel<StudentGroup>(this, "chosenGroup"),
new GroupsLoadableDetachableModel(groups));
add(groupChoise);
}
/**
* Overriden method onSubmit for the form.
* It takes input fields arguments and removes group, if it exists.
*/
@Override
protected void onSubmit() {
if (chosenGroup == null) {
this.error(String.format("No group selected"));
} else {
studentGroupRepository.remove(chosenGroup);
this.info(String.format("Curriculum has been removed"));
}
}
private static final long serialVersionUID = 2L;
}
/**
* Form for uploads.
*/
private class FileUploadForm extends Form<Void> {
/**
* Constructor of the form.
* @param name
*/
public FileUploadForm(String name) {
super(name);
// set this form to multipart mode (allways needed for uploads!)
setMultiPart(true);
// Add file input field and other options fields
fileUploadField = new FileUploadField("fileInput");
add(fileUploadField);
textParseSheet = new TextField<Integer>("parseSheet", new Model<Integer>(), Integer.class);
textParseSheet.setRequired(true);
textParseSheet.add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
add(textParseSheet);
textParseStart = new TextField<Integer>("parseStart", new Model<Integer>(), Integer.class);
textParseStart.setRequired(true);
textParseStart.add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
add(textParseStart);
textParseEnd = new TextField<Integer>("parseEnd", new Model<Integer>(), Integer.class);
textParseEnd.setRequired(true);
textParseEnd.add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
add(textParseEnd);
textParseSemester = new TextField<Integer>("parseSemester", new Model<Integer>(), Integer.class);
textParseSemester.setRequired(true);
textParseSemester.add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
add(textParseSemester);
textGroupSpec = new TextField<String>("groupSpec", new Model<String>(), String.class);
textGroupSpec.setRequired(true);
add(textGroupSpec);
textGroupYear = new TextField<Integer>("groupYear", new Model<Integer>(), Integer.class);
textGroupYear.setRequired(true);
textGroupYear.add(new RangeValidator<Integer>(MIN_YEAR, MAX_YEAR));
add(textGroupYear);
textGroupNumber = new TextField<Integer>("groupNumber", new Model<Integer>(), Integer.class);
textGroupNumber.setRequired(true);
textGroupNumber.add(new RangeValidator<Integer>(1, MAX_GROUP_NUMBER));
add(textGroupNumber);
// Set maximum size to 10M
setMaxSize(Bytes.megabytes(MAX_FILESIZE));
}
/**
* Overriden method onSubmit for the FileUpload form.
* It takes input fields arguments, uploads file, than parses it, stores
* to the database and output the result.
*/
@Override
protected void onSubmit() {
final Integer parseSheet = textParseSheet.getConvertedInput();
final Integer parseStart = textParseStart.getConvertedInput();
final Integer parseEnd = textParseEnd.getConvertedInput();
final Integer parseSemesters = textParseSemester.getConvertedInput();
final String groupSpec = textGroupSpec.getConvertedInput();
final Integer groupYear = textGroupYear.getConvertedInput();
final Integer groupNumber = textGroupNumber.getConvertedInput();
final FileUpload upload = fileUploadField.getFileUpload();
- parseGroup = new StudentGroup(groupSpec, Long.valueOf(groupNumber), Long.valueOf(groupYear));
+ parseGroup = studentGroupRepository.getGroupByCodeAndYearAndNumber(groupSpec,
+ Long.valueOf(groupNumber), Long.valueOf(groupYear));
+ if (parseGroup == null) {
+ parseGroup = new StudentGroup(groupSpec, Long.valueOf(groupNumber), Long.valueOf(groupYear));
+ }
//parser launch
try {
//upload and create file on server
final String uploadedFileName = makeUploadedFile(upload);
//create and run parser
final CurriculumParser cParser = new CurriculumParser(parseGroup,
parseSheet, parseStart, parseEnd, parseSemesters,
uploadedFileName);
final List<CurriculumXLSRow> listParsed = cParser.parse();
//commit parsed objects
final List<Workload> workloads = new ArrayList<Workload>();
for (int i = 0; i < listParsed.size(); i++) {
workloads.addAll(listParsed.get(i).getWorkloadList());
}
workloadService.storeWorkloads(workloads);
this.info(String.format("Curriculum in '%s' was successfully"
+ " parsed\n into database (%d items).",
uploadedFileName, listParsed.size()));
} catch (IOException ioe) {
this.error(ioe);
}// catch (Exception e) {
// this.info("Curriculum has been parsed, but Throwable was catched...");
//}
}
/**
* Upload the file on server into the getUploadFolder() returned path.
* @param upload
* @return The absolute path to the uploaded file on server.
*/
private String makeUploadedFile(FileUpload upload) throws IOException {
if (upload == null) {
return null;
}
// Create a new file
final File newFile = new File(getUploadFolder(), upload.getClientFileName());
// Check new file, delete if it allready existed
checkFileExists(newFile);
// Save to new file
newFile.createNewFile();
upload.writeTo(newFile);
//EditPage.this.info("saved file: " + upload.getClientFileName() + "\nOriginal saved in: " + newFile.getAbsolutePath());
return newFile.getAbsolutePath();
}
/**
* Check whether the file already exists, and if so, try to delete it.
* @param newFile the file to check
*/
private void checkFileExists(File newFile) {
if ((newFile.exists()) && (!Files.remove(newFile))) {
throw new IllegalStateException("Unable to overwrite " + newFile.getAbsolutePath());
}
}
private FileUploadField fileUploadField;
private TextField<Integer> textParseSheet;
private TextField<Integer> textParseStart;
private TextField<Integer> textParseEnd;
private TextField<Integer> textParseSemester;
private TextField<String> textGroupSpec;
private TextField<Integer> textGroupYear;
private TextField<Integer> textGroupNumber;
private static final long serialVersionUID = 2L;
}
}
| true | true | protected void onSubmit() {
final Integer parseSheet = textParseSheet.getConvertedInput();
final Integer parseStart = textParseStart.getConvertedInput();
final Integer parseEnd = textParseEnd.getConvertedInput();
final Integer parseSemesters = textParseSemester.getConvertedInput();
final String groupSpec = textGroupSpec.getConvertedInput();
final Integer groupYear = textGroupYear.getConvertedInput();
final Integer groupNumber = textGroupNumber.getConvertedInput();
final FileUpload upload = fileUploadField.getFileUpload();
parseGroup = new StudentGroup(groupSpec, Long.valueOf(groupNumber), Long.valueOf(groupYear));
//parser launch
try {
//upload and create file on server
final String uploadedFileName = makeUploadedFile(upload);
//create and run parser
final CurriculumParser cParser = new CurriculumParser(parseGroup,
parseSheet, parseStart, parseEnd, parseSemesters,
uploadedFileName);
final List<CurriculumXLSRow> listParsed = cParser.parse();
//commit parsed objects
final List<Workload> workloads = new ArrayList<Workload>();
for (int i = 0; i < listParsed.size(); i++) {
workloads.addAll(listParsed.get(i).getWorkloadList());
}
workloadService.storeWorkloads(workloads);
this.info(String.format("Curriculum in '%s' was successfully"
+ " parsed\n into database (%d items).",
uploadedFileName, listParsed.size()));
} catch (IOException ioe) {
this.error(ioe);
}// catch (Exception e) {
// this.info("Curriculum has been parsed, but Throwable was catched...");
//}
}
/**
* Upload the file on server into the getUploadFolder() returned path.
* @param upload
* @return The absolute path to the uploaded file on server.
*/
private String makeUploadedFile(FileUpload upload) throws IOException {
if (upload == null) {
return null;
}
// Create a new file
final File newFile = new File(getUploadFolder(), upload.getClientFileName());
// Check new file, delete if it allready existed
checkFileExists(newFile);
// Save to new file
newFile.createNewFile();
upload.writeTo(newFile);
//EditPage.this.info("saved file: " + upload.getClientFileName() + "\nOriginal saved in: " + newFile.getAbsolutePath());
return newFile.getAbsolutePath();
}
/**
* Check whether the file already exists, and if so, try to delete it.
* @param newFile the file to check
*/
private void checkFileExists(File newFile) {
if ((newFile.exists()) && (!Files.remove(newFile))) {
throw new IllegalStateException("Unable to overwrite " + newFile.getAbsolutePath());
}
}
private FileUploadField fileUploadField;
private TextField<Integer> textParseSheet;
private TextField<Integer> textParseStart;
private TextField<Integer> textParseEnd;
private TextField<Integer> textParseSemester;
private TextField<String> textGroupSpec;
private TextField<Integer> textGroupYear;
private TextField<Integer> textGroupNumber;
private static final long serialVersionUID = 2L;
}
| protected void onSubmit() {
final Integer parseSheet = textParseSheet.getConvertedInput();
final Integer parseStart = textParseStart.getConvertedInput();
final Integer parseEnd = textParseEnd.getConvertedInput();
final Integer parseSemesters = textParseSemester.getConvertedInput();
final String groupSpec = textGroupSpec.getConvertedInput();
final Integer groupYear = textGroupYear.getConvertedInput();
final Integer groupNumber = textGroupNumber.getConvertedInput();
final FileUpload upload = fileUploadField.getFileUpload();
parseGroup = studentGroupRepository.getGroupByCodeAndYearAndNumber(groupSpec,
Long.valueOf(groupNumber), Long.valueOf(groupYear));
if (parseGroup == null) {
parseGroup = new StudentGroup(groupSpec, Long.valueOf(groupNumber), Long.valueOf(groupYear));
}
//parser launch
try {
//upload and create file on server
final String uploadedFileName = makeUploadedFile(upload);
//create and run parser
final CurriculumParser cParser = new CurriculumParser(parseGroup,
parseSheet, parseStart, parseEnd, parseSemesters,
uploadedFileName);
final List<CurriculumXLSRow> listParsed = cParser.parse();
//commit parsed objects
final List<Workload> workloads = new ArrayList<Workload>();
for (int i = 0; i < listParsed.size(); i++) {
workloads.addAll(listParsed.get(i).getWorkloadList());
}
workloadService.storeWorkloads(workloads);
this.info(String.format("Curriculum in '%s' was successfully"
+ " parsed\n into database (%d items).",
uploadedFileName, listParsed.size()));
} catch (IOException ioe) {
this.error(ioe);
}// catch (Exception e) {
// this.info("Curriculum has been parsed, but Throwable was catched...");
//}
}
/**
* Upload the file on server into the getUploadFolder() returned path.
* @param upload
* @return The absolute path to the uploaded file on server.
*/
private String makeUploadedFile(FileUpload upload) throws IOException {
if (upload == null) {
return null;
}
// Create a new file
final File newFile = new File(getUploadFolder(), upload.getClientFileName());
// Check new file, delete if it allready existed
checkFileExists(newFile);
// Save to new file
newFile.createNewFile();
upload.writeTo(newFile);
//EditPage.this.info("saved file: " + upload.getClientFileName() + "\nOriginal saved in: " + newFile.getAbsolutePath());
return newFile.getAbsolutePath();
}
/**
* Check whether the file already exists, and if so, try to delete it.
* @param newFile the file to check
*/
private void checkFileExists(File newFile) {
if ((newFile.exists()) && (!Files.remove(newFile))) {
throw new IllegalStateException("Unable to overwrite " + newFile.getAbsolutePath());
}
}
private FileUploadField fileUploadField;
private TextField<Integer> textParseSheet;
private TextField<Integer> textParseStart;
private TextField<Integer> textParseEnd;
private TextField<Integer> textParseSemester;
private TextField<String> textGroupSpec;
private TextField<Integer> textGroupYear;
private TextField<Integer> textGroupNumber;
private static final long serialVersionUID = 2L;
}
|
diff --git a/src/biz/bokhorst/xprivacy/PrivacyService.java b/src/biz/bokhorst/xprivacy/PrivacyService.java
index ff20e7de..a7620664 100644
--- a/src/biz/bokhorst/xprivacy/PrivacyService.java
+++ b/src/biz/bokhorst/xprivacy/PrivacyService.java
@@ -1,1299 +1,1300 @@
package biz.bokhorst.xprivacy;
import java.io.File;
import java.lang.reflect.Method;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteStatement;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Process;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class PrivacyService {
private static int mXUid = -1;
private static String mSecret = null;
private static List<String> mListError;
private static IPrivacyService mClient = null;
private static SQLiteDatabase mDatabase = null;
private static Thread mWorker = null;
private static Handler mHandler = null;
private static boolean mOnDemanding = false;
private static SQLiteStatement stmtGetRestriction = null;
private static SQLiteStatement stmtGetSetting = null;
private static SQLiteStatement stmtGetUsageRestriction = null;
private static SQLiteStatement stmtGetUsageMethod = null;
private static int cCurrentVersion = 260;
private static String cServiceName = "xprivacy" + cCurrentVersion;
private static String cTableRestriction = "restriction";
private static String cTableUsage = "usage";
private static String cTableSetting = "setting";
private static boolean mUseCache = false;
private static Map<CSetting, CSetting> mSettingCache = new HashMap<CSetting, CSetting>();
private static Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>();
private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// TODO: define column names
// sqlite3 /data/data/biz.bokhorst.xprivacy/xprivacy.db
public static void register(List<String> listError, String secret) {
// Store secret and errors
mSecret = secret;
mListError = listError;
try {
// Get memory class to enable/disable caching
// http://stackoverflow.com/questions/2630158/detect-application-heap-size-in-android
int memoryClass = (int) (Runtime.getRuntime().maxMemory() / 1024L / 1024L);
mUseCache = (memoryClass >= 32);
Util.log(null, Log.WARN, "Memory class=" + memoryClass + " cache=" + mUseCache);
// Start a worker thread
mWorker = new Thread(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
mHandler = new Handler();
Looper.loop();
} catch (Throwable ex) {
Util.bug(null, ex);
mListError.add(ex.toString());
}
}
});
mWorker.start();
// Catch ANR's
try {
final Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
for (Method anr : cam.getDeclaredMethods())
if (anr.getName().equals("inputDispatchingTimedOut")) {
Util.log(null, Log.WARN, "Hooking " + anr);
XposedBridge.hookMethod(anr, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
try {
// Delay ANR while on demand dialog open
if (mOnDemanding)
param.setResult(5 * 1000);
} catch (Throwable ex) {
Util.bug(null, ex);
mListError.add(ex.toString());
}
}
});
}
} catch (Throwable ex) {
Util.bug(null, ex);
mListError.add(ex.toString());
}
// Register privacy service
// @formatter:off
// public static void addService(String name, IBinder service)
// public static void addService(String name, IBinder service, boolean allowIsolated)
// @formatter:on
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class,
boolean.class);
Util.log(null, Log.WARN, "Invoking " + mAddService);
mAddService.invoke(null, cServiceName, mPrivacyService, true);
} else {
Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class);
Util.log(null, Log.WARN, "Invoking " + mAddService);
mAddService.invoke(null, cServiceName, mPrivacyService);
}
Util.log(null, Log.WARN, "Service registered name=" + cServiceName);
} catch (Throwable ex) {
Util.bug(null, ex);
mListError.add(ex.toString());
}
}
public static boolean checkClient() {
try {
IPrivacyService client = getClient();
if (client != null)
return (client.getVersion() == cCurrentVersion);
} catch (RemoteException ex) {
Util.bug(null, ex);
}
return false;
}
public static IPrivacyService getClient() {
if (mClient == null)
try {
// public static IBinder getService(String name)
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
Method mGetService = cServiceManager.getDeclaredMethod("getService", String.class);
mClient = IPrivacyService.Stub.asInterface((IBinder) mGetService.invoke(null, cServiceName));
} catch (Throwable ex) {
mClient = null;
Util.bug(null, ex);
}
// Disable disk strict mode
try {
ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
ThreadPolicy newpolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites().build();
StrictMode.setThreadPolicy(newpolicy);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return mClient;
}
private static final IPrivacyService.Stub mPrivacyService = new IPrivacyService.Stub() {
// Management
@Override
public int getVersion() throws RemoteException {
return cCurrentVersion;
}
@Override
public List<String> check() throws RemoteException {
enforcePermission();
File dbFile = getDbFile();
if (!dbFile.exists() || !dbFile.canRead() || !dbFile.canWrite())
throw new InvalidParameterException("Database does not exist or is not accessible");
synchronized (mListError) {
return mListError;
}
}
// Restrictions
@Override
public void setRestriction(ParcelableRestriction restriction) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
// 0 not restricted, ask
// 1 restricted, ask
// 2 not restricted, asked
// 3 restricted, asked
db.beginTransaction();
try {
// Create category record
if (restriction.methodName == null) {
ContentValues cvalues = new ContentValues();
cvalues.put("uid", restriction.uid);
cvalues.put("restriction", restriction.restrictionName);
cvalues.put("method", "");
cvalues.put("restricted", (restriction.restricted ? 1 : 0) + (restriction.asked ? 2 : 0));
db.insertWithOnConflict(cTableRestriction, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE);
}
// Create method exception record
if (restriction.methodName != null) {
ContentValues mvalues = new ContentValues();
mvalues.put("uid", restriction.uid);
mvalues.put("restriction", restriction.restrictionName);
mvalues.put("method", restriction.methodName);
mvalues.put("restricted", (restriction.restricted ? 0 : 1) + (restriction.asked ? 2 : 0));
db.insertWithOnConflict(cTableRestriction, null, mvalues, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear cache
if (mUseCache)
synchronized (mRestrictionCache) {
CRestriction key = new CRestriction(new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null));
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
for (Hook hook : PrivacyManager.getHooks(restriction.restrictionName)) {
key = new CRestriction(new ParcelableRestriction(restriction.uid,
restriction.restrictionName, hook.getName()));
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void setRestrictionList(List<ParcelableRestriction> listRestriction) throws RemoteException {
// Permission enforced by setRestriction
for (ParcelableRestriction restriction : listRestriction)
setRestriction(restriction);
}
@Override
public ParcelableRestriction getRestriction(final ParcelableRestriction restriction, boolean usage,
String secret) throws RemoteException {
final ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, restriction.methodName);
try {
// No permissions enforced, but usage data requires a secret
// Check for self
if (Util.getAppId(restriction.uid) == getXUid()) {
if (PrivacyManager.cIdentification.equals(restriction.restrictionName)
&& "getString".equals(restriction.methodName))
return result;
if (PrivacyManager.cIPC.equals(restriction.restrictionName))
return result;
else if (PrivacyManager.cStorage.equals(restriction.restrictionName))
return result;
else if (PrivacyManager.cSystem.equals(restriction.restrictionName))
return result;
else if (PrivacyManager.cView.equals(restriction.restrictionName))
return result;
}
if (usage) {
// Check for system
if (!PrivacyManager.isApplication(restriction.uid))
if (!getSettingBool(0, PrivacyManager.cSettingSystem, false))
return result;
// Check if restrictions enabled
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingRestricted, true))
return result;
}
// Check cache
boolean cached = false;
if (mUseCache) {
CRestriction key = new CRestriction(restriction);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key)) {
cached = true;
ParcelableRestriction cache = mRestrictionCache.get(key).getRestriction();
result.restricted = cache.restricted;
result.asked = cache.asked;
}
}
}
if (!cached) {
// No permissions required
SQLiteDatabase db = getDatabase();
// Precompile statement when needed
if (stmtGetRestriction == null) {
String sql = "SELECT restricted FROM " + cTableRestriction
+ " WHERE uid=? AND restriction=? AND method=?";
stmtGetRestriction = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetRestriction) {
stmtGetRestriction.clearBindings();
stmtGetRestriction.bindLong(1, restriction.uid);
stmtGetRestriction.bindString(2, restriction.restrictionName);
stmtGetRestriction.bindString(3, "");
long state = stmtGetRestriction.simpleQueryForLong();
result.restricted = ((state & 1) != 0);
result.asked = ((state & 2) != 0);
}
} catch (SQLiteDoneException ignored) {
}
if (restriction.methodName != null)
try {
synchronized (stmtGetRestriction) {
stmtGetRestriction.clearBindings();
stmtGetRestriction.bindLong(1, restriction.uid);
stmtGetRestriction.bindString(2, restriction.restrictionName);
stmtGetRestriction.bindString(3, restriction.methodName);
long state = stmtGetRestriction.simpleQueryForLong();
if (result.restricted)
result.restricted = ((state & 1) == 0);
if (!result.asked)
result.asked = ((state & 2) != 0);
}
} catch (SQLiteDoneException ignored) {
// no change
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Fallback
if (!result.restricted && usage && PrivacyManager.isApplication(restriction.uid)
&& !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
Hook hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName);
if (hook != null && !hook.isDangerous())
result.restricted = PrivacyProvider.getRestrictedFallback(null, restriction.uid,
restriction.restrictionName, restriction.methodName);
}
// Update cache
if (mUseCache) {
CRestriction key = new CRestriction(result);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
mRestrictionCache.put(key, key);
}
}
}
// Media: notify user
if (result.restricted && usage && PrivacyManager.cMedia.equals(restriction.restrictionName))
notifyRestricted(restriction);
// Ask to restrict
if (!result.asked && usage && restriction.methodName != null
&& PrivacyManager.isApplication(restriction.uid))
result.restricted = onDemandDialog(restriction);
// Log usage
if (usage && restriction.methodName != null)
if (getSettingBool(0, PrivacyManager.cSettingUsage, true)) {
// Check secret
boolean allowed = true;
if (Util.getAppId(Binder.getCallingUid()) != getXUid()) {
if (mSecret == null || !mSecret.equals(secret)) {
allowed = false;
Util.log(null, Log.WARN, "Invalid secret");
}
}
if (allowed) {
mExecutor.execute(new Runnable() {
public void run() {
try {
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", restriction.uid);
values.put("restriction", restriction.restrictionName);
values.put("method", restriction.methodName);
values.put("restricted", result.restricted);
values.put("time", new Date().getTime());
db.insertWithOnConflict(cTableUsage, null, values,
SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
}
});
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result;
}
@Override
public List<ParcelableRestriction> getRestrictionList(ParcelableRestriction selector) throws RemoteException {
List<ParcelableRestriction> result = new ArrayList<ParcelableRestriction>();
try {
enforcePermission();
if (selector.restrictionName == null)
for (String sRestrictionName : PrivacyManager.getRestrictions()) {
ParcelableRestriction restriction = new ParcelableRestriction(selector.uid, sRestrictionName,
null, false);
restriction.restricted = getRestriction(restriction, false, mSecret).restricted;
result.add(restriction);
}
else
for (Hook md : PrivacyManager.getHooks(selector.restrictionName)) {
ParcelableRestriction restriction = new ParcelableRestriction(selector.uid,
selector.restrictionName, md.getName(), false);
restriction.restricted = getRestriction(restriction, false, mSecret).restricted;
result.add(restriction);
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteRestrictions(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableRestriction, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Restrictions deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear cache
if (mUseCache)
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Usage
@Override
public long getUsage(List<ParcelableRestriction> listRestriction) throws RemoteException {
long lastUsage = 0;
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
// Precompile statement when needed
if (stmtGetUsageRestriction == null) {
String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=?";
stmtGetUsageRestriction = db.compileStatement(sql);
}
if (stmtGetUsageMethod == null) {
String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=? AND method=?";
stmtGetUsageMethod = db.compileStatement(sql);
}
db.beginTransaction();
try {
for (ParcelableRestriction restriction : listRestriction) {
if (restriction.methodName == null)
try {
synchronized (stmtGetUsageRestriction) {
stmtGetUsageRestriction.clearBindings();
stmtGetUsageRestriction.bindLong(1, restriction.uid);
stmtGetUsageRestriction.bindString(2, restriction.restrictionName);
lastUsage = Math.max(lastUsage, stmtGetUsageRestriction.simpleQueryForLong());
}
} catch (SQLiteDoneException ignored) {
}
else
try {
synchronized (stmtGetUsageMethod) {
stmtGetUsageMethod.clearBindings();
stmtGetUsageMethod.bindLong(1, restriction.uid);
stmtGetUsageMethod.bindString(2, restriction.restrictionName);
stmtGetUsageMethod.bindString(3, restriction.methodName);
lastUsage = Math.max(lastUsage, stmtGetUsageMethod.simpleQueryForLong());
}
} catch (SQLiteDoneException ignored) {
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return lastUsage;
}
@Override
public List<ParcelableRestriction> getUsageList(int uid) throws RemoteException {
List<ParcelableRestriction> result = new ArrayList<ParcelableRestriction>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor;
if (uid == 0)
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, null, new String[] {}, null, null, null);
else
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
ParcelableRestriction data = new ParcelableRestriction();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
result.add(data);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (uid == 0)
db.delete(cTableUsage, null, new String[] {});
else
db.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(ParcelableSetting setting) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND name=?", new String[] { Integer.toString(setting.uid),
setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Update cache
if (mUseCache) {
CSetting key = new CSetting(setting.uid, setting.name);
key.setValue(setting.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
if (setting.value != null)
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void setSettingList(List<ParcelableSetting> listSetting) throws RemoteException {
// Permission enforced by setSetting
for (ParcelableSetting setting : listSetting)
setSetting(setting);
}
@Override
@SuppressLint("DefaultLocale")
public ParcelableSetting getSetting(ParcelableSetting setting) throws RemoteException {
ParcelableSetting result = new ParcelableSetting(setting.uid, setting.name, setting.value);
try {
// No permissions enforced
// Check cache
if (mUseCache && setting.value != null) {
CSetting key = new CSetting(setting.uid, setting.name);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key)) {
result.value = mSettingCache.get(key).getValue();
return result;
}
}
}
// No persmissions required
SQLiteDatabase db = getDatabase();
// Fallback
- if (!getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
+ if (!PrivacyManager.cSettingMigrated.equals(setting.name)
+ && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (setting.uid == 0)
result.value = PrivacyProvider.getSettingFallback(setting.name, null, false);
if (result.value == null) {
result.value = PrivacyProvider.getSettingFallback(
String.format("%s.%d", setting.name, setting.uid), setting.value, false);
return result;
}
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, setting.uid);
stmtGetSetting.bindString(2, setting.name);
String value = stmtGetSetting.simpleQueryForString();
if (value != null)
result.value = value;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Add to cache
if (mUseCache && result.value != null) {
CSetting key = new CSetting(setting.uid, setting.name);
key.setValue(result.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result;
}
@Override
public List<ParcelableSetting> getSettingList(int uid) throws RemoteException {
List<ParcelableSetting> listSetting = new ArrayList<ParcelableSetting>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
listSetting.add(new ParcelableSetting(uid, cursor.getString(0), cursor.getString(1)));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return listSetting;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear cache
if (mUseCache)
synchronized (mSettingCache) {
mSettingCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void clear() throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.execSQL("DELETE FROM restriction");
db.execSQL("DELETE FROM setting");
db.execSQL("DELETE FROM usage");
Util.log(null, Log.WARN, "Database cleared");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear caches
if (mUseCache) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingCache) {
mSettingCache.clear();
}
Util.log(null, Log.WARN, "Cache cleared");
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Helper methods
private Boolean onDemandDialog(final ParcelableRestriction restriction) {
final ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null, false);
try {
// Without handler nothing can be done
if (mHandler == null)
return false;
// Check if enabled
if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true))
return false;
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false))
return false;
// Skip dangerous methods
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
Hook hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName);
if (!dangerous && hook.isDangerous())
return false;
// Skip hooks with no usage data
if (hook.hasNoUsageData())
return false;
// Get am context
final Context context = getContext();
if (context == null)
return false;
// Go ask
synchronized (this) {
mOnDemanding = true;
// Create semaphore
final Semaphore semaphore = new Semaphore(1);
semaphore.acquireUninterruptibly();
// Run dialog in looper
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Build message
ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid);
int stringId = resources.getIdentifier("restrict_" + restriction.restrictionName,
"string", self);
String message = String.format(resources.getString(R.string.msg_ondemand),
TextUtils.join(", ", appInfo.getApplicationName()),
resources.getString(stringId), restriction.methodName);
// Ask
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(resources.getString(R.string.app_name));
LinearLayout llPrompt = new LinearLayout(context);
llPrompt.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
llPrompt.setLayoutParams(lParams);
TextView tvMessage = new TextView(context);
tvMessage.setText(message);
lParams.setMargins(resources.getDimensionPixelSize(R.dimen.activity_horizontal_margin),
resources.getDimensionPixelSize(R.dimen.activity_vertical_margin),
resources.getDimensionPixelSize(R.dimen.activity_horizontal_margin), 0);
tvMessage.setLayoutParams(lParams);
llPrompt.addView(tvMessage);
final CheckBox cbCategory = new CheckBox(context);
cbCategory.setText(resources.getString(R.string.menu_category));
cbCategory.setChecked(true);
lParams.setMargins(0, 0, 0,
resources.getDimensionPixelSize(R.dimen.activity_vertical_margin));
cbCategory.setLayoutParams(lParams);
llPrompt.addView(cbCategory);
alertDialogBuilder.setView(llPrompt);
alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher));
alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
onDemandChoice(restriction, cbCategory.isChecked(), true);
semaphore.release();
}
});
alertDialogBuilder.setNeutralButton(resources.getString(R.string.title_denyonce),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
semaphore.release();
}
});
alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Allow
result.restricted = false;
onDemandChoice(restriction, cbCategory.isChecked(), false);
semaphore.release();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
semaphore.release();
}
}
});
// Wait for dialog
semaphore.acquireUninterruptibly();
mOnDemanding = false;
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result.restricted;
}
private void onDemandChoice(ParcelableRestriction restriction, boolean category, boolean restricted) {
try {
if (category || restricted) {
// Set category restricted, but if the user has requested
// blocking a single function, keep asking for the others
ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null, restricted, category);
setRestriction(result);
// Make exceptions for dangerous methods
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
if (restricted && !dangerous) {
result.restricted = dangerous;
result.asked = true;
for (Hook hook : PrivacyManager.getHooks(restriction.restrictionName))
if (hook.isDangerous()) {
result.methodName = hook.getName();
setRestriction(result);
}
}
// Restrict the requested function & don't ask again
if (!category) {
result.methodName = restriction.methodName;
result.restricted = true;
result.asked = true;
setRestriction(result);
}
} else {
// Leave the category, add an exception for the function
ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, restriction.methodName, restricted, true);
setRestriction(result);
}
// Mark state as changed
setSetting(new ParcelableSetting(restriction.uid, PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_CHANGED)));
// Update modification time
setSetting(new ParcelableSetting(restriction.uid, PrivacyManager.cSettingModifyTime,
Long.toString(System.currentTimeMillis())));
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
}
private void notifyRestricted(ParcelableRestriction restriction) {
final Context context = getContext();
if (context != null && mHandler != null)
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Notify user
Toast.makeText(context, resources.getString(R.string.msg_restrictedby), Toast.LENGTH_LONG)
.show();
} catch (NameNotFoundException ex) {
Util.bug(null, ex);
}
}
});
}
private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException {
String value = getSetting(new ParcelableSetting(uid, name, Boolean.toString(defaultValue))).value;
return Boolean.parseBoolean(value);
}
};
private static void enforcePermission() {
int callingUid = Util.getAppId(Binder.getCallingUid());
if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) {
String callingPkg = null;
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null)
callingPkg = TextUtils.join(", ", pm.getPackagesForUid(Binder.getCallingUid()));
}
throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid() + "/" + callingPkg);
}
}
private static Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
if (am == null)
return null;
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private static int getXUid() {
if (mXUid < 0)
try {
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
String self = PrivacyService.class.getPackage().getName();
ApplicationInfo xInfo = pm.getApplicationInfo(self, 0);
mXUid = xInfo.uid;
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return mXUid;
}
private static File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "xprivacy" + File.separator + "xprivacy.db");
}
public static void setupDatabase() {
// This is run from Zygote with root permissions
try {
File dbFile = getDbFile();
// Create database folder
dbFile.getParentFile().mkdirs();
// Set database file permissions
// Owner: rwx (system)
// Group: --- (system)
// World: ---
Util.setPermission(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
File[] files = dbFile.getParentFile().listFiles();
if (files != null)
for (File file : files)
Util.setPermission(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
// Move database from app folder
File folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName());
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = file.renameTo(target);
Util.log(null, Log.WARN, "Moving " + file + " to " + target + " ok=" + status);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static SQLiteDatabase getDatabase() {
// Create/upgrade database when needed
if (mDatabase == null) {
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
// Update migration status
if (db.getVersion() > 1) {
Util.log(null, Log.WARN, "Updating migration status");
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", 0);
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
// Upgrade database if needed
if (db.needUpgrade(1)) {
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
Util.log(null, Log.WARN, "Creating database");
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(2))
// Old migrated indication
db.setVersion(2);
if (db.needUpgrade(3)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM usage WHERE method=''");
db.setVersion(3);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(4)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value IS NULL");
db.setVersion(4);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(5)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value = ''");
db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'");
db.setVersion(5);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(6)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'");
db.setVersion(6);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
Util.log(null, Log.WARN, "Database version=" + db.getVersion());
mDatabase = db;
}
return mDatabase;
}
}
| true | true | public List<ParcelableRestriction> getUsageList(int uid) throws RemoteException {
List<ParcelableRestriction> result = new ArrayList<ParcelableRestriction>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor;
if (uid == 0)
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, null, new String[] {}, null, null, null);
else
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
ParcelableRestriction data = new ParcelableRestriction();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
result.add(data);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (uid == 0)
db.delete(cTableUsage, null, new String[] {});
else
db.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(ParcelableSetting setting) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND name=?", new String[] { Integer.toString(setting.uid),
setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Update cache
if (mUseCache) {
CSetting key = new CSetting(setting.uid, setting.name);
key.setValue(setting.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
if (setting.value != null)
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void setSettingList(List<ParcelableSetting> listSetting) throws RemoteException {
// Permission enforced by setSetting
for (ParcelableSetting setting : listSetting)
setSetting(setting);
}
@Override
@SuppressLint("DefaultLocale")
public ParcelableSetting getSetting(ParcelableSetting setting) throws RemoteException {
ParcelableSetting result = new ParcelableSetting(setting.uid, setting.name, setting.value);
try {
// No permissions enforced
// Check cache
if (mUseCache && setting.value != null) {
CSetting key = new CSetting(setting.uid, setting.name);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key)) {
result.value = mSettingCache.get(key).getValue();
return result;
}
}
}
// No persmissions required
SQLiteDatabase db = getDatabase();
// Fallback
if (!getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (setting.uid == 0)
result.value = PrivacyProvider.getSettingFallback(setting.name, null, false);
if (result.value == null) {
result.value = PrivacyProvider.getSettingFallback(
String.format("%s.%d", setting.name, setting.uid), setting.value, false);
return result;
}
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, setting.uid);
stmtGetSetting.bindString(2, setting.name);
String value = stmtGetSetting.simpleQueryForString();
if (value != null)
result.value = value;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Add to cache
if (mUseCache && result.value != null) {
CSetting key = new CSetting(setting.uid, setting.name);
key.setValue(result.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result;
}
@Override
public List<ParcelableSetting> getSettingList(int uid) throws RemoteException {
List<ParcelableSetting> listSetting = new ArrayList<ParcelableSetting>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
listSetting.add(new ParcelableSetting(uid, cursor.getString(0), cursor.getString(1)));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return listSetting;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear cache
if (mUseCache)
synchronized (mSettingCache) {
mSettingCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void clear() throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.execSQL("DELETE FROM restriction");
db.execSQL("DELETE FROM setting");
db.execSQL("DELETE FROM usage");
Util.log(null, Log.WARN, "Database cleared");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear caches
if (mUseCache) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingCache) {
mSettingCache.clear();
}
Util.log(null, Log.WARN, "Cache cleared");
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Helper methods
private Boolean onDemandDialog(final ParcelableRestriction restriction) {
final ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null, false);
try {
// Without handler nothing can be done
if (mHandler == null)
return false;
// Check if enabled
if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true))
return false;
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false))
return false;
// Skip dangerous methods
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
Hook hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName);
if (!dangerous && hook.isDangerous())
return false;
// Skip hooks with no usage data
if (hook.hasNoUsageData())
return false;
// Get am context
final Context context = getContext();
if (context == null)
return false;
// Go ask
synchronized (this) {
mOnDemanding = true;
// Create semaphore
final Semaphore semaphore = new Semaphore(1);
semaphore.acquireUninterruptibly();
// Run dialog in looper
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Build message
ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid);
int stringId = resources.getIdentifier("restrict_" + restriction.restrictionName,
"string", self);
String message = String.format(resources.getString(R.string.msg_ondemand),
TextUtils.join(", ", appInfo.getApplicationName()),
resources.getString(stringId), restriction.methodName);
// Ask
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(resources.getString(R.string.app_name));
LinearLayout llPrompt = new LinearLayout(context);
llPrompt.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
llPrompt.setLayoutParams(lParams);
TextView tvMessage = new TextView(context);
tvMessage.setText(message);
lParams.setMargins(resources.getDimensionPixelSize(R.dimen.activity_horizontal_margin),
resources.getDimensionPixelSize(R.dimen.activity_vertical_margin),
resources.getDimensionPixelSize(R.dimen.activity_horizontal_margin), 0);
tvMessage.setLayoutParams(lParams);
llPrompt.addView(tvMessage);
final CheckBox cbCategory = new CheckBox(context);
cbCategory.setText(resources.getString(R.string.menu_category));
cbCategory.setChecked(true);
lParams.setMargins(0, 0, 0,
resources.getDimensionPixelSize(R.dimen.activity_vertical_margin));
cbCategory.setLayoutParams(lParams);
llPrompt.addView(cbCategory);
alertDialogBuilder.setView(llPrompt);
alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher));
alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
onDemandChoice(restriction, cbCategory.isChecked(), true);
semaphore.release();
}
});
alertDialogBuilder.setNeutralButton(resources.getString(R.string.title_denyonce),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
semaphore.release();
}
});
alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Allow
result.restricted = false;
onDemandChoice(restriction, cbCategory.isChecked(), false);
semaphore.release();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
semaphore.release();
}
}
});
// Wait for dialog
semaphore.acquireUninterruptibly();
mOnDemanding = false;
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result.restricted;
}
private void onDemandChoice(ParcelableRestriction restriction, boolean category, boolean restricted) {
try {
if (category || restricted) {
// Set category restricted, but if the user has requested
// blocking a single function, keep asking for the others
ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null, restricted, category);
setRestriction(result);
// Make exceptions for dangerous methods
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
if (restricted && !dangerous) {
result.restricted = dangerous;
result.asked = true;
for (Hook hook : PrivacyManager.getHooks(restriction.restrictionName))
if (hook.isDangerous()) {
result.methodName = hook.getName();
setRestriction(result);
}
}
// Restrict the requested function & don't ask again
if (!category) {
result.methodName = restriction.methodName;
result.restricted = true;
result.asked = true;
setRestriction(result);
}
} else {
// Leave the category, add an exception for the function
ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, restriction.methodName, restricted, true);
setRestriction(result);
}
// Mark state as changed
setSetting(new ParcelableSetting(restriction.uid, PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_CHANGED)));
// Update modification time
setSetting(new ParcelableSetting(restriction.uid, PrivacyManager.cSettingModifyTime,
Long.toString(System.currentTimeMillis())));
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
}
private void notifyRestricted(ParcelableRestriction restriction) {
final Context context = getContext();
if (context != null && mHandler != null)
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Notify user
Toast.makeText(context, resources.getString(R.string.msg_restrictedby), Toast.LENGTH_LONG)
.show();
} catch (NameNotFoundException ex) {
Util.bug(null, ex);
}
}
});
}
private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException {
String value = getSetting(new ParcelableSetting(uid, name, Boolean.toString(defaultValue))).value;
return Boolean.parseBoolean(value);
}
};
private static void enforcePermission() {
int callingUid = Util.getAppId(Binder.getCallingUid());
if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) {
String callingPkg = null;
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null)
callingPkg = TextUtils.join(", ", pm.getPackagesForUid(Binder.getCallingUid()));
}
throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid() + "/" + callingPkg);
}
}
private static Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
if (am == null)
return null;
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private static int getXUid() {
if (mXUid < 0)
try {
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
String self = PrivacyService.class.getPackage().getName();
ApplicationInfo xInfo = pm.getApplicationInfo(self, 0);
mXUid = xInfo.uid;
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return mXUid;
}
private static File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "xprivacy" + File.separator + "xprivacy.db");
}
public static void setupDatabase() {
// This is run from Zygote with root permissions
try {
File dbFile = getDbFile();
// Create database folder
dbFile.getParentFile().mkdirs();
// Set database file permissions
// Owner: rwx (system)
// Group: --- (system)
// World: ---
Util.setPermission(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
File[] files = dbFile.getParentFile().listFiles();
if (files != null)
for (File file : files)
Util.setPermission(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
// Move database from app folder
File folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName());
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = file.renameTo(target);
Util.log(null, Log.WARN, "Moving " + file + " to " + target + " ok=" + status);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static SQLiteDatabase getDatabase() {
// Create/upgrade database when needed
if (mDatabase == null) {
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
// Update migration status
if (db.getVersion() > 1) {
Util.log(null, Log.WARN, "Updating migration status");
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", 0);
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
// Upgrade database if needed
if (db.needUpgrade(1)) {
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
Util.log(null, Log.WARN, "Creating database");
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(2))
// Old migrated indication
db.setVersion(2);
if (db.needUpgrade(3)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM usage WHERE method=''");
db.setVersion(3);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(4)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value IS NULL");
db.setVersion(4);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(5)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value = ''");
db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'");
db.setVersion(5);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(6)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'");
db.setVersion(6);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
Util.log(null, Log.WARN, "Database version=" + db.getVersion());
mDatabase = db;
}
return mDatabase;
}
}
| public List<ParcelableRestriction> getUsageList(int uid) throws RemoteException {
List<ParcelableRestriction> result = new ArrayList<ParcelableRestriction>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor;
if (uid == 0)
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, null, new String[] {}, null, null, null);
else
cursor = db.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted",
"time" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
ParcelableRestriction data = new ParcelableRestriction();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
result.add(data);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (uid == 0)
db.delete(cTableUsage, null, new String[] {});
else
db.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(ParcelableSetting setting) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND name=?", new String[] { Integer.toString(setting.uid),
setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Update cache
if (mUseCache) {
CSetting key = new CSetting(setting.uid, setting.name);
key.setValue(setting.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
if (setting.value != null)
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void setSettingList(List<ParcelableSetting> listSetting) throws RemoteException {
// Permission enforced by setSetting
for (ParcelableSetting setting : listSetting)
setSetting(setting);
}
@Override
@SuppressLint("DefaultLocale")
public ParcelableSetting getSetting(ParcelableSetting setting) throws RemoteException {
ParcelableSetting result = new ParcelableSetting(setting.uid, setting.name, setting.value);
try {
// No permissions enforced
// Check cache
if (mUseCache && setting.value != null) {
CSetting key = new CSetting(setting.uid, setting.name);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key)) {
result.value = mSettingCache.get(key).getValue();
return result;
}
}
}
// No persmissions required
SQLiteDatabase db = getDatabase();
// Fallback
if (!PrivacyManager.cSettingMigrated.equals(setting.name)
&& !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (setting.uid == 0)
result.value = PrivacyProvider.getSettingFallback(setting.name, null, false);
if (result.value == null) {
result.value = PrivacyProvider.getSettingFallback(
String.format("%s.%d", setting.name, setting.uid), setting.value, false);
return result;
}
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, setting.uid);
stmtGetSetting.bindString(2, setting.name);
String value = stmtGetSetting.simpleQueryForString();
if (value != null)
result.value = value;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Add to cache
if (mUseCache && result.value != null) {
CSetting key = new CSetting(setting.uid, setting.name);
key.setValue(result.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result;
}
@Override
public List<ParcelableSetting> getSettingList(int uid) throws RemoteException {
List<ParcelableSetting> listSetting = new ArrayList<ParcelableSetting>();
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
listSetting.add(new ParcelableSetting(uid, cursor.getString(0), cursor.getString(1)));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
return listSetting;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear cache
if (mUseCache)
synchronized (mSettingCache) {
mSettingCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
@Override
public void clear() throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
db.execSQL("DELETE FROM restriction");
db.execSQL("DELETE FROM setting");
db.execSQL("DELETE FROM usage");
Util.log(null, Log.WARN, "Database cleared");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// Clear caches
if (mUseCache) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingCache) {
mSettingCache.clear();
}
Util.log(null, Log.WARN, "Cache cleared");
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
throw new RemoteException(ex.toString());
}
}
// Helper methods
private Boolean onDemandDialog(final ParcelableRestriction restriction) {
final ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null, false);
try {
// Without handler nothing can be done
if (mHandler == null)
return false;
// Check if enabled
if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true))
return false;
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false))
return false;
// Skip dangerous methods
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
Hook hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName);
if (!dangerous && hook.isDangerous())
return false;
// Skip hooks with no usage data
if (hook.hasNoUsageData())
return false;
// Get am context
final Context context = getContext();
if (context == null)
return false;
// Go ask
synchronized (this) {
mOnDemanding = true;
// Create semaphore
final Semaphore semaphore = new Semaphore(1);
semaphore.acquireUninterruptibly();
// Run dialog in looper
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Build message
ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid);
int stringId = resources.getIdentifier("restrict_" + restriction.restrictionName,
"string", self);
String message = String.format(resources.getString(R.string.msg_ondemand),
TextUtils.join(", ", appInfo.getApplicationName()),
resources.getString(stringId), restriction.methodName);
// Ask
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(resources.getString(R.string.app_name));
LinearLayout llPrompt = new LinearLayout(context);
llPrompt.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
llPrompt.setLayoutParams(lParams);
TextView tvMessage = new TextView(context);
tvMessage.setText(message);
lParams.setMargins(resources.getDimensionPixelSize(R.dimen.activity_horizontal_margin),
resources.getDimensionPixelSize(R.dimen.activity_vertical_margin),
resources.getDimensionPixelSize(R.dimen.activity_horizontal_margin), 0);
tvMessage.setLayoutParams(lParams);
llPrompt.addView(tvMessage);
final CheckBox cbCategory = new CheckBox(context);
cbCategory.setText(resources.getString(R.string.menu_category));
cbCategory.setChecked(true);
lParams.setMargins(0, 0, 0,
resources.getDimensionPixelSize(R.dimen.activity_vertical_margin));
cbCategory.setLayoutParams(lParams);
llPrompt.addView(cbCategory);
alertDialogBuilder.setView(llPrompt);
alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher));
alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
onDemandChoice(restriction, cbCategory.isChecked(), true);
semaphore.release();
}
});
alertDialogBuilder.setNeutralButton(resources.getString(R.string.title_denyonce),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
semaphore.release();
}
});
alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Allow
result.restricted = false;
onDemandChoice(restriction, cbCategory.isChecked(), false);
semaphore.release();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
semaphore.release();
}
}
});
// Wait for dialog
semaphore.acquireUninterruptibly();
mOnDemanding = false;
}
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
return result.restricted;
}
private void onDemandChoice(ParcelableRestriction restriction, boolean category, boolean restricted) {
try {
if (category || restricted) {
// Set category restricted, but if the user has requested
// blocking a single function, keep asking for the others
ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, null, restricted, category);
setRestriction(result);
// Make exceptions for dangerous methods
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
if (restricted && !dangerous) {
result.restricted = dangerous;
result.asked = true;
for (Hook hook : PrivacyManager.getHooks(restriction.restrictionName))
if (hook.isDangerous()) {
result.methodName = hook.getName();
setRestriction(result);
}
}
// Restrict the requested function & don't ask again
if (!category) {
result.methodName = restriction.methodName;
result.restricted = true;
result.asked = true;
setRestriction(result);
}
} else {
// Leave the category, add an exception for the function
ParcelableRestriction result = new ParcelableRestriction(restriction.uid,
restriction.restrictionName, restriction.methodName, restricted, true);
setRestriction(result);
}
// Mark state as changed
setSetting(new ParcelableSetting(restriction.uid, PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_CHANGED)));
// Update modification time
setSetting(new ParcelableSetting(restriction.uid, PrivacyManager.cSettingModifyTime,
Long.toString(System.currentTimeMillis())));
} catch (Throwable ex) {
Util.bug(null, ex);
synchronized (mListError) {
mListError.add(ex.toString());
}
}
}
private void notifyRestricted(ParcelableRestriction restriction) {
final Context context = getContext();
if (context != null && mHandler != null)
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Notify user
Toast.makeText(context, resources.getString(R.string.msg_restrictedby), Toast.LENGTH_LONG)
.show();
} catch (NameNotFoundException ex) {
Util.bug(null, ex);
}
}
});
}
private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException {
String value = getSetting(new ParcelableSetting(uid, name, Boolean.toString(defaultValue))).value;
return Boolean.parseBoolean(value);
}
};
private static void enforcePermission() {
int callingUid = Util.getAppId(Binder.getCallingUid());
if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) {
String callingPkg = null;
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null)
callingPkg = TextUtils.join(", ", pm.getPackagesForUid(Binder.getCallingUid()));
}
throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid() + "/" + callingPkg);
}
}
private static Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
if (am == null)
return null;
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private static int getXUid() {
if (mXUid < 0)
try {
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
String self = PrivacyService.class.getPackage().getName();
ApplicationInfo xInfo = pm.getApplicationInfo(self, 0);
mXUid = xInfo.uid;
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return mXUid;
}
private static File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "xprivacy" + File.separator + "xprivacy.db");
}
public static void setupDatabase() {
// This is run from Zygote with root permissions
try {
File dbFile = getDbFile();
// Create database folder
dbFile.getParentFile().mkdirs();
// Set database file permissions
// Owner: rwx (system)
// Group: --- (system)
// World: ---
Util.setPermission(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
File[] files = dbFile.getParentFile().listFiles();
if (files != null)
for (File file : files)
Util.setPermission(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
// Move database from app folder
File folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName());
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = file.renameTo(target);
Util.log(null, Log.WARN, "Moving " + file + " to " + target + " ok=" + status);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static SQLiteDatabase getDatabase() {
// Create/upgrade database when needed
if (mDatabase == null) {
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
// Update migration status
if (db.getVersion() > 1) {
Util.log(null, Log.WARN, "Updating migration status");
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", 0);
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
// Upgrade database if needed
if (db.needUpgrade(1)) {
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
Util.log(null, Log.WARN, "Creating database");
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(2))
// Old migrated indication
db.setVersion(2);
if (db.needUpgrade(3)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM usage WHERE method=''");
db.setVersion(3);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(4)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value IS NULL");
db.setVersion(4);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(5)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value = ''");
db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'");
db.setVersion(5);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
if (db.needUpgrade(6)) {
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'");
db.setVersion(6);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
db.endTransaction();
}
}
Util.log(null, Log.WARN, "Database version=" + db.getVersion());
mDatabase = db;
}
return mDatabase;
}
}
|
diff --git a/src/main/java/net/loadingchunks/plugins/PushEnder/PushUser.java b/src/main/java/net/loadingchunks/plugins/PushEnder/PushUser.java
index 194551f..e3514ae 100644
--- a/src/main/java/net/loadingchunks/plugins/PushEnder/PushUser.java
+++ b/src/main/java/net/loadingchunks/plugins/PushEnder/PushUser.java
@@ -1,23 +1,23 @@
package net.loadingchunks.plugins.PushEnder;
import java.util.HashMap;
import org.bukkit.configuration.ConfigurationSection;
public class PushUser {
public String userToken = "";
public String username = "";
public HashMap<String, Boolean> eventConfig = new HashMap<String, Boolean>();
public PushUser(String name, ConfigurationSection cs) {
- if(cs.contains("userToken"))
- userToken = cs.getString("userToken");
+ if(cs.contains("token"))
+ userToken = cs.getString("token");
if(!cs.contains("events"))
return;
for(String key : cs.getConfigurationSection("events").getKeys(false)) {
eventConfig.put(key, cs.getBoolean("events." + key));
}
}
}
| true | true | public PushUser(String name, ConfigurationSection cs) {
if(cs.contains("userToken"))
userToken = cs.getString("userToken");
if(!cs.contains("events"))
return;
for(String key : cs.getConfigurationSection("events").getKeys(false)) {
eventConfig.put(key, cs.getBoolean("events." + key));
}
}
| public PushUser(String name, ConfigurationSection cs) {
if(cs.contains("token"))
userToken = cs.getString("token");
if(!cs.contains("events"))
return;
for(String key : cs.getConfigurationSection("events").getKeys(false)) {
eventConfig.put(key, cs.getBoolean("events." + key));
}
}
|
diff --git a/facets/src/main/java/org/ilrt/wf/facets/impl/FlatFacetImpl.java b/facets/src/main/java/org/ilrt/wf/facets/impl/FlatFacetImpl.java
index bf45ae0..6c0652a 100644
--- a/facets/src/main/java/org/ilrt/wf/facets/impl/FlatFacetImpl.java
+++ b/facets/src/main/java/org/ilrt/wf/facets/impl/FlatFacetImpl.java
@@ -1,158 +1,158 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ilrt.wf.facets.impl;
import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.RDFS;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.ilrt.wf.facets.Facet;
import org.ilrt.wf.facets.FacetEnvironment;
import org.ilrt.wf.facets.FacetException;
import org.ilrt.wf.facets.FacetQueryService;
import org.ilrt.wf.facets.FacetState;
import org.ilrt.wf.facets.QNameUtility;
import org.ilrt.wf.facets.constraints.ValueConstraint;
/**
*
* @author pldms
*/
public class FlatFacetImpl extends AbstractFacetFactoryImpl {
private final FacetQueryService facetQueryService;
private final QNameUtility qNameUtility;
public FlatFacetImpl(FacetQueryService facetQueryService, QNameUtility qNameUtility) {
this.facetQueryService = facetQueryService;
this.qNameUtility = qNameUtility;
}
@Override
public Facet create(FacetEnvironment environment) throws FacetException {
FacetStateImpl state;
String type = environment.getConfig().get(Facet.CONSTRAINT_TYPE);
String property = environment.getConfig().get(Facet.LINK_PROPERTY);
String invertVal = environment.getConfig().get(Facet.LINK_INVERT);
String label = environment.getConfig().get(Facet.REQUIRE_LABEL);
boolean invert = (invertVal != null && invertVal.equalsIgnoreCase("true"));
- boolean requireLabel = (label != null && invertVal.equalsIgnoreCase("true"));
+ boolean requireLabel = (label != null && label.equalsIgnoreCase("true"));
Property prop = ResourceFactory.createProperty(property);
String param = environment.getConfig().get(Facet.PARAM_NAME);
ValueConstraint typeConstraint = createTypeConstraint(type);
String[] currentVals = environment.getParameters().get(environment.getConfig().get(Facet.PARAM_NAME));
if ( currentVals == null || currentVals.length == 0 ) { // The root state
Collection<RDFNode> vals = facetQueryService.getValuesOfPropertyForType(
ResourceFactory.createResource(type),
prop,
invert,
requireLabel);
state = new FacetStateCollector("Base", null, null, Collections.singletonList(typeConstraint));
((FacetStateCollector) state).setProperty(prop);
((FacetStateCollector) state).setInvert(invert);
state.setRoot(true);
List<FacetState> refinements = new ArrayList(vals.size());
for (RDFNode val: vals) {
ValueConstraint valConstraint = new ValueConstraint(prop, val, invert);
FacetState refine = new FacetStateImpl(
getLabel(val),
state,
toParamVal(val),
Arrays.asList(typeConstraint, valConstraint));
refinements.add(refine);
}
// Not convinced about this.
Collections.sort(refinements, new Comparator() {
@Override
public int compare(Object t, Object t1) {
return ((FacetState) t).getName().compareTo(((FacetState) t1).getName());
}
});
state.setRefinements(refinements);
} else {
FacetStateImpl bState = new FacetStateImpl("Base", null, null, Collections.singletonList(typeConstraint));
bState.setRoot(true);
RDFNode val = fromParamVal(currentVals[0]);
ValueConstraint valConstraint = new ValueConstraint(prop, val,invert);
state = new FacetStateImpl(
getLabel(val),
bState,
toParamVal(val),
Arrays.asList(typeConstraint, valConstraint)
);
}
return new FacetImpl(getFacetTitle(environment), state, getParameterName(environment));
}
private String toParamVal(RDFNode node) {
if (node.isLiteral()){
return "L" + ((Literal) node).getLexicalForm() + " " +
qNameUtility.getQName(((Literal) node).getDatatypeURI());
}
else if (node.isURIResource())
return "U" + qNameUtility.getQName(((Resource) node).getURI()) + '#' + getLabel(node);
else return "B" + ((Resource) node).getId().getLabelString();
}
private final TypeMapper TM = TypeMapper.getInstance();
private RDFNode fromParamVal(String val) {
if (val.startsWith("U"))
{
String param = val.substring(1);
String uri = param.substring(0,param.lastIndexOf("#")); // obtain uri from parameter
String label = param.substring(param.lastIndexOf("#")+1); // obtain label from parameter
// create a resource using these properties
Resource r = ResourceFactory.createResource(qNameUtility.expandQName(uri));
Model m = ModelFactory.createDefaultModel();
r = r.inModel(m);
r.addProperty(RDFS.label, label);
return r;
}
// Erm, what should we do here? Fail?
else if (val.startsWith("B")) return ResourceFactory.createResource();
else {
int index = val.lastIndexOf(" ");
String lex = val.substring(1, index);
String dt = qNameUtility.expandQName(val.substring(index + 1));
return (dt.isEmpty()) ?
ResourceFactory.createPlainLiteral(lex) :
ResourceFactory.createTypedLiteral(lex, TM.getSafeTypeByName(dt));
}
}
private String getLabel(RDFNode node) {
if (node.isLiteral()) return ((Literal) node).getLexicalForm();
else if (node.isAnon()) return ((Resource) node).getId().getLabelString();
else {
Resource r = (Resource) node;
String label = (r.hasProperty(RDFS.label)) ?
r.getProperty(RDFS.label).getLiteral().getLexicalForm() :
qNameUtility.getQName(r.getURI());
return label;
}
}
}
| true | true | public Facet create(FacetEnvironment environment) throws FacetException {
FacetStateImpl state;
String type = environment.getConfig().get(Facet.CONSTRAINT_TYPE);
String property = environment.getConfig().get(Facet.LINK_PROPERTY);
String invertVal = environment.getConfig().get(Facet.LINK_INVERT);
String label = environment.getConfig().get(Facet.REQUIRE_LABEL);
boolean invert = (invertVal != null && invertVal.equalsIgnoreCase("true"));
boolean requireLabel = (label != null && invertVal.equalsIgnoreCase("true"));
Property prop = ResourceFactory.createProperty(property);
String param = environment.getConfig().get(Facet.PARAM_NAME);
ValueConstraint typeConstraint = createTypeConstraint(type);
String[] currentVals = environment.getParameters().get(environment.getConfig().get(Facet.PARAM_NAME));
if ( currentVals == null || currentVals.length == 0 ) { // The root state
Collection<RDFNode> vals = facetQueryService.getValuesOfPropertyForType(
ResourceFactory.createResource(type),
prop,
invert,
requireLabel);
state = new FacetStateCollector("Base", null, null, Collections.singletonList(typeConstraint));
((FacetStateCollector) state).setProperty(prop);
((FacetStateCollector) state).setInvert(invert);
state.setRoot(true);
List<FacetState> refinements = new ArrayList(vals.size());
for (RDFNode val: vals) {
ValueConstraint valConstraint = new ValueConstraint(prop, val, invert);
FacetState refine = new FacetStateImpl(
getLabel(val),
state,
toParamVal(val),
Arrays.asList(typeConstraint, valConstraint));
refinements.add(refine);
}
// Not convinced about this.
Collections.sort(refinements, new Comparator() {
@Override
public int compare(Object t, Object t1) {
return ((FacetState) t).getName().compareTo(((FacetState) t1).getName());
}
});
state.setRefinements(refinements);
} else {
FacetStateImpl bState = new FacetStateImpl("Base", null, null, Collections.singletonList(typeConstraint));
bState.setRoot(true);
RDFNode val = fromParamVal(currentVals[0]);
ValueConstraint valConstraint = new ValueConstraint(prop, val,invert);
state = new FacetStateImpl(
getLabel(val),
bState,
toParamVal(val),
Arrays.asList(typeConstraint, valConstraint)
);
}
return new FacetImpl(getFacetTitle(environment), state, getParameterName(environment));
}
| public Facet create(FacetEnvironment environment) throws FacetException {
FacetStateImpl state;
String type = environment.getConfig().get(Facet.CONSTRAINT_TYPE);
String property = environment.getConfig().get(Facet.LINK_PROPERTY);
String invertVal = environment.getConfig().get(Facet.LINK_INVERT);
String label = environment.getConfig().get(Facet.REQUIRE_LABEL);
boolean invert = (invertVal != null && invertVal.equalsIgnoreCase("true"));
boolean requireLabel = (label != null && label.equalsIgnoreCase("true"));
Property prop = ResourceFactory.createProperty(property);
String param = environment.getConfig().get(Facet.PARAM_NAME);
ValueConstraint typeConstraint = createTypeConstraint(type);
String[] currentVals = environment.getParameters().get(environment.getConfig().get(Facet.PARAM_NAME));
if ( currentVals == null || currentVals.length == 0 ) { // The root state
Collection<RDFNode> vals = facetQueryService.getValuesOfPropertyForType(
ResourceFactory.createResource(type),
prop,
invert,
requireLabel);
state = new FacetStateCollector("Base", null, null, Collections.singletonList(typeConstraint));
((FacetStateCollector) state).setProperty(prop);
((FacetStateCollector) state).setInvert(invert);
state.setRoot(true);
List<FacetState> refinements = new ArrayList(vals.size());
for (RDFNode val: vals) {
ValueConstraint valConstraint = new ValueConstraint(prop, val, invert);
FacetState refine = new FacetStateImpl(
getLabel(val),
state,
toParamVal(val),
Arrays.asList(typeConstraint, valConstraint));
refinements.add(refine);
}
// Not convinced about this.
Collections.sort(refinements, new Comparator() {
@Override
public int compare(Object t, Object t1) {
return ((FacetState) t).getName().compareTo(((FacetState) t1).getName());
}
});
state.setRefinements(refinements);
} else {
FacetStateImpl bState = new FacetStateImpl("Base", null, null, Collections.singletonList(typeConstraint));
bState.setRoot(true);
RDFNode val = fromParamVal(currentVals[0]);
ValueConstraint valConstraint = new ValueConstraint(prop, val,invert);
state = new FacetStateImpl(
getLabel(val),
bState,
toParamVal(val),
Arrays.asList(typeConstraint, valConstraint)
);
}
return new FacetImpl(getFacetTitle(environment), state, getParameterName(environment));
}
|
diff --git a/org.dawnsci.conversion.test/src/org/dawnsci/conversion/NCDConvertTest.java b/org.dawnsci.conversion.test/src/org/dawnsci/conversion/NCDConvertTest.java
index 01656137..ac524326 100644
--- a/org.dawnsci.conversion.test/src/org/dawnsci/conversion/NCDConvertTest.java
+++ b/org.dawnsci.conversion.test/src/org/dawnsci/conversion/NCDConvertTest.java
@@ -1,221 +1,224 @@
/*
* Copyright (c) 2012 Diamond Light Source Ltd.
*
* 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.dawnsci.conversion;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.dawb.common.services.conversion.IConversionContext;
import org.dawb.common.services.conversion.IConversionContext.ConversionScheme;
import org.dawb.common.services.conversion.IConversionService;
import org.dawnsci.conversion.converters.CustomNCDConverter.SAS_FORMAT;
import org.eclipse.dawnsci.analysis.api.io.IDataHolder;
import org.junit.Test;
import uk.ac.diamond.scisoft.analysis.io.LoaderFactory;
public class NCDConvertTest {
@Test
public void testNCDSimple() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
final String path = getTestFilePath("results_i22-102527_Pilatus2M_280313_112434.nxs");
final IConversionContext context = service.open(path);
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetName("/entry1/Pilatus2M_result/data");
context.setAxisDatasetName("/entry1/Pilatus2M_result/q");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
for (File file : fa) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
assertEquals(61, names.length);
assertEquals("q(1/nm)",names[0]);
assertEquals("Column_0",names[1]);
}
}
@Test
public void testNCDSimpleNoAxis() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
final String path = getTestFilePath("results_i22-102527_Pilatus2M_280313_112434.nxs");
final IConversionContext context = service.open(path);
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetName("/entry1/Pilatus2M_result/data");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
for (File file : fa) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
assertEquals(60, names.length);
assertEquals("Column_0",names[0]);
assertEquals("Column_1",names[1]);
}
}
@Test
public void testNCDMultiDims() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
final String path = getTestFilePath("results_i22-114346_Pilatus2M_220313_090939.nxs");
final IConversionContext context = service.open(path);
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetName("/entry1/Pilatus2M_result/data");
context.setAxisDatasetName("/entry1/Pilatus2M_result/q");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
assertEquals(12, fa.length);
for (File file : fa) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
assertEquals(3, names.length);
assertEquals("q(1/A)",names[0]);
assertEquals("Column_0",names[1]);
}
}
@Test
public void testNCDSingleAndNormalised() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
final String path = getTestFilePath("results_i22-118040_Pilatus2M_010513_125108.nxs");
final IConversionContext context = service.open(path);
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetNames(Arrays.asList(new String[] {"/entry1/Pilatus2M_result/data","/entry1/Pilatus2M_processing/Normalisation/data"}));
context.setAxisDatasetName("/entry1/Pilatus2M_result/q");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
assertEquals(2, fa.length);
for (File file : fa) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
assertEquals(2, names.length);
assertEquals("q(1/A)",names[0]);
assertEquals("Column_0",names[1]);
}
}
@Test
public void testNCDMultiFile() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
- final String path = getTestFilePath("results_i22-118040_Pilatus2M_010513_125108.nxs");
- final String path1 = getTestFilePath("results_i22-102527_Pilatus2M_280313_112434.nxs");
- final String path2 = getTestFilePath("results_i22-114346_Pilatus2M_220313_090939.nxs");
+ final String resultName = "results_i22-118040_Pilatus2M_010513_125108";
+ final String resultName2 = "results_i22-102527_Pilatus2M_280313_112434";
+ final String resultName3 = "results_i22-114346_Pilatus2M_220313_090939";
+ final String path = getTestFilePath(resultName+".nxs");
+ final String path1 = getTestFilePath(resultName2+".nxs");
+ final String path2 = getTestFilePath(resultName3+".nxs");
Map<String, String> unitMap = new HashMap<String, String>();
- unitMap.put(path , "q(1/A)");
- unitMap.put(path1, "q(1/nm)");
- unitMap.put(path2, "q(1/A)");
+ unitMap.put(resultName , "q(1/A)");
+ unitMap.put(resultName2, "q(1/nm)");
+ unitMap.put(resultName3, "q(1/A)");
final IConversionContext context = service.open(path);
///TODO fix in interface
if (context instanceof ConversionContext) {
((ConversionContext)context).setFilePaths(path,path1,path2);
}
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetNames(Arrays.asList(new String[] {"/entry1/Pilatus2M_result/data","/entry1/Pilatus2M_processing/Normalisation/data"}));
context.setAxisDatasetName("/entry1/Pilatus2M_result/q");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
assertEquals(27, fa.length);
for (File file : fa) {
for (String pathName : unitMap.keySet()) {
if (file.getName().contains(pathName)) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
String unitName = unitMap.get(pathName);
assertEquals(unitName, names[0]);
assertEquals("Column_0", names[1]);
}
}
}
}
private String getTestFilePath(String fileName) {
final File test = new File("testfiles/"+fileName);
return test.getAbsolutePath();
}
}
| false | true | public void testNCDMultiFile() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
final String path = getTestFilePath("results_i22-118040_Pilatus2M_010513_125108.nxs");
final String path1 = getTestFilePath("results_i22-102527_Pilatus2M_280313_112434.nxs");
final String path2 = getTestFilePath("results_i22-114346_Pilatus2M_220313_090939.nxs");
Map<String, String> unitMap = new HashMap<String, String>();
unitMap.put(path , "q(1/A)");
unitMap.put(path1, "q(1/nm)");
unitMap.put(path2, "q(1/A)");
final IConversionContext context = service.open(path);
///TODO fix in interface
if (context instanceof ConversionContext) {
((ConversionContext)context).setFilePaths(path,path1,path2);
}
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetNames(Arrays.asList(new String[] {"/entry1/Pilatus2M_result/data","/entry1/Pilatus2M_processing/Normalisation/data"}));
context.setAxisDatasetName("/entry1/Pilatus2M_result/q");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
assertEquals(27, fa.length);
for (File file : fa) {
for (String pathName : unitMap.keySet()) {
if (file.getName().contains(pathName)) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
String unitName = unitMap.get(pathName);
assertEquals(unitName, names[0]);
assertEquals("Column_0", names[1]);
}
}
}
}
| public void testNCDMultiFile() throws Exception {
IConversionService service = new ConversionServiceImpl();
// Determine path to test file
final String resultName = "results_i22-118040_Pilatus2M_010513_125108";
final String resultName2 = "results_i22-102527_Pilatus2M_280313_112434";
final String resultName3 = "results_i22-114346_Pilatus2M_220313_090939";
final String path = getTestFilePath(resultName+".nxs");
final String path1 = getTestFilePath(resultName2+".nxs");
final String path2 = getTestFilePath(resultName3+".nxs");
Map<String, String> unitMap = new HashMap<String, String>();
unitMap.put(resultName , "q(1/A)");
unitMap.put(resultName2, "q(1/nm)");
unitMap.put(resultName3, "q(1/A)");
final IConversionContext context = service.open(path);
///TODO fix in interface
if (context instanceof ConversionContext) {
((ConversionContext)context).setFilePaths(path,path1,path2);
}
final File tmp = File.createTempFile("NCDtestSimple", ".dat");
tmp.deleteOnExit();
final File dir = new File(tmp.getParent(), "NCD_export"+System.currentTimeMillis());
dir.mkdirs();
dir.deleteOnExit();
context.setOutputPath(dir.getAbsolutePath());
context.setConversionScheme(ConversionScheme.CUSTOM_NCD);
context.setDatasetNames(Arrays.asList(new String[] {"/entry1/Pilatus2M_result/data","/entry1/Pilatus2M_processing/Normalisation/data"}));
context.setAxisDatasetName("/entry1/Pilatus2M_result/q");
context.addSliceDimension(0, "all");
context.setUserObject(SAS_FORMAT.ASCII);
service.process(context);
final File[] fa = dir.listFiles();
assertEquals(27, fa.length);
for (File file : fa) {
for (String pathName : unitMap.keySet()) {
if (file.getName().contains(pathName)) {
file.deleteOnExit();
final IDataHolder dh = LoaderFactory.getData(file.getAbsolutePath());
String[] names = dh.getNames();
String unitName = unitMap.get(pathName);
assertEquals(unitName, names[0]);
assertEquals("Column_0", names[1]);
}
}
}
}
|
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 cbdb801f3..6cc477029 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,1598 +1,1598 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui.views;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
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.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
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.TreeViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.mylar.core.MylarStatusHandler;
import org.eclipse.mylar.internal.tasks.ui.AbstractTaskListFilter;
import org.eclipse.mylar.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylar.internal.tasks.ui.TaskArchiveFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskCompletionFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskListColorsAndFonts;
import org.eclipse.mylar.internal.tasks.ui.TaskListPatternFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskListPreferenceConstants;
import org.eclipse.mylar.internal.tasks.ui.TaskPriorityFilter;
import org.eclipse.mylar.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylar.internal.tasks.ui.actions.CollapseAllAction;
import org.eclipse.mylar.internal.tasks.ui.actions.CopyTaskDetailsAction;
import org.eclipse.mylar.internal.tasks.ui.actions.DeleteAction;
import org.eclipse.mylar.internal.tasks.ui.actions.ExpandAllAction;
import org.eclipse.mylar.internal.tasks.ui.actions.FilterArchiveContainerAction;
import org.eclipse.mylar.internal.tasks.ui.actions.FilterCompletedTasksAction;
import org.eclipse.mylar.internal.tasks.ui.actions.GoIntoAction;
import org.eclipse.mylar.internal.tasks.ui.actions.GoUpAction;
import org.eclipse.mylar.internal.tasks.ui.actions.MarkTaskCompleteAction;
import org.eclipse.mylar.internal.tasks.ui.actions.MarkTaskIncompleteAction;
import org.eclipse.mylar.internal.tasks.ui.actions.NewLocalTaskAction;
import org.eclipse.mylar.internal.tasks.ui.actions.OpenTaskListElementAction;
import org.eclipse.mylar.internal.tasks.ui.actions.OpenTasksUiPreferencesAction;
import org.eclipse.mylar.internal.tasks.ui.actions.OpenWithBrowserAction;
import org.eclipse.mylar.internal.tasks.ui.actions.PresentationDropDownSelectionAction;
import org.eclipse.mylar.internal.tasks.ui.actions.PreviousTaskDropDownAction;
import org.eclipse.mylar.internal.tasks.ui.actions.RemoveFromCategoryAction;
import org.eclipse.mylar.internal.tasks.ui.actions.RenameAction;
import org.eclipse.mylar.internal.tasks.ui.actions.SynchronizeAutomaticallyAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskActivateAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskDeactivateAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskListElementPropertiesAction;
import org.eclipse.mylar.tasks.core.AbstractQueryHit;
import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.AbstractTaskContainer;
import org.eclipse.mylar.tasks.core.DateRangeContainer;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.ITaskActivityListener;
import org.eclipse.mylar.tasks.core.ITaskListChangeListener;
import org.eclipse.mylar.tasks.core.ITaskListElement;
import org.eclipse.mylar.tasks.core.Task;
import org.eclipse.mylar.tasks.core.TaskArchive;
import org.eclipse.mylar.tasks.core.TaskCategory;
import org.eclipse.mylar.tasks.ui.TaskTransfer;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.mylar.tasks.ui.TasksUiUtil;
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.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.Rectangle;
import org.eclipse.swt.graphics.Region;
import org.eclipse.swt.widgets.Composite;
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.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.themes.IThemeManager;
/**
* @author Mik Kersten
* @author Ken Sueda
*/
public class TaskListView extends ViewPart {
private static final String PRESENTATION_SCHEDULED = "Scheduled";
public static final String ID = "org.eclipse.mylar.tasks.ui.views.TaskListView";
public static final String LABEL_VIEW = "Task List";
private static final String MEMENTO_KEY_SORT_DIRECTION = "sortDirection";
private static final String MEMENTO_KEY_SORTER = "sorter";
private static final String MEMENTO_KEY_SORT_INDEX = "sortIndex";
private static final String ID_SEPARATOR_NEW = "new";
private static final String ID_SEPARATOR_CONTEXT = "context";
private static final String ID_SEPARATOR_TASKS = "tasks";
private static final String ID_SEPARATOR_NAVIGATION = "navigation";
private static final String ID_SEPARATOR_FILTERS = "filters";
private static final String ID_SEPARATOR_REPOSITORY = "repository";
private static final String LABEL_NO_TASKS = "no task active";
static final String[] PRIORITY_LEVELS = { Task.PriorityLevel.P1.toString(), Task.PriorityLevel.P2.toString(),
Task.PriorityLevel.P3.toString(), Task.PriorityLevel.P4.toString(), Task.PriorityLevel.P5.toString() };
public static final String[] PRIORITY_LEVEL_DESCRIPTIONS = { Task.PriorityLevel.P1.getDescription(),
Task.PriorityLevel.P2.getDescription(), Task.PriorityLevel.P3.getDescription(),
Task.PriorityLevel.P4.getDescription(), Task.PriorityLevel.P5.getDescription() };
private static final String PART_NAME = "Task List";
private boolean focusedMode = false;
private 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 TaskListElementPropertiesAction propertiesAction;
private OpenWithBrowserAction openWithBrowser;
private NewLocalTaskAction newLocalTaskAction;
private RenameAction renameAction;
private CollapseAllAction collapseAll;
private ExpandAllAction expandAll;
private DeleteAction deleteAction;
private RemoveFromCategoryAction removeFromCategoryAction;
private TaskActivateAction activateAction = new TaskActivateAction();
private TaskDeactivateAction deactivateAction = new TaskDeactivateAction();
private FilterCompletedTasksAction filterCompleteTask;
private SynchronizeAutomaticallyAction synchronizeAutomatically;
private OpenTasksUiPreferencesAction openPreferencesAction;
private FilterArchiveContainerAction filterArchiveCategory;
private PriorityDropDownAction filterOnPriority;
PreviousTaskDropDownAction previousTaskAction;
private PresentationDropDownSelectionAction presentationDropDownSelectionAction;
static TaskPriorityFilter FILTER_PRIORITY = new TaskPriorityFilter();
private static TaskCompletionFilter FILTER_COMPLETE = new TaskCompletionFilter();
private static TaskArchiveFilter FILTER_ARCHIVE = new TaskArchiveFilter();
private Set<AbstractTaskListFilter> filters = new HashSet<AbstractTaskListFilter>();
protected String[] columnNames = new String[] { "Summary", " " };
protected int[] columnWidths = new int[] { 200, 29 };
private TreeColumn[] columns;
private IMemento taskListMemento;
public static final String columnWidthIdentifier = "org.eclipse.mylar.tasklist.ui.views.tasklist.columnwidth";
public static final String tableSortIdentifier = "org.eclipse.mylar.tasklist.ui.views.tasklist.sortIndex";
private static final int DEFAULT_SORT_DIRECTION = 1;
private int sortIndex = 0;
private ITaskListPresentation currentPresentation;
private TaskListTableLabelProvider taskListTableLabelProvider;
private TaskListTableSorter tableSorter;
int sortDirection = DEFAULT_SORT_DIRECTION;
private Color categoryGradientStart;
private Color categoryGradientEnd;
private final static int MAX_SELECTION_HISTORY_SIZE = 10;
private LinkedHashMap<String, IStructuredSelection> lastSelectionByTaskHandle = new LinkedHashMap<String, IStructuredSelection>(
MAX_SELECTION_HISTORY_SIZE);
private ITaskListPresentation catagorizedPresentation = new ITaskListPresentation() {
public IStructuredContentProvider getContentProvider() {
return new TaskListContentProvider(TaskListView.this);
}
public String getPresentationName() {
return "Categorized";
}
public ImageDescriptor getImageDescriptor() {
return TasksUiImages.CATEGORY;
}
};
// TODO: Use extension point
private ITaskListPresentation scheduledPresentation = new ITaskListPresentation() {
public IStructuredContentProvider getContentProvider() {
return new TaskScheduleContentProvider(TaskListView.this, TasksUiPlugin.getTaskListManager());
}
public String getPresentationName() {
return PRESENTATION_SCHEDULED;
}
public ImageDescriptor getImageDescriptor() {
return TasksUiImages.CALENDAR;
}
};
/**
* True if the view should indicate that interaction monitoring is paused
*/
protected boolean isPaused = false;
private final Listener CATEGORY_GRADIENT_DRAWER = new Listener() {
public void handleEvent(Event event) {
if (event.item.getData() instanceof AbstractTaskContainer) {
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 Color(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 ITaskActivityListener() {
public void taskActivated(final ITask task) {
if (task != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
updateDescription(task);
selectedAndFocusTask(task);
filteredTree.indicateActiveTask(task);
}
});
}
}
public void tasksActivated(List<ITask> tasks) {
if (tasks.size() == 1) {
taskActivated(tasks.get(0));
}
}
public void taskDeactivated(final ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(task);
updateDescription(null);
filteredTree.indicateNoActiveTask();
}
});
}
public void activityChanged(DateRangeContainer week) {
// ignore
}
public void taskListRead() {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(null);
}
});
}
public void calendarChanged() {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(null);
}
});
}
};
private final ITaskListChangeListener TASK_REFERESH_LISTENER = new ITaskListChangeListener() {
public void localInfoChanged(final ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (getCurrentPresentation().getPresentationName().equals(
scheduledPresentation.getPresentationName())) {
refresh(null);
} else {
refresh(task);
}
}
});
if (task.isActive()) {
String activeTaskLabel = filteredTree.getActiveTaskLabelText();
if (activeTaskLabel != null && !activeTaskLabel.equals(task.getSummary())) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
filteredTree.indicateActiveTask(task);
}
});
}
}
}
public void repositoryInfoChanged(ITask task) {
localInfoChanged(task);
}
public void taskMoved(final ITask task, final AbstractTaskContainer fromContainer,
final AbstractTaskContainer toContainer) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
// category might appear or disappear
refresh(null);
AbstractTaskContainer rootCategory = TasksUiPlugin.getTaskListManager().getTaskList()
.getRootCategory();
if (rootCategory.equals(fromContainer) || rootCategory.equals(toContainer)) {
refresh(null);
} else {
refresh(toContainer);
refresh(task);
refresh(fromContainer);
}
}
});
}
public void taskDeleted(ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(null);
}
});
}
public void containerAdded(AbstractTaskContainer container) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(null);
}
});
}
public void containerDeleted(AbstractTaskContainer container) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(null);
}
});
}
public void taskAdded(ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refresh(null);
}
});
}
public void containerInfoChanged(final AbstractTaskContainer container) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (container == null) {
// HACK: should be part of policy
getViewer().refresh(false);
} else if (container.equals(TasksUiPlugin.getTaskListManager().getTaskList().getRootCategory())) {
refresh(null);
} else {
refresh(container);
}
}
});
}
};
private final IPropertyChangeListener THEME_CHANGE_LISTENER = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME)
|| TaskListColorsAndFonts.isTaskListTheme(event.getProperty())) {
updateGradientColors();
taskListTableLabelProvider.setCategoryBackgroundColor(themeManager.getCurrentTheme().getColorRegistry()
.get(TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY));
getViewer().refresh();
}
}
};
private void updateGradientColors() {
categoryGradientStart = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_CATEGORY_GRADIENT_START);
categoryGradientEnd = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_CATEGORY_GRADIENT_END);
if (gradientListenerAdded == false && categoryGradientStart != null
&& !categoryGradientStart.equals(categoryGradientEnd)) {
getViewer().getTree().addListener(SWT.EraseItem, CATEGORY_GRADIENT_DRAWER);
gradientListenerAdded = true;
} else if (categoryGradientStart != null && categoryGradientStart.equals(categoryGradientEnd)) {
getViewer().getTree().removeListener(SWT.EraseItem, CATEGORY_GRADIENT_DRAWER);
gradientListenerAdded = false;
}
}
public static TaskListView getFromActivePerspective() {
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (activePage != null) {
IViewPart view = activePage.findView(ID);
if (view instanceof TaskListView) {
return (TaskListView) view;
}
}
return null;
}
public static TaskListView openInActivePerspective() {
try {
return (TaskListView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ID);
} catch (Exception e) {
return null;
}
}
public TaskListView() {
TasksUiPlugin.getTaskListManager().addActivityListener(TASK_ACTIVITY_LISTENER);
TasksUiPlugin.getTaskListManager().getTaskList().addChangeListener(TASK_REFERESH_LISTENER);
}
@Override
public void dispose() {
super.dispose();
TasksUiPlugin.getTaskListManager().getTaskList().removeChangeListener(TASK_REFERESH_LISTENER);
TasksUiPlugin.getTaskListManager().removeActivityListener(TASK_ACTIVITY_LISTENER);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
if (themeManager != null) {
themeManager.removePropertyChangeListener(THEME_CHANGE_LISTENER);
}
}
/**
* TODO: should be updated when view mode switches to fast and vice-versa
*/
private void updateDescription(ITask task) {
if (getSite() == null || getSite().getPage() == null)
return;
IViewReference reference = getSite().getPage().findViewReference(ID);
boolean shouldSetDescription = false;
if (reference != null && reference.isFastView()) {
shouldSetDescription = true;
}
if (task != null) {
setTitleToolTip(PART_NAME + " (" + task.getSummary() + ")");
if (shouldSetDescription) {
setContentDescription(task.getSummary());
} else {
setContentDescription("");
}
} else {
setTitleToolTip(PART_NAME);
if (shouldSetDescription) {
setContentDescription(LABEL_NO_TASKS);
} else {
setContentDescription("");
}
}
}
public void addTaskToHistory(ITask task) {
if (!TasksUiPlugin.getDefault().isMultipleActiveTasksMode()) {
TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
// nextTaskAction.setEnabled(taskHistory.hasNext());
// previousTaskAction.setEnabled(TasksUiPlugin.getTaskListManager().getTaskActivationHistory().hasPrevious());
}
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
init(site);
this.taskListMemento = memento;
}
@Override
public void saveState(IMemento memento) {
// IMemento colMemento = memento.createChild(columnWidthIdentifier);
// for (int i = 0; i < columnWidths.length; i++) {
// IMemento m = colMemento.createChild("col" + i);
// m.putInteger(MEMENTO_KEY_WIDTH, columnWidths[i]);
// }
IMemento sorter = memento.createChild(tableSortIdentifier);
IMemento m = sorter.createChild(MEMENTO_KEY_SORTER);
m.putInteger(MEMENTO_KEY_SORT_INDEX, sortIndex);
m.putInteger(MEMENTO_KEY_SORT_DIRECTION, sortDirection);
// TODO: move to task list save policy
///TasksUiPlugin.getTaskListManager().saveTaskList();
}
private void restoreState() {
if (taskListMemento != null) {
// IMemento taskListWidth =
// taskListMemento.getChild(columnWidthIdentifier);
// if (taskListWidth != null) {
// for (int i = 0; i < columnWidths.length - 1; i++) {
// IMemento m = taskListWidth.getChild("col" + i);
// if (m != null) {
// int width = m.getInteger(MEMENTO_KEY_WIDTH);
// columnWidths[i] = width;
// columns[i].setWidth(width);
// }
// }
// }
IMemento sorterMemento = taskListMemento.getChild(tableSortIdentifier);
if (sorterMemento != null) {
IMemento m = sorterMemento.getChild(MEMENTO_KEY_SORTER);
if (m != null) {
sortIndex = m.getInteger(MEMENTO_KEY_SORT_INDEX);
Integer sortDirInt = m.getInteger(MEMENTO_KEY_SORT_DIRECTION);
if (sortDirInt != null) {
sortDirection = sortDirInt.intValue();
}
} else {
sortIndex = 2;
sortDirection = DEFAULT_SORT_DIRECTION;
}
} else {
sortIndex = 2; // default priority
sortDirection = DEFAULT_SORT_DIRECTION;
}
if (sortIndex < 2) {
tableSorter.setColumn(columnNames[sortIndex]);
getViewer().refresh(false);
}
// getViewer().setSorter(new TaskListTableSorter(this,
// columnNames[sortIndex]));
}
addFilter(FILTER_PRIORITY);
// if (MylarTaskListPlugin.getDefault().isFilterInCompleteMode())
// MylarTaskListPlugin.getTaskListManager().getTaskList().addFilter(inCompleteFilter);
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TaskListPreferenceConstants.FILTER_COMPLETE_MODE))
addFilter(FILTER_COMPLETE);
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TaskListPreferenceConstants.FILTER_ARCHIVE_MODE))
addFilter(FILTER_ARCHIVE);
if (TasksUiPlugin.getDefault().isMultipleActiveTasksMode()) {
togglePreviousAction(false);
// toggleNextAction(false);
}
getViewer().refresh();
}
@Override
public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | /*SWT.H_SCROLL |*/ SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
getViewer().getTree().setHeaderVisible(false);
// getViewer().getTree().setLinesVisible(true);
getViewer().setUseHashlookup(true);
configureColumns(columnNames, columnWidths);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
taskListTableLabelProvider = new TaskListTableLabelProvider(new TaskElementLabelProvider(true), PlatformUI
.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground, this, true);
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(),
// PRIORITY_LEVEL_DESCRIPTIONS, SWT.READ_ONLY);
editors[1] = null;
// editors[2] = null;
// editors[2] = new CheckboxCellEditor();
getViewer().setCellEditors(editors);
getViewer().setCellModifier(taskListCellModifier);
tableSorter = new TaskListTableSorter(this, columnNames[sortIndex]);
getViewer().setSorter(tableSorter);
applyPresentation(catagorizedPresentation);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setInput(getViewSite());
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
TreeItem[] selected = getViewer().getTree().getSelection();
if (selected.length == 1) {
Object selectedObject = selected[0].getData();
if (selectedObject instanceof ITask || selectedObject instanceof AbstractQueryHit) {
- if (e.x < selected[0].getBounds(0).x + 10) {
+ if (e.x < selected[0].getBounds(0).x + 13 && e.x > selected[0].getBounds(0).x - 3) {
taskListCellModifier.toggleTaskActivation((ITaskListElement)selectedObject);
}
}
}
}
public void mouseUp(MouseEvent e) {
}
});
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDetailsAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
newLocalTaskAction.run();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char) e.keyCode) || Character.isDigit((char) e.keyCode)) {
String string = new Character((char) e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(renameAction, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
TaskListToolTipHandler taskListToolTipHandler = new TaskListToolTipHandler(getViewer().getControl().getShell());
taskListToolTipHandler.activateHoverHelp(getViewer().getControl());
// 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("");
updateGradientColors();
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
getSite().setSelectionProvider(getViewer());
}
public void applyPresentation(ITaskListPresentation presentation) {
try {
getViewer().getControl().setRedraw(false);
if (!filteredTree.getFilterControl().getText().equals("")) {
filteredTree.getFilterControl().setText("");
}
if (presentation.getPresentationName().equals(PRESENTATION_SCHEDULED)) {
TasksUiPlugin.getTaskListManager().parseFutureReminders();
}
getViewer().setContentProvider(presentation.getContentProvider());
refreshAndFocus(isFocusedMode());
currentPresentation = presentation;
} finally {
getViewer().getControl().setRedraw(true);
}
}
public ITaskListPresentation 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]));
}
final int index = i;
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sortIndex = index;
sortDirection *= DEFAULT_SORT_DIRECTION;
tableSorter.setColumn(columnNames[sortIndex]);
getViewer().refresh(false);
}
});
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
}
});
}
}
private void initDragAndDrop(Composite parent) {
Transfer[] dragTypes = new Transfer[] { TaskTransfer.getInstance(), TextTransfer.getInstance(),
FileTransfer.getInstance() };
Transfer[] dropTypes = new Transfer[] { TaskTransfer.getInstance(), TextTransfer.getInstance(),
FileTransfer.getInstance(), // PluginTransfer.getInstance(),
RTFTransfer.getInstance() };
getViewer().addDragSupport(DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK, dragTypes,
new TaskListDragSourceListener(this));
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() {
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
for (ITask t : activeTasks) {
getViewer().expandToLevel(t, 0);
}
}
});
}
private void hookContextMenu() {
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
TaskListView.this.fillContextMenu(manager);
}
});
Menu menu = menuManager.createContextMenu(getViewer().getControl());
getViewer().getControl().setMenu(menu);
getSite().registerContextMenu(menuManager, getViewer());
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
updateDrillDownActions();
manager.add(goUpAction);
manager.add(collapseAll);
manager.add(expandAll);
manager.add(new Separator(ID_SEPARATOR_FILTERS));
manager.add(filterOnPriority);
manager.add(filterCompleteTask);
manager.add(filterArchiveCategory);
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) {
filterOnPriority.updateCheckedState();
}
});
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(IMenuManager manager) {
updateDrillDownActions();
ITaskListElement element = null;
final Object firstSelectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (firstSelectedObject instanceof ITaskListElement) {
element = (ITaskListElement) firstSelectedObject;
}
List<ITaskListElement> selectedElements = new ArrayList<ITaskListElement>();
for (Iterator<?> i = ((IStructuredSelection) getViewer().getSelection()).iterator(); i.hasNext();) {
Object object = i.next();
if (object instanceof ITaskListElement) {
selectedElements.add((ITaskListElement) object);
}
}
ITask task = null;
if ((element instanceof ITask) || (element instanceof AbstractQueryHit)) {
if (element instanceof AbstractQueryHit) {
task = ((AbstractQueryHit) element).getCorrespondingTask();
} else {
task = (ITask) element;
}
}
manager.add(new Separator(ID_SEPARATOR_NEW));
manager.add(new Separator());
Map<String, List<IDynamicSubMenuContributor>> dynamicMenuMap = TasksUiPlugin.getDefault().getDynamicMenuMap();
if (!(element instanceof AbstractTaskContainer)) {
addAction(openAction, manager, element);
}
addAction(openWithBrowser, manager, element);
if (task != null) {
if (task.isActive()) {
manager.add(deactivateAction);
} else {
manager.add(activateAction);
}
} else if (element instanceof AbstractQueryHit) {
manager.add(activateAction);
}
manager.add(new Separator());
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);
}
}
}
}
manager.add(new Separator());
addAction(copyDetailsAction, manager, element);
if (task != null && !(element instanceof AbstractQueryHit)) {
addAction(removeFromCategoryAction, manager, element);
}
addAction(deleteAction, manager, element);
if (!(element instanceof AbstractRepositoryTask) || element instanceof AbstractTaskContainer) {
addAction(renameAction, manager, element);
}
if (element instanceof AbstractTaskContainer) {
manager.add(goIntoAction);
}
if (drilledIntoCategory != null) {
manager.add(goUpAction);
}
manager.add(new Separator(ID_SEPARATOR_REPOSITORY));
manager.add(new Separator(ID_SEPARATOR_CONTEXT));
if (element instanceof ITask || element instanceof AbstractQueryHit) {
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 AbstractRepositoryQuery || element instanceof TaskCategory) {
manager.add(new Separator());
addAction(propertiesAction, manager, element);
}
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void addMenuManager(IMenuManager menuToAdd, IMenuManager manager, ITaskListElement element) {
if ((element instanceof ITask || element instanceof AbstractQueryHit)
|| (element instanceof AbstractTaskContainer || element instanceof AbstractRepositoryQuery)) {
manager.add(menuToAdd);
}
}
private void addAction(Action action, IMenuManager manager, ITaskListElement element) {
manager.add(action);
if (element != null) {
// ITaskHandler handler =
// MylarTaskListPlugin.getDefault().getHandlerForElement(element);
// if (handler != null) {
// action.setEnabled(handler.enableAction(action, element));
// } else {
updateActionEnablement(action, element);
// }
}
}
/**
* Refactor out element
*/
private void updateActionEnablement(Action action, ITaskListElement element) {
if (element instanceof ITask) {
if (action instanceof OpenWithBrowserAction) {
if (((ITask) element).hasValidUrl()) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof DeleteAction) {
action.setEnabled(true);
} else if (action instanceof NewLocalTaskAction) {
action.setEnabled(false);
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyTaskDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
action.setEnabled(true);
}
} else if (element instanceof AbstractTaskContainer) {
if (action instanceof MarkTaskCompleteAction) {
action.setEnabled(false);
} else if (action instanceof MarkTaskIncompleteAction) {
action.setEnabled(false);
} else if (action instanceof DeleteAction) {
if (element instanceof TaskArchive)
action.setEnabled(false);
else
action.setEnabled(true);
} else if (action instanceof NewLocalTaskAction) {
if (element instanceof TaskArchive)
action.setEnabled(false);
else
action.setEnabled(true);
} else if (action instanceof GoIntoAction) {
TaskCategory cat = (TaskCategory) element;
if (cat.getChildren().size() > 0) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyTaskDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
if (element instanceof AbstractTaskContainer) {
AbstractTaskContainer container = (AbstractTaskContainer) element;
action.setEnabled(container.canRename());
}
// if (element instanceof TaskArchive)
// action.setEnabled(false);
// else
// action.setEnabled(true);
}
} else {
action.setEnabled(true);
}
// if(!canEnableGoInto){
// goIntoAction.setEnabled(false);
// }
}
private void makeActions() {
copyDetailsAction = new CopyTaskDetailsAction(true);
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());
propertiesAction = new TaskListElementPropertiesAction(this.getViewer());
openWithBrowser = new OpenWithBrowserAction();
filterCompleteTask = new FilterCompletedTasksAction(this);
synchronizeAutomatically = new SynchronizeAutomaticallyAction();
openPreferencesAction = new OpenTasksUiPreferencesAction();
filterArchiveCategory = new FilterArchiveContainerAction(this);
filterOnPriority = new PriorityDropDownAction(this);
previousTaskAction = new PreviousTaskDropDownAction(this, TasksUiPlugin.getTaskListManager()
.getTaskActivationHistory());
ITaskListPresentation[] presentations = { catagorizedPresentation, scheduledPresentation };
presentationDropDownSelectionAction = new PresentationDropDownSelectionAction(this, presentations);
filteredTree.getViewer().addSelectionChangedListener(openWithBrowser);
filteredTree.getViewer().addSelectionChangedListener(copyDetailsAction);
// openWithBrowser.selectionChanged((StructuredSelection)
// getViewer().getSelection());
// copyDetailsAction.selectionChanged((StructuredSelection)
// getViewer().getSelection());
//
}
// public void toggleNextAction(boolean enable) {
// nextTaskAction.setEnabled(enable);
// }
// public NextTaskDropDownAction getNextTaskAction() {
// return nextTaskAction;
// }
public void togglePreviousAction(boolean enable) {
previousTaskAction.setEnabled(enable);
}
public PreviousTaskDropDownAction getPreviousTaskAction() {
return previousTaskAction;
}
/**
* Recursive function that checks for the occurrence of a certain task
* taskId. All children of the supplied node will be checked.
*
* @param task
* The <code>ITask</code> object that is to be searched.
* @param taskId
* The taskId that is being searched for.
* @return <code>true</code> if the taskId was found in the node or any of
* its children
*/
protected boolean lookForId(String taskId) {
return (TasksUiPlugin.getTaskListManager().getTaskList().getTask(taskId) == null);
// for (ITask task :
// MylarTaskListPlugin.getTaskListManager().getTaskList().getRootTasks())
// {
// if (task.getHandle().equals(taskId)) {
// return true;
// }
// }
// for (TaskCategory cat :
// MylarTaskListPlugin.getTaskListManager().getTaskList().getTaskCategories())
// {
// for (ITask task : cat.getChildren()) {
// if (task.getHandle().equals(taskId)) {
// return true;
// }
// }
// }
// return false;
}
private void hookOpenAction() {
getViewer().addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
openAction.run();
}
});
getViewer().addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
StructuredSelection selection = (StructuredSelection) getViewer().getSelection();
Object object = selection.getFirstElement();
if (TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
TaskListPreferenceConstants.ACTIVATE_ON_OPEN)) {
ITask selectedTask = TaskListView.getFromActivePerspective().getSelectedTask();
if (selectedTask != null) {
// TODO: move history stuff
activateAction.run(selectedTask);
addTaskToHistory(selectedTask);
previousTaskAction.setButtonStatus();
}
}
if (object instanceof TaskCategory || object instanceof AbstractRepositoryQuery) {
TasksUiUtil.refreshAndOpenTaskListElement((ITaskListElement) object);
// if(getViewer().getExpandedState(object)){
// getViewer().collapseToLevel(object,
// TreeViewer.ALL_LEVELS);
// } else {
// getViewer().expandToLevel(object, TreeViewer.ALL_LEVELS);
// }
}
}
});
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
filteredTree.getViewer().getControl().setFocus();
}
public String getBugIdFromUser() {
InputDialog dialog = new InputDialog(getSite().getWorkbenchWindow().getShell(), "Enter Bugzilla ID",
"Enter the Bugzilla ID: ", "", null);
int dialogResult = dialog.open();
if (dialogResult == Window.OK) {
return dialog.getValue();
} else {
return null;
}
}
public void refreshAndFocus(boolean expand) {
refresh(null);
if (expand) {
getViewer().expandAll();
}
selectedAndFocusTask(TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask());
}
public TreeViewer getViewer() {
return filteredTree.getViewer();
}
public TaskCompletionFilter getCompleteFilter() {
return FILTER_COMPLETE;
}
public TaskPriorityFilter getPriorityFilter() {
return FILTER_PRIORITY;
}
public void addFilter(AbstractTaskListFilter filter) {
if (!filters.contains(filter)) {
filters.add(filter);
}
}
public void clearFilters(boolean preserveArchiveFilter) {
filters.clear();
if (preserveArchiveFilter) {
filters.add(FILTER_ARCHIVE);
}
}
public void removeFilter(AbstractTaskListFilter filter) {
filters.remove(filter);
}
public void updateDrillDownActions() {
if (drillDownAdapter.canGoBack()) {
goUpAction.setEnabled(true);
} else {
goUpAction.setEnabled(false);
}
}
boolean isInRenameAction = false;
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 AbstractTaskContainer) {
drilledIntoCategory = (AbstractTaskContainer) element;
drillDownAdapter.goInto();
IActionBars bars = getViewSite().getActionBars();
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 ITask getSelectedTask() {
ISelection selection = getViewer().getSelection();
if (selection.isEmpty())
return null;
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (ITask) structuredSelection.getFirstElement();
} else if (element instanceof AbstractQueryHit) {
return ((AbstractQueryHit) element).getOrCreateCorrespondingTask();
}
}
return null;
}
public static ITask getSelectedTask(ISelection selection) {
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
if (structuredSelection.size() != 1) {
return null;
}
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (ITask) structuredSelection.getFirstElement();
} else if (element instanceof AbstractQueryHit) {
return ((AbstractQueryHit) element).getCorrespondingTask();
}
}
return null;
}
public void indicatePaused(boolean paused) {
isPaused = paused;
IStatusLineManager statusLineManager = getViewSite().getActionBars().getStatusLineManager();
if (isPaused) {
statusLineManager
.setMessage(TasksUiImages.getImage(TasksUiImages.TASKLIST), "Mylar 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);
// if no task exists, select the query hit if exists
AbstractQueryHit hit = null;
if (getViewer().getSelection().isEmpty()
&& (hit = TasksUiPlugin.getTaskListManager().getTaskList().getQueryHit(task.getHandleIdentifier())) != null) {
try {
AbstractRepositoryQuery query = TasksUiPlugin.getTaskListManager().getTaskList().getQueryForHandle(
task.getHandleIdentifier());
getViewer().expandToLevel(query, 1);
getViewer().setSelection(new StructuredSelection(hit), true);
} catch (SWTException e) {
MylarStatusHandler.log(e, "Failed to expand Task List");
}
}
}
private void saveSelection() {
IStructuredSelection selection = (IStructuredSelection) getViewer().getSelection();
if (!selection.isEmpty()) {
if (selection.getFirstElement() instanceof ITaskListElement) {
// make sure the new selection is inserted at the end of the
// list
String handle = ((ITaskListElement) selection.getFirstElement()).getHandleIdentifier();
lastSelectionByTaskHandle.remove(handle);
lastSelectionByTaskHandle.put(handle, selection);
if (lastSelectionByTaskHandle.size() > MAX_SELECTION_HISTORY_SIZE) {
Iterator<String> it = lastSelectionByTaskHandle.keySet().iterator();
it.next();
it.remove();
}
}
}
}
private IStructuredSelection restoreSelection(ITaskListElement task) {
IStructuredSelection selection = lastSelectionByTaskHandle.get(task.getHandleIdentifier());
if (selection != null) {
return selection;
} else {
return new StructuredSelection(task);
}
}
/**
* Encapsulates refresh policy.
*/
private void refresh(final ITaskListElement element) {
if (getViewer().getControl() != null && !getViewer().getControl().isDisposed()) {
if (element == null) {
try {
// getViewer().getControl().setRedraw(false);
getViewer().refresh(true);
} finally {
// getViewer().getControl().setRedraw(true);
}
} else {
try {
if (element instanceof ITask) {
ITask task = (ITask) element;
AbstractTaskContainer rootCategory = TasksUiPlugin.getTaskListManager().getTaskList()
.getRootCategory();
Set<AbstractRepositoryQuery> queries = TasksUiPlugin.getTaskListManager().getTaskList()
.getQueriesForHandle(task.getHandleIdentifier());
if (task.getContainer() == null || task.getContainer().equals(rootCategory)
|| (task instanceof AbstractRepositoryTask && queries.isEmpty())) {
// || task.getContainer() instanceof TaskArchive) {
refresh(null);
} else {
getViewer().refresh(task.getContainer(), true);
// refresh(task.getContainer());
}
AbstractQueryHit hit = TasksUiPlugin.getTaskListManager().getTaskList().getQueryHit(
task.getHandleIdentifier());
if (hit != null) {
refresh(hit);
}
} else if (element instanceof AbstractQueryHit) {
AbstractQueryHit hit = (AbstractQueryHit) element;
Set<AbstractRepositoryQuery> queries = TasksUiPlugin.getTaskListManager().getTaskList()
.getQueriesForHandle(hit.getHandleIdentifier());
for (AbstractRepositoryQuery query : queries) {
refresh(query);
}
} else if (element instanceof AbstractTaskContainer) {
// check if the container should appear or disappear
// List<?> visibleElements =
// Arrays.asList(getViewer().getVisibleExpandedElements());
// boolean containerVisible =
// visibleElements.contains(element);
// AbstractTaskContainer container =
// (AbstractTaskContainer) element;
// boolean refreshRoot = false;
// if (refreshRoot) {
// getViewer().refresh();
// } else {
// refresh(element);
getViewer().refresh(element, true);
// }
} else {
// getViewer().refresh(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer());
getViewer().refresh(element, true);
// if (element instanceof AbstractTaskContainer
// && !((AbstractTaskContainer)
// element).equals(TasksUiPlugin.getTaskListManager()
// .getTaskList().getArchiveContainer())) {
// List<?> visibleElements =
// Arrays.asList(getViewer().getVisibleExpandedElements());
// if (!visibleElements.contains(element)) {
// getViewer().refresh();
// // refresh(null);
// }
// }
}
} catch (SWTException e) {
MylarStatusHandler.log(e, "Failed to refresh Task List");
}
}
}
}
public Image[] getPirorityImages() {
Image[] images = new Image[Task.PriorityLevel.values().length];
for (int i = 0; i < Task.PriorityLevel.values().length; i++) {
images[i] = TasksUiUtil.getImageForPriority(Task.PriorityLevel.values()[i]);
}
return images;
}
public Set<AbstractTaskListFilter> getFilters() {
return filters;
}
public static String getCurrentPriorityLevel() {
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TaskListPreferenceConstants.SELECTED_PRIORITY)) {
return TasksUiPlugin.getDefault().getPreferenceStore().getString(
TaskListPreferenceConstants.SELECTED_PRIORITY);
} else {
return Task.PriorityLevel.P5.toString();
}
}
public TaskArchiveFilter getArchiveFilter() {
return FILTER_ARCHIVE;
}
public void setManualFiltersEnabled(boolean enabled) {
filterOnPriority.setEnabled(enabled);
filterCompleteTask.setEnabled(enabled);
filterArchiveCategory.setEnabled(enabled);
}
public boolean isFocusedMode() {
return focusedMode;
}
public void setFocusedMode(boolean focusedMode) {
this.focusedMode = focusedMode;
}
}
| 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());
getViewer().getTree().setHeaderVisible(false);
// getViewer().getTree().setLinesVisible(true);
getViewer().setUseHashlookup(true);
configureColumns(columnNames, columnWidths);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
taskListTableLabelProvider = new TaskListTableLabelProvider(new TaskElementLabelProvider(true), PlatformUI
.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground, this, true);
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(),
// PRIORITY_LEVEL_DESCRIPTIONS, SWT.READ_ONLY);
editors[1] = null;
// editors[2] = null;
// editors[2] = new CheckboxCellEditor();
getViewer().setCellEditors(editors);
getViewer().setCellModifier(taskListCellModifier);
tableSorter = new TaskListTableSorter(this, columnNames[sortIndex]);
getViewer().setSorter(tableSorter);
applyPresentation(catagorizedPresentation);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setInput(getViewSite());
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
TreeItem[] selected = getViewer().getTree().getSelection();
if (selected.length == 1) {
Object selectedObject = selected[0].getData();
if (selectedObject instanceof ITask || selectedObject instanceof AbstractQueryHit) {
if (e.x < selected[0].getBounds(0).x + 10) {
taskListCellModifier.toggleTaskActivation((ITaskListElement)selectedObject);
}
}
}
}
public void mouseUp(MouseEvent e) {
}
});
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDetailsAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
newLocalTaskAction.run();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char) e.keyCode) || Character.isDigit((char) e.keyCode)) {
String string = new Character((char) e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(renameAction, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
TaskListToolTipHandler taskListToolTipHandler = new TaskListToolTipHandler(getViewer().getControl().getShell());
taskListToolTipHandler.activateHoverHelp(getViewer().getControl());
// 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("");
updateGradientColors();
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
getSite().setSelectionProvider(getViewer());
}
| public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | /*SWT.H_SCROLL |*/ SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
getViewer().getTree().setHeaderVisible(false);
// getViewer().getTree().setLinesVisible(true);
getViewer().setUseHashlookup(true);
configureColumns(columnNames, columnWidths);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
taskListTableLabelProvider = new TaskListTableLabelProvider(new TaskElementLabelProvider(true), PlatformUI
.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground, this, true);
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(),
// PRIORITY_LEVEL_DESCRIPTIONS, SWT.READ_ONLY);
editors[1] = null;
// editors[2] = null;
// editors[2] = new CheckboxCellEditor();
getViewer().setCellEditors(editors);
getViewer().setCellModifier(taskListCellModifier);
tableSorter = new TaskListTableSorter(this, columnNames[sortIndex]);
getViewer().setSorter(tableSorter);
applyPresentation(catagorizedPresentation);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setInput(getViewSite());
getViewer().getTree().addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
TreeItem[] selected = getViewer().getTree().getSelection();
if (selected.length == 1) {
Object selectedObject = selected[0].getData();
if (selectedObject instanceof ITask || selectedObject instanceof AbstractQueryHit) {
if (e.x < selected[0].getBounds(0).x + 13 && e.x > selected[0].getBounds(0).x - 3) {
taskListCellModifier.toggleTaskActivation((ITaskListElement)selectedObject);
}
}
}
}
public void mouseUp(MouseEvent e) {
}
});
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDetailsAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
newLocalTaskAction.run();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char) e.keyCode) || Character.isDigit((char) e.keyCode)) {
String string = new Character((char) e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(renameAction, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
TaskListToolTipHandler taskListToolTipHandler = new TaskListToolTipHandler(getViewer().getControl().getShell());
taskListToolTipHandler.activateHoverHelp(getViewer().getControl());
// 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("");
updateGradientColors();
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
getSite().setSelectionProvider(getViewer());
}
|
diff --git a/pdisk-server/war/src/main/java/eu/stratuslab/storage/disk/utils/ProcessUtils.java b/pdisk-server/war/src/main/java/eu/stratuslab/storage/disk/utils/ProcessUtils.java
index b207e79..3b6ea15 100644
--- a/pdisk-server/war/src/main/java/eu/stratuslab/storage/disk/utils/ProcessUtils.java
+++ b/pdisk-server/war/src/main/java/eu/stratuslab/storage/disk/utils/ProcessUtils.java
@@ -1,54 +1,54 @@
package eu.stratuslab.storage.disk.utils;
import java.io.File;
import java.io.IOException;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import eu.stratuslab.storage.disk.main.PersistentDiskApplication;
public class ProcessUtils {
public static Boolean isExecutable(String filename) {
File exec = new File(filename);
return isExecutable(exec);
}
public static Boolean isExecutable(File exec) {
return exec.isFile() && exec.canExecute();
}
public static void execute(ProcessBuilder pb, String errorMsg) {
int returnCode = 1;
Process process;
try {
process = pb.start();
boolean blocked = true;
while (blocked) {
process.waitFor();
blocked = false;
}
returnCode = process.exitValue();
} catch (IOException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occurred while executing command: "
+ PersistentDiskApplication.join(pb.command(), " ")
- + "\n" + errorMsg + ".");
+ + ".\n" + errorMsg + ".");
} catch (InterruptedException consumed) {
// Just continue with the loop.
}
if (returnCode != 0) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occurred while executing command: "
+ PersistentDiskApplication.join(pb.command(), " ")
- + "\n" + errorMsg + ".\nReturn code was: "
+ + ".\n" + errorMsg + ".\nReturn code was: "
+ String.valueOf(returnCode));
}
}
}
| false | true | public static void execute(ProcessBuilder pb, String errorMsg) {
int returnCode = 1;
Process process;
try {
process = pb.start();
boolean blocked = true;
while (blocked) {
process.waitFor();
blocked = false;
}
returnCode = process.exitValue();
} catch (IOException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occurred while executing command: "
+ PersistentDiskApplication.join(pb.command(), " ")
+ "\n" + errorMsg + ".");
} catch (InterruptedException consumed) {
// Just continue with the loop.
}
if (returnCode != 0) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occurred while executing command: "
+ PersistentDiskApplication.join(pb.command(), " ")
+ "\n" + errorMsg + ".\nReturn code was: "
+ String.valueOf(returnCode));
}
}
| public static void execute(ProcessBuilder pb, String errorMsg) {
int returnCode = 1;
Process process;
try {
process = pb.start();
boolean blocked = true;
while (blocked) {
process.waitFor();
blocked = false;
}
returnCode = process.exitValue();
} catch (IOException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occurred while executing command: "
+ PersistentDiskApplication.join(pb.command(), " ")
+ ".\n" + errorMsg + ".");
} catch (InterruptedException consumed) {
// Just continue with the loop.
}
if (returnCode != 0) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occurred while executing command: "
+ PersistentDiskApplication.join(pb.command(), " ")
+ ".\n" + errorMsg + ".\nReturn code was: "
+ String.valueOf(returnCode));
}
}
|
diff --git a/javarmi/StockExClient/src/stockexclient/InteractionManager.java b/javarmi/StockExClient/src/stockexclient/InteractionManager.java
index 90078fe..4583025 100644
--- a/javarmi/StockExClient/src/stockexclient/InteractionManager.java
+++ b/javarmi/StockExClient/src/stockexclient/InteractionManager.java
@@ -1,389 +1,392 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stockexclient;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Scanner;
import stockEx.Client;
import stockEx.IAuthentication;
import stockEx.IStockQuery;
import stockEx.Stock;
/**
*
* @author Kuntal
*/
public class InteractionManager
{
private Scanner scanIn;
private IStockQuery stockQuery;
private IAuthentication authentication;
private Client client;
private boolean isAdmin;
private void printloginMessage()
{
System.out.println("Please log in before you send the request.");
}
private void printMessage(String message)
{
System.out.println(message);
}
/**
*
* @return client type
*/
private boolean isLoggedIn()
{
return client != null;
}
/**
*
* @param commandName
*/
private void printWarning(String commandName)
{
System.out.print("Invalid parameters or Invalid command '" + commandName);
System.out.println("'. Use help for syntax.");
}
/**
*
* @param stockQuery
* @param auth
* @param isAdmin
*/
public InteractionManager(IStockQuery stockQuery, IAuthentication auth, boolean isAdmin)
{
this.isAdmin = isAdmin;
this.stockQuery = stockQuery;
this.authentication = auth;
System.out.println("------------------------------------------------------");
System.out.println("| Welcome to dypen Stock Exchange |");
System.out.println("------------------------------------------------------");
System.out.println("");
}
/**
*
* @throws RemoteException
*/
public void init() throws RemoteException
{
String command;
int quantity = 0;
String[] commandString;
boolean isExit = false;
do
{
System.out.println(isLoggedIn() ? client.getUsername() + " >" : " >");
command = getInput();
commandString = command.split(" ");
switch (commandString[0])
{
case "query":
if (isLoggedIn())
{
if (commandString.length == 2)
{
try
{
System.out.println(stockQuery.query(client, commandString[1]));
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "list":
if (isLoggedIn())
{
if (commandString.length == 1 && !client.isAdmin())
{
List<Stock> list = stockQuery.list(client);
if (list.size() > 0)
{
for (Stock stock : list)
{
System.out.println(stock);
}
}
else
{
printMessage("No records found.");
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "buy":
if (isLoggedIn())
{
if (commandString.length == 3 && !client.isAdmin())
{
try
{
quantity = getInteger(commandString[2]);
if (quantity > 0)
{
client = stockQuery.buy(client, commandString[1], quantity);
System.out.println(Integer.toString(quantity) + " " + commandString[1] + " bought.");
System.out.println(" Your current balance is $" + client.getBalance() + " .");
}
else
{
System.out.println("Enter quantity greater than zero.");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "sell":
if (isLoggedIn())
{
if (commandString.length == 3 && !client.isAdmin())
{
try
{
quantity = getInteger(commandString[2]);
if (quantity > 0)
{
stockQuery.sell(client, commandString[1], quantity);
System.out.println(Integer.toString(quantity) + " " + commandString[1] + " sold.");
System.out.println(" Your current balance is $" + client.getBalance() + " .");
}
else
{
System.out.println("Enter quantity great than zero.");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "update":
if (isLoggedIn())
{
if (commandString.length == 3 && client.isAdmin())
{
try
{
double price = getInputAmount(commandString[2]);
if (price > 0)
{
stockQuery.update(client, commandString[1], price);
System.out.println("Price of " + commandString[1] + " updated to " + price + " .");
}
else
{
System.out.println("Enter price greater than zero");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "user":
if (commandString.length == 2)
{
client = authentication.init(commandString[1], isAdmin);
- printMessage("Your Balance is :" + client.getBalance());
+ if (!client.isAdmin())
+ {
+ printMessage("Your Balance is :" + client.getBalance());
+ }
}
else
{
printWarning(commandString[0]);
}
break;
case "help":
if (commandString.length == 1)
{
printPrompt();
}
break;
case "quit":
client = null;
isExit = true;
break;
default:
printWarning(commandString[0]);
break;
}
}
while (!isExit);
}
public void printPrompt()
{
System.out.println("-----------------------------------------------");
System.out.println("| COMMANDS |");
System.out.println("-----------------------------------------------");
System.out.println("| user <user name> |");
System.out.println("| Eg. user johnsmith |");
System.out.println("| |");
if (isLoggedIn())
{
System.out.println("| query <ticker name> |");
System.out.println("| Eg. query goog |");
System.out.println("| |");
if (!client.isAdmin())
{
System.out.println("| buy <ticker name> <quantity> |");
System.out.println("| Eg. buy goog 10 |");
System.out.println("| |");
System.out.println("| sell <ticker name> <quantity> |");
System.out.println("| Eg. sell goog 10 |");
System.out.println("| |");
System.out.println("| list |");
}
else
{
System.out.println("| update <ticker name> <price> |");
System.out.println("| Eg. update goog 999.99 |");
}
System.out.println("| |");
System.out.println("| quit |");
}
System.out.println("-----------------------------------------------");
}
/**
*
* @return command string
*/
private String getInput()
{
scanIn = new Scanner(System.in);
String input = scanIn.nextLine().trim().toLowerCase();
return input;
}
/**
*
* @param bal <p/>
* @return balance in double format
* <p/>
* @throws NumberFormatException
*/
private double getInputAmount(String bal) throws NumberFormatException
{
//check if a valid decimal
if (!bal.matches("^\\d+$|^[.]?\\d{1,2}$|^\\d+[.]?\\d{1,2}$"))
{
throw new NumberFormatException("Invalid entry");
}
return Double.valueOf(bal);
}
/**
*
* @param strInt <p/>
* @return string in integer format
* <p/>
* @throws NumberFormatException
*/
private int getInteger(String strInt) throws NumberFormatException
{
//check if a valid decimal
if (!strInt.matches("^[0-9]+$"))
{
throw new NumberFormatException("Invalid entry");
}
return Integer.valueOf(strInt);
}
}
| true | true | public void init() throws RemoteException
{
String command;
int quantity = 0;
String[] commandString;
boolean isExit = false;
do
{
System.out.println(isLoggedIn() ? client.getUsername() + " >" : " >");
command = getInput();
commandString = command.split(" ");
switch (commandString[0])
{
case "query":
if (isLoggedIn())
{
if (commandString.length == 2)
{
try
{
System.out.println(stockQuery.query(client, commandString[1]));
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "list":
if (isLoggedIn())
{
if (commandString.length == 1 && !client.isAdmin())
{
List<Stock> list = stockQuery.list(client);
if (list.size() > 0)
{
for (Stock stock : list)
{
System.out.println(stock);
}
}
else
{
printMessage("No records found.");
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "buy":
if (isLoggedIn())
{
if (commandString.length == 3 && !client.isAdmin())
{
try
{
quantity = getInteger(commandString[2]);
if (quantity > 0)
{
client = stockQuery.buy(client, commandString[1], quantity);
System.out.println(Integer.toString(quantity) + " " + commandString[1] + " bought.");
System.out.println(" Your current balance is $" + client.getBalance() + " .");
}
else
{
System.out.println("Enter quantity greater than zero.");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "sell":
if (isLoggedIn())
{
if (commandString.length == 3 && !client.isAdmin())
{
try
{
quantity = getInteger(commandString[2]);
if (quantity > 0)
{
stockQuery.sell(client, commandString[1], quantity);
System.out.println(Integer.toString(quantity) + " " + commandString[1] + " sold.");
System.out.println(" Your current balance is $" + client.getBalance() + " .");
}
else
{
System.out.println("Enter quantity great than zero.");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "update":
if (isLoggedIn())
{
if (commandString.length == 3 && client.isAdmin())
{
try
{
double price = getInputAmount(commandString[2]);
if (price > 0)
{
stockQuery.update(client, commandString[1], price);
System.out.println("Price of " + commandString[1] + " updated to " + price + " .");
}
else
{
System.out.println("Enter price greater than zero");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "user":
if (commandString.length == 2)
{
client = authentication.init(commandString[1], isAdmin);
printMessage("Your Balance is :" + client.getBalance());
}
else
{
printWarning(commandString[0]);
}
break;
case "help":
if (commandString.length == 1)
{
printPrompt();
}
break;
case "quit":
client = null;
isExit = true;
break;
default:
printWarning(commandString[0]);
break;
}
}
while (!isExit);
}
| public void init() throws RemoteException
{
String command;
int quantity = 0;
String[] commandString;
boolean isExit = false;
do
{
System.out.println(isLoggedIn() ? client.getUsername() + " >" : " >");
command = getInput();
commandString = command.split(" ");
switch (commandString[0])
{
case "query":
if (isLoggedIn())
{
if (commandString.length == 2)
{
try
{
System.out.println(stockQuery.query(client, commandString[1]));
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "list":
if (isLoggedIn())
{
if (commandString.length == 1 && !client.isAdmin())
{
List<Stock> list = stockQuery.list(client);
if (list.size() > 0)
{
for (Stock stock : list)
{
System.out.println(stock);
}
}
else
{
printMessage("No records found.");
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "buy":
if (isLoggedIn())
{
if (commandString.length == 3 && !client.isAdmin())
{
try
{
quantity = getInteger(commandString[2]);
if (quantity > 0)
{
client = stockQuery.buy(client, commandString[1], quantity);
System.out.println(Integer.toString(quantity) + " " + commandString[1] + " bought.");
System.out.println(" Your current balance is $" + client.getBalance() + " .");
}
else
{
System.out.println("Enter quantity greater than zero.");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "sell":
if (isLoggedIn())
{
if (commandString.length == 3 && !client.isAdmin())
{
try
{
quantity = getInteger(commandString[2]);
if (quantity > 0)
{
stockQuery.sell(client, commandString[1], quantity);
System.out.println(Integer.toString(quantity) + " " + commandString[1] + " sold.");
System.out.println(" Your current balance is $" + client.getBalance() + " .");
}
else
{
System.out.println("Enter quantity great than zero.");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "update":
if (isLoggedIn())
{
if (commandString.length == 3 && client.isAdmin())
{
try
{
double price = getInputAmount(commandString[2]);
if (price > 0)
{
stockQuery.update(client, commandString[1], price);
System.out.println("Price of " + commandString[1] + " updated to " + price + " .");
}
else
{
System.out.println("Enter price greater than zero");
}
}
catch (NumberFormatException ne)
{
printWarning(commandString[0]);
}
catch (Exception ex)
{
printMessage(ex.getMessage());
}
}
else
{
printWarning(commandString[0]);
}
}
else
{
printloginMessage();
}
break;
case "user":
if (commandString.length == 2)
{
client = authentication.init(commandString[1], isAdmin);
if (!client.isAdmin())
{
printMessage("Your Balance is :" + client.getBalance());
}
}
else
{
printWarning(commandString[0]);
}
break;
case "help":
if (commandString.length == 1)
{
printPrompt();
}
break;
case "quit":
client = null;
isExit = true;
break;
default:
printWarning(commandString[0]);
break;
}
}
while (!isExit);
}
|
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/ngodatabase/OrganizationNewsFeedView.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/ngodatabase/OrganizationNewsFeedView.java
index e5c61229c..fe002818d 100644
--- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/ngodatabase/OrganizationNewsFeedView.java
+++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/ngodatabase/OrganizationNewsFeedView.java
@@ -1,329 +1,329 @@
package net.cyklotron.cms.modules.views.ngodatabase;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.jcontainer.dna.Logger;
import org.objectledge.context.Context;
import org.objectledge.coral.datatypes.DateAttributeHandler;
import org.objectledge.coral.entity.EntityDoesNotExistException;
import org.objectledge.coral.query.MalformedQueryException;
import org.objectledge.coral.query.QueryResults;
import org.objectledge.coral.security.Subject;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.i18n.I18nContext;
import org.objectledge.parameters.DefaultParameters;
import org.objectledge.parameters.Parameters;
import org.objectledge.parameters.RequestParameters;
import org.objectledge.pipeline.ProcessingException;
import org.objectledge.table.TableException;
import org.objectledge.table.TableFilter;
import org.objectledge.table.TableModel;
import org.objectledge.table.TableRow;
import org.objectledge.table.TableState;
import org.objectledge.table.TableStateManager;
import org.objectledge.table.TableTool;
import org.objectledge.templating.MergingException;
import org.objectledge.templating.Template;
import org.objectledge.templating.TemplateNotFoundException;
import org.objectledge.templating.TemplatingContext;
import org.objectledge.web.HttpContext;
import org.objectledge.web.mvc.MVCContext;
import org.objectledge.web.mvc.builders.BuildException;
import net.cyklotron.cms.CmsDataFactory;
import net.cyklotron.cms.documents.DocumentNodeResource;
import net.cyklotron.cms.documents.LinkRenderer;
import net.cyklotron.cms.integration.IntegrationService;
import net.cyklotron.cms.modules.views.syndication.BaseSyndicationScreen;
import net.cyklotron.cms.ngodatabase.NgoDatabaseService;
import net.cyklotron.cms.ngodatabase.Organization;
import net.cyklotron.cms.preferences.PreferencesService;
import net.cyklotron.cms.site.SiteResource;
import net.cyklotron.cms.site.SiteResourceImpl;
import net.cyklotron.cms.structure.table.ValidityStartFilter;
import net.cyklotron.cms.syndication.CannotExecuteQueryException;
import net.cyklotron.cms.syndication.CannotGenerateFeedException;
import net.cyklotron.cms.syndication.SyndicationService;
import net.cyklotron.cms.util.CmsResourceListTableModel;
import net.cyklotron.cms.util.OfflineLinkRenderingService;
import net.cyklotron.cms.util.ProtectedValidityFilter;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
/**
* View organization's news outgoing feed.
*
* @author <a href="mailto:[email protected]">Pawel Potempski</a>
* @version $Id: Download.java,v 1.6 2006-01-02 11:42:17 rafal Exp $
*/
public class OrganizationNewsFeedView
extends BaseSyndicationScreen
{
private IntegrationService integrationService;
private I18nContext i18nContext;
private OfflineLinkRenderingService offlineLinkRenderingService;
private NgoDatabaseService ngoDatabaseService;
public OrganizationNewsFeedView(Context context, Logger logger,
PreferencesService preferencesService, CmsDataFactory cmsDataFactory,
TableStateManager tableStateManager, SyndicationService syndicationService,
IntegrationService integrationService, NgoDatabaseService ngoDatabaseService,
OfflineLinkRenderingService offlineLinkRenderingService)
{
super(context, logger, preferencesService, cmsDataFactory, tableStateManager,
syndicationService);
this.integrationService = integrationService;
this.offlineLinkRenderingService = offlineLinkRenderingService;
this.ngoDatabaseService = ngoDatabaseService;
}
@Override
public void process(Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, I18nContext i18nContext,
CoralSession coralSession)
throws ProcessingException
{
throw new UnsupportedOperationException("Implemented the calling method 'build'");
}
@Override
public String build(Template template, String embeddedBuildResults)
throws BuildException
{
HttpContext httpContext = HttpContext.getHttpContext(context);
SyndFeedOutput output = new SyndFeedOutput();
try
{
SyndFeed feed = buildFeed(context);
httpContext.setContentType("text/xml");
httpContext.getResponse().addDateHeader("Last-Modified", (new Date()).getTime());
httpContext.setEncoding("UTF-8");
Writer writer = httpContext.getPrintWriter();
output.output(feed, writer);
writer.flush();
writer.close();
}
catch(IOException e)
{
throw new BuildException("Could not get the output stream", e);
}
catch(FeedException e)
{
throw new BuildException("Could not get the output stream", e);
}
catch(ProcessingException e)
{
throw new BuildException("Could not get the output stream", e);
}
catch(MergingException e)
{
throw new BuildException("Could not get the output stream", e);
}
catch(CannotExecuteQueryException e)
{
throw new BuildException("Cannot execute query:", e);
}
catch(CannotGenerateFeedException e)
{
throw new BuildException("Cannot generate feed:", e);
}
catch(TableException e)
{
throw new BuildException("Table exception", e);
}
catch(TemplateNotFoundException e)
{
throw new BuildException("Template not found exception", e);
}
catch(EntityDoesNotExistException e)
{
throw new BuildException("Entity does not exist", e);
}
return null;
}
/**
* {@inheritDoc}
*/
public boolean requiresAuthenticatedUser(Context context)
throws Exception
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean requiresSecureChannel(Context context)
throws Exception
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean checkAccessRights(Context context)
throws ProcessingException
{
return true;
}
public SyndFeed buildFeed(Context context)
throws CannotExecuteQueryException, TableException, CannotGenerateFeedException,
TemplateNotFoundException, MergingException, EntityDoesNotExistException,
ProcessingException
{
CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class);
Parameters parameters = RequestParameters.getRequestParameters(context);
Long siteId = parameters.getLong("site_id", -1L);
Long organizedId = parameters.getLong("organization_id", -1L);
Integer range = parameters.getInt("range", 30);
Resource[] resources;
QueryResults results;
try
{
results = coralSession.getQuery().executeQuery(
"FIND RESOURCE FROM documents.document_node WHERE site = " + siteId.toString()
+ " AND organisationIds LIKE '%," + organizedId.toString() + ",%'");
}
catch(MalformedQueryException e)
{
throw new ProcessingException("cannot get 'documents.document_node' resources", e);
}
resources = results.getArray(1);
TableState state = new TableState(getClass().getName(), 1);
TableModel model = null;
try
{
I18nContext i18nContext = I18nContext.getI18nContext(context);
model = new CmsResourceListTableModel(context, integrationService, resources,
i18nContext.getLocale());
}
catch(TableException e)
{
throw e;
}
List<TableFilter> filters = new ArrayList<TableFilter>(2);
Subject anonymousSubject = coralSession.getSecurity().getSubject(Subject.ANONYMOUS);
filters.add(new ProtectedValidityFilter(coralSession, anonymousSubject, new Date()));
Calendar calendar = Calendar.getInstance();
if(range > 0)
{
calendar.add(Calendar.DAY_OF_MONTH, -range);
filters.add(new ValidityStartFilter(calendar.getTime(), null));
}
TableTool tableTool = new TableTool(state, filters, model);
List rows = tableTool.getRows();
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
int i = 0;
for(Iterator iter = rows.iterator(); iter.hasNext(); i++)
{
TableRow row = (TableRow)iter.next();
DocumentNodeResource doc = (DocumentNodeResource)row.getObject();
entry = new SyndEntryImpl();
entry.setTitle(doc.getTitle());
entry.setLink(getDocLink(coralSession, doc));
if(doc.getValidityStart() == null)
{
entry.setPublishedDate(doc.getCreationTime());
}
else
{
entry.setPublishedDate(doc.getValidityStart());
}
String docDescription = "";
if(doc.getAbstract() != null)
{
docDescription = doc.getAbstract();
}
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue(docDescription);
entry.setDescription(description);
entries.add(entry);
}
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
Organization organization = ngoDatabaseService.getOrganization(organizedId);
String organizationName = organization != null ? organization.getName() : "";
- feed.setTitle("Zestaw wiadomosci dodanych do serwisu ngo.pl przez organizację: "
+ feed.setTitle("Zestaw wiadomosci dodanych do serwisu ngo.pl przez: "
+ organizationName);
DateFormat dateFormat = new SimpleDateFormat(DateAttributeHandler.DATE_TIME_FORMAT);
String dateFrom = dateFormat.format(calendar.getTime());
String dateTo = dateFormat.format((new Date()).getTime());
feed.setDescription("Zestaw zawiera wiadomości opublikowane w okresie od: " + dateFrom
+ " do:" + dateTo);
feed.setLink(getFeedLink(coralSession, siteId, organizedId, range));
feed.setPublishedDate(new Date());
feed.setEncoding("UTF-8");
feed.setEntries(entries);
return feed;
}
private String getFeedLink(CoralSession coralSession, Long siteId, Long organizationId,
Integer range)
throws EntityDoesNotExistException
{
Parameters queryStringParameters = new DefaultParameters();
queryStringParameters.set("site_id", siteId);
queryStringParameters.set("organization_id", organizationId);
queryStringParameters.set("range", range);
SiteResource site = SiteResourceImpl.getSiteResource(coralSession, siteId);
return offlineLinkRenderingService.getViewURL(coralSession, site,
"ngodatabase.OrganizationNewsFeedView", null, queryStringParameters);
}
private String getDocLink(CoralSession coralSession, DocumentNodeResource doc)
{
LinkRenderer linkRenderer = offlineLinkRenderingService.getLinkRenderer();
try
{
return linkRenderer.getNodeURL(coralSession, doc);
}
catch(ProcessingException e)
{
return null;
}
}
}
| true | true | public SyndFeed buildFeed(Context context)
throws CannotExecuteQueryException, TableException, CannotGenerateFeedException,
TemplateNotFoundException, MergingException, EntityDoesNotExistException,
ProcessingException
{
CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class);
Parameters parameters = RequestParameters.getRequestParameters(context);
Long siteId = parameters.getLong("site_id", -1L);
Long organizedId = parameters.getLong("organization_id", -1L);
Integer range = parameters.getInt("range", 30);
Resource[] resources;
QueryResults results;
try
{
results = coralSession.getQuery().executeQuery(
"FIND RESOURCE FROM documents.document_node WHERE site = " + siteId.toString()
+ " AND organisationIds LIKE '%," + organizedId.toString() + ",%'");
}
catch(MalformedQueryException e)
{
throw new ProcessingException("cannot get 'documents.document_node' resources", e);
}
resources = results.getArray(1);
TableState state = new TableState(getClass().getName(), 1);
TableModel model = null;
try
{
I18nContext i18nContext = I18nContext.getI18nContext(context);
model = new CmsResourceListTableModel(context, integrationService, resources,
i18nContext.getLocale());
}
catch(TableException e)
{
throw e;
}
List<TableFilter> filters = new ArrayList<TableFilter>(2);
Subject anonymousSubject = coralSession.getSecurity().getSubject(Subject.ANONYMOUS);
filters.add(new ProtectedValidityFilter(coralSession, anonymousSubject, new Date()));
Calendar calendar = Calendar.getInstance();
if(range > 0)
{
calendar.add(Calendar.DAY_OF_MONTH, -range);
filters.add(new ValidityStartFilter(calendar.getTime(), null));
}
TableTool tableTool = new TableTool(state, filters, model);
List rows = tableTool.getRows();
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
int i = 0;
for(Iterator iter = rows.iterator(); iter.hasNext(); i++)
{
TableRow row = (TableRow)iter.next();
DocumentNodeResource doc = (DocumentNodeResource)row.getObject();
entry = new SyndEntryImpl();
entry.setTitle(doc.getTitle());
entry.setLink(getDocLink(coralSession, doc));
if(doc.getValidityStart() == null)
{
entry.setPublishedDate(doc.getCreationTime());
}
else
{
entry.setPublishedDate(doc.getValidityStart());
}
String docDescription = "";
if(doc.getAbstract() != null)
{
docDescription = doc.getAbstract();
}
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue(docDescription);
entry.setDescription(description);
entries.add(entry);
}
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
Organization organization = ngoDatabaseService.getOrganization(organizedId);
String organizationName = organization != null ? organization.getName() : "";
feed.setTitle("Zestaw wiadomosci dodanych do serwisu ngo.pl przez organizację: "
+ organizationName);
DateFormat dateFormat = new SimpleDateFormat(DateAttributeHandler.DATE_TIME_FORMAT);
String dateFrom = dateFormat.format(calendar.getTime());
String dateTo = dateFormat.format((new Date()).getTime());
feed.setDescription("Zestaw zawiera wiadomości opublikowane w okresie od: " + dateFrom
+ " do:" + dateTo);
feed.setLink(getFeedLink(coralSession, siteId, organizedId, range));
feed.setPublishedDate(new Date());
feed.setEncoding("UTF-8");
feed.setEntries(entries);
return feed;
}
| public SyndFeed buildFeed(Context context)
throws CannotExecuteQueryException, TableException, CannotGenerateFeedException,
TemplateNotFoundException, MergingException, EntityDoesNotExistException,
ProcessingException
{
CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class);
Parameters parameters = RequestParameters.getRequestParameters(context);
Long siteId = parameters.getLong("site_id", -1L);
Long organizedId = parameters.getLong("organization_id", -1L);
Integer range = parameters.getInt("range", 30);
Resource[] resources;
QueryResults results;
try
{
results = coralSession.getQuery().executeQuery(
"FIND RESOURCE FROM documents.document_node WHERE site = " + siteId.toString()
+ " AND organisationIds LIKE '%," + organizedId.toString() + ",%'");
}
catch(MalformedQueryException e)
{
throw new ProcessingException("cannot get 'documents.document_node' resources", e);
}
resources = results.getArray(1);
TableState state = new TableState(getClass().getName(), 1);
TableModel model = null;
try
{
I18nContext i18nContext = I18nContext.getI18nContext(context);
model = new CmsResourceListTableModel(context, integrationService, resources,
i18nContext.getLocale());
}
catch(TableException e)
{
throw e;
}
List<TableFilter> filters = new ArrayList<TableFilter>(2);
Subject anonymousSubject = coralSession.getSecurity().getSubject(Subject.ANONYMOUS);
filters.add(new ProtectedValidityFilter(coralSession, anonymousSubject, new Date()));
Calendar calendar = Calendar.getInstance();
if(range > 0)
{
calendar.add(Calendar.DAY_OF_MONTH, -range);
filters.add(new ValidityStartFilter(calendar.getTime(), null));
}
TableTool tableTool = new TableTool(state, filters, model);
List rows = tableTool.getRows();
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
int i = 0;
for(Iterator iter = rows.iterator(); iter.hasNext(); i++)
{
TableRow row = (TableRow)iter.next();
DocumentNodeResource doc = (DocumentNodeResource)row.getObject();
entry = new SyndEntryImpl();
entry.setTitle(doc.getTitle());
entry.setLink(getDocLink(coralSession, doc));
if(doc.getValidityStart() == null)
{
entry.setPublishedDate(doc.getCreationTime());
}
else
{
entry.setPublishedDate(doc.getValidityStart());
}
String docDescription = "";
if(doc.getAbstract() != null)
{
docDescription = doc.getAbstract();
}
description = new SyndContentImpl();
description.setType("text/plain");
description.setValue(docDescription);
entry.setDescription(description);
entries.add(entry);
}
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
Organization organization = ngoDatabaseService.getOrganization(organizedId);
String organizationName = organization != null ? organization.getName() : "";
feed.setTitle("Zestaw wiadomosci dodanych do serwisu ngo.pl przez: "
+ organizationName);
DateFormat dateFormat = new SimpleDateFormat(DateAttributeHandler.DATE_TIME_FORMAT);
String dateFrom = dateFormat.format(calendar.getTime());
String dateTo = dateFormat.format((new Date()).getTime());
feed.setDescription("Zestaw zawiera wiadomości opublikowane w okresie od: " + dateFrom
+ " do:" + dateTo);
feed.setLink(getFeedLink(coralSession, siteId, organizedId, range));
feed.setPublishedDate(new Date());
feed.setEncoding("UTF-8");
feed.setEntries(entries);
return feed;
}
|
diff --git a/nuxeo-drive-server/nuxeo-drive-core/src/test/java/org/nuxeo/drive/service/adapter/TestDefaultTopLevelFolderItemFactory.java b/nuxeo-drive-server/nuxeo-drive-core/src/test/java/org/nuxeo/drive/service/adapter/TestDefaultTopLevelFolderItemFactory.java
index 1f8b8d8d..4c9a3e08 100644
--- a/nuxeo-drive-server/nuxeo-drive-core/src/test/java/org/nuxeo/drive/service/adapter/TestDefaultTopLevelFolderItemFactory.java
+++ b/nuxeo-drive-server/nuxeo-drive-core/src/test/java/org/nuxeo/drive/service/adapter/TestDefaultTopLevelFolderItemFactory.java
@@ -1,310 +1,310 @@
/*
* (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Antoine Taillefer <[email protected]>
*/
package org.nuxeo.drive.service.adapter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.Serializable;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.drive.adapter.FileSystemItem;
import org.nuxeo.drive.adapter.FolderItem;
import org.nuxeo.drive.adapter.impl.DefaultSyncRootFolderItem;
import org.nuxeo.drive.adapter.impl.DefaultTopLevelFolderItem;
import org.nuxeo.drive.service.FileSystemItemAdapterService;
import org.nuxeo.drive.service.NuxeoDriveManager;
import org.nuxeo.drive.service.TopLevelFolderItemFactory;
import org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;
import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
import org.nuxeo.ecm.core.test.TransactionalFeature;
import org.nuxeo.ecm.platform.test.PlatformFeature;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import com.google.inject.Inject;
/**
* Tests the {@link DefaultTopLevelFolderItemFactory}.
*
* @author Antoine Taillefer
*/
@RunWith(FeaturesRunner.class)
@Features({ TransactionalFeature.class, PlatformFeature.class })
@Deploy({ "org.nuxeo.drive.core", "org.nuxeo.ecm.platform.query.api" })
public class TestDefaultTopLevelFolderItemFactory {
@Inject
protected CoreSession session;
@Inject
protected FileSystemItemAdapterService fileSystemItemAdapterService;
@Inject
protected NuxeoDriveManager nuxeoDriveManager;
protected DocumentModel syncRoot1;
protected DocumentModel syncRoot2;
protected TopLevelFolderItemFactory defaultTopLevelFolderItemFactory;
@Before
public void createTestDocs() throws Exception {
// Create and register 2 synchronization roots for Administrator
syncRoot1 = session.createDocument(session.createDocumentModel("/",
"syncRoot1", "Folder"));
syncRoot2 = session.createDocument(session.createDocumentModel("/",
"syncRoot2", "Folder"));
nuxeoDriveManager.registerSynchronizationRoot("Administrator",
syncRoot1, session);
nuxeoDriveManager.registerSynchronizationRoot("Administrator",
syncRoot2, session);
// Add a child file to syncRoot1
DocumentModel syncRoot1Child = session.createDocumentModel(
"/syncRoot1", "syncRoot1Child", "File");
Blob blob = new StringBlob("Content of Joe's file.");
blob.setFilename("Joe.odt");
syncRoot1Child.setPropertyValue("file:content", (Serializable) blob);
syncRoot1Child = session.createDocument(syncRoot1Child);
// Flush the session so that the other session instances from the
// FileSystemManager service.
session.save();
// Get default top level folder item factory
defaultTopLevelFolderItemFactory = fileSystemItemAdapterService.getTopLevelFolderItemFactory();
assertTrue(defaultTopLevelFolderItemFactory instanceof DefaultTopLevelFolderItemFactory);
assertEquals("Nuxeo Drive",
defaultTopLevelFolderItemFactory.getFolderName());
}
@Test
public void testFactory() throws Exception {
// -------------------------------------------------------------
// Check TopLevelFolderItemFactory#getTopLevelFolderItem(String
- // userName)
+ // Principal)
// -------------------------------------------------------------
FolderItem topLevelFolderItem = defaultTopLevelFolderItemFactory.getTopLevelFolderItem(session.getPrincipal());
assertNotNull(topLevelFolderItem);
assertTrue(topLevelFolderItem instanceof DefaultTopLevelFolderItem);
assertTrue(topLevelFolderItem.getId().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertTrue(topLevelFolderItem.getPath().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertTrue(topLevelFolderItem.getPath().startsWith("/"));
assertNull(topLevelFolderItem.getParentId());
assertEquals("Nuxeo Drive", topLevelFolderItem.getName());
assertTrue(topLevelFolderItem.isFolder());
assertEquals("system", topLevelFolderItem.getCreator());
assertFalse(topLevelFolderItem.getCanRename());
try {
topLevelFolderItem.rename("newName");
fail("Should not be able to rename the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot rename a virtual folder item.", e.getMessage());
}
assertFalse(topLevelFolderItem.getCanDelete());
try {
topLevelFolderItem.delete();
fail("Should not be able to delete the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot delete a virtual folder item.", e.getMessage());
}
assertFalse(topLevelFolderItem.canMove(null));
try {
topLevelFolderItem.move(null);
fail("Should not be able to move the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot move a virtual folder item.", e.getMessage());
}
List<FileSystemItem> children = topLevelFolderItem.getChildren();
assertNotNull(children);
assertEquals(2, children.size());
assertFalse(topLevelFolderItem.getCanCreateChild());
for (FileSystemItem child : children) {
assertEquals(topLevelFolderItem.getPath() + '/' + child.getId(),
child.getPath());
}
try {
topLevelFolderItem.createFile(new StringBlob("Child file content."));
fail("Should not be able to create a file in the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot create a file in a virtual folder item.",
e.getMessage());
}
try {
topLevelFolderItem.createFolder("subFolder");
fail("Should not be able to create a folder in the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot create a folder in a virtual folder item.",
e.getMessage());
}
// -------------------------------------------------------------
// Check VirtualFolderItemFactory#getVirtualFolderItem(Principal
// userName)
// -------------------------------------------------------------
assertEquals(
topLevelFolderItem,
defaultTopLevelFolderItemFactory.getVirtualFolderItem(session.getPrincipal()));
}
/**
* Tests the default top level folder item children, ie. the synchronization
* root folders.
*/
@Test
public void testTopLevelFolderItemChildren() throws ClientException {
FolderItem topLevelFolderItem = defaultTopLevelFolderItemFactory.getTopLevelFolderItem(session.getPrincipal());
List<FileSystemItem> children = topLevelFolderItem.getChildren();
assertNotNull(children);
assertEquals(2, children.size());
FileSystemItem firstRootAsFsItem = children.get(0);
assertTrue(firstRootAsFsItem instanceof DefaultSyncRootFolderItem);
assertEquals(
"defaultSyncRootFolderItemFactory#test#" + syncRoot1.getId(),
firstRootAsFsItem.getId());
assertTrue(firstRootAsFsItem.getParentId().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertEquals("syncRoot1", firstRootAsFsItem.getName());
assertTrue(firstRootAsFsItem.isFolder());
assertEquals("Administrator", firstRootAsFsItem.getCreator());
assertTrue(firstRootAsFsItem.getCanRename());
firstRootAsFsItem.rename("newName");
assertEquals("newName", firstRootAsFsItem.getName());
assertTrue(firstRootAsFsItem instanceof FolderItem);
FolderItem firstRootAsFolderItem = (FolderItem) firstRootAsFsItem;
List<FileSystemItem> childFsItemChildren = firstRootAsFolderItem.getChildren();
assertNotNull(childFsItemChildren);
assertEquals(1, childFsItemChildren.size());
assertTrue(firstRootAsFolderItem.getCanCreateChild());
FileSystemItem secondRootAsFsItem = children.get(1);
assertTrue(secondRootAsFsItem instanceof DefaultSyncRootFolderItem);
assertEquals(
"defaultSyncRootFolderItemFactory#test#" + syncRoot2.getId(),
secondRootAsFsItem.getId());
assertTrue(secondRootAsFsItem.getParentId().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertEquals("syncRoot2", secondRootAsFsItem.getName());
// Let's delete a Sync Root FS Item: this should result in a root
// unregistration
assertTrue(firstRootAsFsItem.getCanDelete());
firstRootAsFsItem.delete();
assertFalse(nuxeoDriveManager.getSynchronizationRootReferences(session).contains(
new IdRef(syncRoot1.getId())));
assertFalse(firstRootAsFsItem.canMove(null));
try {
firstRootAsFsItem.move(null);
fail("Should not be able to move a synchronization root folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot move a synchronization root folder item.",
e.getMessage());
}
}
@Test
public void testFileSystemItemFactory() throws ClientException {
// #getName()
assertEquals(
"org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory",
defaultTopLevelFolderItemFactory.getName());
// #setName(String name)
defaultTopLevelFolderItemFactory.setName("testName");
assertEquals("testName", defaultTopLevelFolderItemFactory.getName());
defaultTopLevelFolderItemFactory.setName("org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory");
// #isFileSystemItem(DocumentModel doc)
DocumentModel fakeDoc = new DocumentModelImpl("File");
assertFalse(defaultTopLevelFolderItemFactory.isFileSystemItem(fakeDoc));
// #getFileSystemItem(DocumentModel doc)
try {
defaultTopLevelFolderItemFactory.getFileSystemItem(fakeDoc);
fail("Should be unsupported.");
} catch (UnsupportedOperationException e) {
assertEquals(
"Cannot get the file system item for a given document from factory org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory.",
e.getMessage());
}
// #getFileSystemItem(DocumentModel doc, String parentId)
try {
defaultTopLevelFolderItemFactory.getFileSystemItem(fakeDoc,
"testParentId");
fail("Should be unsupported.");
} catch (UnsupportedOperationException e) {
assertEquals(
"Cannot get the file system item for a given document from factory org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory.",
e.getMessage());
}
// #canHandleFileSystemItemId(String id)
assertTrue(defaultTopLevelFolderItemFactory.canHandleFileSystemItemId("org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory#"));
assertFalse(defaultTopLevelFolderItemFactory.canHandleFileSystemItemId("org.nuxeo.drive.service.impl.DefaultFileSystemItemFactory#"));
// #exists(String id, Principal principal)
assertTrue(defaultTopLevelFolderItemFactory.exists(
"org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory#",
session.getPrincipal()));
try {
defaultTopLevelFolderItemFactory.exists("testId",
session.getPrincipal());
fail("Should be unsupported.");
} catch (UnsupportedOperationException e) {
assertEquals(
"Cannot check if a file system item exists for an id that cannot be handled from factory org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory.",
e.getMessage());
}
// #getFileSystemItemById(String id, Principal principal)
FileSystemItem topLevelFolderItem = defaultTopLevelFolderItemFactory.getFileSystemItemById(
"org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory#",
session.getPrincipal());
assertNotNull(topLevelFolderItem);
assertTrue(topLevelFolderItem instanceof DefaultTopLevelFolderItem);
assertNull(topLevelFolderItem.getParentId());
assertEquals("Nuxeo Drive", topLevelFolderItem.getName());
try {
defaultTopLevelFolderItemFactory.getFileSystemItemById("testId",
session.getPrincipal());
fail("Should be unsupported.");
} catch (UnsupportedOperationException e) {
assertEquals(
"Cannot get the file system item for an id that cannot be handled from factory org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory.",
e.getMessage());
}
}
}
| true | true | public void testFactory() throws Exception {
// -------------------------------------------------------------
// Check TopLevelFolderItemFactory#getTopLevelFolderItem(String
// userName)
// -------------------------------------------------------------
FolderItem topLevelFolderItem = defaultTopLevelFolderItemFactory.getTopLevelFolderItem(session.getPrincipal());
assertNotNull(topLevelFolderItem);
assertTrue(topLevelFolderItem instanceof DefaultTopLevelFolderItem);
assertTrue(topLevelFolderItem.getId().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertTrue(topLevelFolderItem.getPath().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertTrue(topLevelFolderItem.getPath().startsWith("/"));
assertNull(topLevelFolderItem.getParentId());
assertEquals("Nuxeo Drive", topLevelFolderItem.getName());
assertTrue(topLevelFolderItem.isFolder());
assertEquals("system", topLevelFolderItem.getCreator());
assertFalse(topLevelFolderItem.getCanRename());
try {
topLevelFolderItem.rename("newName");
fail("Should not be able to rename the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot rename a virtual folder item.", e.getMessage());
}
assertFalse(topLevelFolderItem.getCanDelete());
try {
topLevelFolderItem.delete();
fail("Should not be able to delete the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot delete a virtual folder item.", e.getMessage());
}
assertFalse(topLevelFolderItem.canMove(null));
try {
topLevelFolderItem.move(null);
fail("Should not be able to move the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot move a virtual folder item.", e.getMessage());
}
List<FileSystemItem> children = topLevelFolderItem.getChildren();
assertNotNull(children);
assertEquals(2, children.size());
assertFalse(topLevelFolderItem.getCanCreateChild());
for (FileSystemItem child : children) {
assertEquals(topLevelFolderItem.getPath() + '/' + child.getId(),
child.getPath());
}
try {
topLevelFolderItem.createFile(new StringBlob("Child file content."));
fail("Should not be able to create a file in the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot create a file in a virtual folder item.",
e.getMessage());
}
try {
topLevelFolderItem.createFolder("subFolder");
fail("Should not be able to create a folder in the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot create a folder in a virtual folder item.",
e.getMessage());
}
// -------------------------------------------------------------
// Check VirtualFolderItemFactory#getVirtualFolderItem(Principal
// userName)
// -------------------------------------------------------------
assertEquals(
topLevelFolderItem,
defaultTopLevelFolderItemFactory.getVirtualFolderItem(session.getPrincipal()));
}
| public void testFactory() throws Exception {
// -------------------------------------------------------------
// Check TopLevelFolderItemFactory#getTopLevelFolderItem(String
// Principal)
// -------------------------------------------------------------
FolderItem topLevelFolderItem = defaultTopLevelFolderItemFactory.getTopLevelFolderItem(session.getPrincipal());
assertNotNull(topLevelFolderItem);
assertTrue(topLevelFolderItem instanceof DefaultTopLevelFolderItem);
assertTrue(topLevelFolderItem.getId().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertTrue(topLevelFolderItem.getPath().endsWith(
"DefaultTopLevelFolderItemFactory#"));
assertTrue(topLevelFolderItem.getPath().startsWith("/"));
assertNull(topLevelFolderItem.getParentId());
assertEquals("Nuxeo Drive", topLevelFolderItem.getName());
assertTrue(topLevelFolderItem.isFolder());
assertEquals("system", topLevelFolderItem.getCreator());
assertFalse(topLevelFolderItem.getCanRename());
try {
topLevelFolderItem.rename("newName");
fail("Should not be able to rename the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot rename a virtual folder item.", e.getMessage());
}
assertFalse(topLevelFolderItem.getCanDelete());
try {
topLevelFolderItem.delete();
fail("Should not be able to delete the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot delete a virtual folder item.", e.getMessage());
}
assertFalse(topLevelFolderItem.canMove(null));
try {
topLevelFolderItem.move(null);
fail("Should not be able to move the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot move a virtual folder item.", e.getMessage());
}
List<FileSystemItem> children = topLevelFolderItem.getChildren();
assertNotNull(children);
assertEquals(2, children.size());
assertFalse(topLevelFolderItem.getCanCreateChild());
for (FileSystemItem child : children) {
assertEquals(topLevelFolderItem.getPath() + '/' + child.getId(),
child.getPath());
}
try {
topLevelFolderItem.createFile(new StringBlob("Child file content."));
fail("Should not be able to create a file in the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot create a file in a virtual folder item.",
e.getMessage());
}
try {
topLevelFolderItem.createFolder("subFolder");
fail("Should not be able to create a folder in the default top level folder item.");
} catch (UnsupportedOperationException e) {
assertEquals("Cannot create a folder in a virtual folder item.",
e.getMessage());
}
// -------------------------------------------------------------
// Check VirtualFolderItemFactory#getVirtualFolderItem(Principal
// userName)
// -------------------------------------------------------------
assertEquals(
topLevelFolderItem,
defaultTopLevelFolderItemFactory.getVirtualFolderItem(session.getPrincipal()));
}
|
diff --git a/srcj/com/sun/electric/tool/io/output/Spice.java b/srcj/com/sun/electric/tool/io/output/Spice.java
index 887da3c85..9683fa160 100755
--- a/srcj/com/sun/electric/tool/io/output/Spice.java
+++ b/srcj/com/sun/electric/tool/io/output/Spice.java
@@ -1,3358 +1,3356 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Spice.java
* Original C Code written by Steven M. Rubin and Sid Penstone
* Translated to Java by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.output;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.HierarchyEnumerator;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.network.Global;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitiveNodeSize;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.TransistorSize;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.generator.sclibrary.SCLibraryGen;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.input.spicenetlist.SpiceNetlistReader;
import com.sun.electric.tool.io.input.spicenetlist.SpiceSubckt;
import com.sun.electric.tool.logicaleffort.LENetlister;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations.NamePattern;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.Exec;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.ExecDialog;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import java.awt.geom.AffineTransform;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* This is the Simulation Interface tool.
*/
public class Spice extends Topology
{
/** key of Variable holding generic Spice templates. */ public static final Variable.Key SPICE_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template");
/** key of Variable holding Spice 2 templates. */ public static final Variable.Key SPICE_2_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice2");
/** key of Variable holding Spice 3 templates. */ public static final Variable.Key SPICE_3_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice3");
/** key of Variable holding HSpice templates. */ public static final Variable.Key SPICE_H_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_hspice");
/** key of Variable holding PSpice templates. */ public static final Variable.Key SPICE_P_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_pspice");
/** key of Variable holding GnuCap templates. */ public static final Variable.Key SPICE_GC_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_gnucap");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_SM_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_smartspice");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_A_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_assura");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_C_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_calibre");
/** key of Variable holding Spice model file. */ public static final Variable.Key SPICE_NETLIST_FILE_KEY = Variable.newKey("ATTR_SPICE_netlist_file");
/** key of Variable holding SPICE code. */ public static final Variable.Key SPICE_CARD_KEY = Variable.newKey("SIM_spice_card");
/** key of Variable holding SPICE declaration. */ public static final Variable.Key SPICE_DECLARATION_KEY = Variable.newKey("SIM_spice_declaration");
/** key of Variable holding SPICE model. */ public static final Variable.Key SPICE_MODEL_KEY = Variable.newKey("SIM_spice_model");
/** key of Variable holding SPICE flat code. */ public static final Variable.Key SPICE_CODE_FLAT_KEY = Variable.newKey("SIM_spice_code_flat");
/** key of wire capacitance. */ public static final Variable.Key ATTR_C = Variable.newKey("ATTR_C");
/** key of wire resistance. */ public static final Variable.Key ATTR_R = Variable.newKey("ATTR_R");
/** key of Variable holding generic CDL templates. */ public static final Variable.Key CDL_TEMPLATE_KEY = Variable.newKey("ATTR_CDL_template");
/** Prefix for spice extension. */ public static final String SPICE_EXTENSION_PREFIX = "Extension ";
/** Prefix for spice null extension. */ public static final String SPICE_NOEXTENSION_PREFIX = "N O N E ";
/** maximum subcircuit name length */ private static final int SPICEMAXLENSUBCKTNAME = 70;
/** maximum subcircuit name length */ private static final int CDLMAXLENSUBCKTNAME = 40;
/** maximum subcircuit name length */ private static final int SPICEMAXLENLINE = 78;
/** legal characters in a spice deck */ private static final String SPICELEGALCHARS = "!#$%*+-/<>[]_@";
/** legal characters in a spice deck */ private static final String PSPICELEGALCHARS = "!#$%*+-/<>[]_";
/** legal characters in a CDL deck */ private static final String CDLNOBRACKETLEGALCHARS = "!#$%*+-/<>_";
/** if CDL writes out empty subckt definitions */ private static final boolean CDLWRITESEMPTYSUBCKTS = false;
/** default Technology to use. */ private Technology layoutTechnology;
/** Mask shrink factor (default =1) */ private double maskScale;
/** True to write CDL format */ private boolean useCDL;
/** Legal characters */ private String legalSpiceChars;
/** Template Key for current spice engine */ private Variable.Key preferedEngineTemplateKey;
/** Special case for HSpice for Assura */ private boolean assuraHSpice = false;
/** Spice type: 2, 3, H, P, etc */ private Simulation.SpiceEngine spiceEngine;
/** those cells that have overridden models */ private HashMap<Cell,String> modelOverrides = new HashMap<Cell,String>();
/** List of segmented nets and parasitics */ private List<SegmentedNets> segmentedParasiticInfo = new ArrayList<SegmentedNets>();
/** Networks exempted during parasitic ext */ private ExemptedNets exemptedNets;
/** Whether or not to write empty subckts */ private boolean writeEmptySubckts = true;
/** max length per line */ private int spiceMaxLenLine = SPICEMAXLENLINE;
/** Flat measurements file */ private FlatSpiceCodeVisitor spiceCodeFlat = null;
/** map of "parameterized" cells not covered by Topology */ private Map<Cell,Cell> uniquifyCells;
/** uniqueID */ private int uniqueID;
/** map of shortened instance names */ private Map<String,Integer> uniqueNames;
private static final boolean useNewParasitics = true;
private static class SpiceNet
{
/** network object associated with this */ Network network;
/** merged geometry for this network */ PolyMerge merge;
/** area of diffusion */ double diffArea;
/** perimeter of diffusion */ double diffPerim;
/** amount of capacitance in non-diff */ float nonDiffCapacitance;
/** number of transistors on the net */ int transistorCount;
}
/**
* The main entry point for Spice deck writing.
* @param cell the top-level cell to write.
* @param context the hierarchical context to the cell.
* @param filePath the disk file to create.
* @param cdl true if this is CDL output (false for Spice).
*/
public static void writeSpiceFile(Cell cell, VarContext context, String filePath, boolean cdl)
{
Spice out = new Spice();
out.useCDL = cdl;
if (out.openTextOutputStream(filePath)) return;
if (out.writeCell(cell, context)) return;
if (out.closeTextOutputStream()) return;
System.out.println(filePath + " written");
// write CDL support file if requested
if (out.useCDL)
{
// write the control files
String deckFile = filePath;
String deckPath = "";
int lastDirSep = deckFile.lastIndexOf(File.separatorChar);
if (lastDirSep > 0)
{
deckPath = deckFile.substring(0, lastDirSep);
deckFile = deckFile.substring(lastDirSep+1);
}
String templateFile = deckPath + File.separator + cell.getName() + ".cdltemplate";
if (out.openTextOutputStream(templateFile)) return;
String libName = Simulation.getCDLLibName();
String libPath = Simulation.getCDLLibPath();
out.printWriter.print("cdlInKeys = list(nil\n");
out.printWriter.print(" 'searchPath \"" + deckFile + "");
if (libPath.length() > 0)
out.printWriter.print("\n " + libPath);
out.printWriter.print("\"\n");
out.printWriter.print(" 'cdlFile \"" + deckPath + File.separator + deckFile + "\"\n");
out.printWriter.print(" 'userSkillFile \"\"\n");
out.printWriter.print(" 'opusLib \"" + libName + "\"\n");
out.printWriter.print(" 'primaryCell \"" + cell.getName() + "\"\n");
out.printWriter.print(" 'caseSensitivity \"lower\"\n");
out.printWriter.print(" 'hierarchy \"flatten\"\n");
out.printWriter.print(" 'cellTable \"\"\n");
out.printWriter.print(" 'viewName \"netlist\"\n");
out.printWriter.print(" 'viewType \"\"\n");
out.printWriter.print(" 'pr nil\n");
out.printWriter.print(" 'skipDevice nil\n");
out.printWriter.print(" 'schemaLib \"sample\"\n");
out.printWriter.print(" 'refLib \"\"\n");
out.printWriter.print(" 'globalNodeExpand \"full\"\n");
out.printWriter.print(")\n");
if (out.closeTextOutputStream()) return;
System.out.println(templateFile + " written");
}
String runSpice = Simulation.getSpiceRunChoice();
if (!runSpice.equals(Simulation.spiceRunChoiceDontRun)) {
String command = Simulation.getSpiceRunProgram() + " " + Simulation.getSpiceRunProgramArgs();
// see if user specified custom dir to run process in
String workdir = User.getWorkingDirectory();
String rundir = workdir;
if (Simulation.getSpiceUseRunDir()) {
rundir = Simulation.getSpiceRunDir();
}
File dir = new File(rundir);
int start = filePath.lastIndexOf(File.separator);
if (start == -1) start = 0; else {
start++;
if (start > filePath.length()) start = filePath.length();
}
int end = filePath.lastIndexOf(".");
if (end == -1) end = filePath.length();
String filename_noext = filePath.substring(start, end);
String filename = filePath.substring(start, filePath.length());
// replace vars in command and args
command = command.replaceAll("\\$\\{WORKING_DIR}", workdir);
command = command.replaceAll("\\$\\{USE_DIR}", rundir);
command = command.replaceAll("\\$\\{FILENAME}", filename);
command = command.replaceAll("\\$\\{FILENAME_NO_EXT}", filename_noext);
// set up run probe
FileType type = Simulate.getCurrentSpiceOutputType();
String [] extensions = type.getExtensions();
String outFile = rundir + File.separator + filename_noext + "." + extensions[0];
Exec.FinishedListener l = new SpiceFinishedListener(cell, type, outFile);
if (runSpice.equals(Simulation.spiceRunChoiceRunIgnoreOutput)) {
Exec e = new Exec(command, null, dir, null, null);
if (Simulation.getSpiceRunProbe()) e.addFinishedListener(l);
e.start();
}
if (runSpice.equals(Simulation.spiceRunChoiceRunReportOutput)) {
ExecDialog dialog = new ExecDialog(TopLevel.getCurrentJFrame(), false);
if (Simulation.getSpiceRunProbe()) dialog.addFinishedListener(l);
dialog.startProcess(command, null, dir);
}
System.out.println("Running spice command: "+command);
}
if (Simulation.isParasiticsBackAnnotateLayout() && Simulation.isSpiceUseParasitics()) {
out.backAnnotateLayout();
}
}
private static class SpiceFinishedListener implements Exec.FinishedListener
{
private Cell cell;
private FileType type;
private String file;
private SpiceFinishedListener(Cell cell, FileType type, String file) {
this.cell = cell;
this.type = type;
this.file = file;
}
public void processFinished(Exec.FinishedEvent e) {
URL fileURL = TextUtils.makeURLToFile(file);
// create a new waveform window
WaveformWindow ww = WaveformWindow.findWaveformWindow(cell);
Simulate.plotSimulationResults(type, cell, fileURL, ww);
}
}
/**
* Creates a new instance of Spice
*/
Spice()
{
}
protected void start()
{
// find the proper technology to use if this is schematics
if (topCell.getTechnology().isLayout())
layoutTechnology = topCell.getTechnology();
else
layoutTechnology = Schematics.getDefaultSchematicTechnology();
// make sure key is cached
spiceEngine = Simulation.getSpiceEngine();
preferedEngineTemplateKey = SPICE_TEMPLATE_KEY;
assuraHSpice = false;
switch (spiceEngine)
{
case SPICE_ENGINE_2: preferedEngineTemplateKey = SPICE_2_TEMPLATE_KEY; break;
case SPICE_ENGINE_3: preferedEngineTemplateKey = SPICE_3_TEMPLATE_KEY; break;
case SPICE_ENGINE_H: preferedEngineTemplateKey = SPICE_H_TEMPLATE_KEY; break;
case SPICE_ENGINE_P: preferedEngineTemplateKey = SPICE_P_TEMPLATE_KEY; break;
case SPICE_ENGINE_G: preferedEngineTemplateKey = SPICE_GC_TEMPLATE_KEY; break;
case SPICE_ENGINE_S: preferedEngineTemplateKey = SPICE_SM_TEMPLATE_KEY; break;
case SPICE_ENGINE_H_ASSURA: preferedEngineTemplateKey = SPICE_A_TEMPLATE_KEY; assuraHSpice = true; break;
case SPICE_ENGINE_H_CALIBRE: preferedEngineTemplateKey = SPICE_C_TEMPLATE_KEY; assuraHSpice = true; break;
}
if (useCDL) {
preferedEngineTemplateKey = CDL_TEMPLATE_KEY;
}
if (assuraHSpice || (useCDL && !CDLWRITESEMPTYSUBCKTS) ||
(!useCDL && !Simulation.isSpiceWriteEmtpySubckts())) {
writeEmptySubckts = false;
}
// get the mask scale
maskScale = 1.0;
// Variable scaleVar = layoutTechnology.getVar("SIM_spice_mask_scale");
// if (scaleVar != null) maskScale = TextUtils.atof(scaleVar.getObject().toString());
// set up the parameterized cells
uniquifyCells = new HashMap<Cell,Cell>();
uniqueID = 0;
uniqueNames = new HashMap<String,Integer>();
checkIfParameterized(topCell);
// setup the legal characters
legalSpiceChars = SPICELEGALCHARS;
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) legalSpiceChars = PSPICELEGALCHARS;
// start writing the spice deck
if (useCDL)
{
// setup bracket conversion for CDL
if (Simulation.isCDLConvertBrackets())
legalSpiceChars = CDLNOBRACKETLEGALCHARS;
multiLinePrint(true, "* First line is ignored\n");
// see if include file specified
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
String filePart = Simulation.getCDLIncludeFile();
if (!filePart.equals("")) {
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Primitives described in this file:\n");
addIncludeFile(filePart);
} else {
System.out.println("Warning: CDL Include file not found: "+fileName);
}
}
} else
{
writeHeader(topCell);
spiceCodeFlat = new FlatSpiceCodeVisitor(filePath+".flatcode", this);
HierarchyEnumerator.enumerateCell(topCell, VarContext.globalContext, spiceCodeFlat, getShortResistorsFlat());
spiceCodeFlat.close();
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
exemptedNets = new ExemptedNets(new File(headerPath + File.separator + "exemptedNets.txt"));
}
}
protected void done()
{
if (!useCDL)
{
writeTrailer(topCell);
if (Simulation.isSpiceWriteFinalDotEnd())
multiLinePrint(false, ".END\n");
}
}
/**
* To write M factor information into given string buffer
* @param no Nodable representing the node
* @param infstr Buffer where to write to
*/
private void writeMFactor(VarContext context, Nodable no, StringBuffer infstr)
{
Variable mVar = no.getVar(Simulation.M_FACTOR_KEY);
if (mVar == null) return;
Object value = context.evalVar(mVar);
// check for M=@M, and warn user that this is a bad idea, and we will not write it out
if (mVar.getObject().toString().equals("@M") || (mVar.getObject().toString().equals("P(\"M\")")))
{
System.out.println("Warning: M=@M [eval=" + value + "] on " + no.getName() +
" is a bad idea, not writing it out: " + context.push(no).getInstPath("."));
return;
}
infstr.append(" M=" + formatParam(value.toString(), TextDescriptor.Unit.NONE));
}
/** Called at the end of the enter cell phase of hierarchy enumeration */
protected void enterCell(HierarchyEnumerator.CellInfo info) {
if (exemptedNets != null)
exemptedNets.setExemptedNets(info);
}
private Variable getEngineTemplate(Cell cell)
{
Variable varTemplate = cell.getVar(preferedEngineTemplateKey);
// Any of the following spice templates, if missing, will default to the generic spice template
if (varTemplate == null)
{
if (preferedEngineTemplateKey == SPICE_2_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_3_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_H_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_P_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_GC_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_SM_TEMPLATE_KEY)
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
}
return varTemplate;
}
/**
* Method to write cellGeom
*/
protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics)
{
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
double cap = 0;
double res = 0;
//System.out.println("--Processing arc "+ai.getName());
boolean extractNet = true;
if (segmentedNets.isPowerGround(ai.getHeadPortInst()))
extractNet = false;
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
extractNet = false;
Network net = netList.getNetwork(ai, 0);
if (extractNet && Simulation.isParasiticsUseExemptedNetsFile()) {
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
extractNet = false;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net))) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
extractNet = true;
}
} else {
extractNet = false;
}
}
}
if (extractNet) {
// figure out res and cap, see if we should ignore it
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaBaseWidth() * scale / 1000; // width in microns
// double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer()) {
if (Simulation.isParasiticsExtractsC()) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
}
if (Simulation.isParasiticsExtractsR()) {
res = length/width * layer.getResistance();
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (res <= cell.getTechnology().getMinResistance()) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
//System.out.println("Using resistance of "+res+" for arc "+ai.getName());
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
segmentedNets.addExtractedNet(net);
} else {
//System.out.println(" not extracting arc "+ai.getName());
// don't need to short arcs on networks that aren't extracted, since it is
// guaranteed that both ends of the arc are named the same.
//segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
//System.out.println("--Processing gate "+ni.getName());
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = ni.getTransistorAltGatePort();
Network gateNet0 = netList.getNetwork(gate0);
if ((gate0 != gate1) && segmentedNets.isExtractedNet(gateNet0)) {
//System.out.println("Shorting gate "+ni.getName()+" ports "
// +gate0.getPortProto().getName()+" and "
// +gate1.getPortProto().getName());
segmentedNets.shortSegments(gate0, gate1);
}
}
// merge wells
} else {
//System.out.println("--Processing subcell "+ni.getName());
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
Network net = netList.getNetwork(pi);
if (segmentedNets.isExtractedNet(net))
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
+ if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
+ if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
+ if (!subCS.isGlobal() && pp == null) continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
- if (Simulation.isSpiceUseNodeNames() && spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
- {
- if (pp == null) continue;
- }
- if (subCS.isGlobal())
- net = netList.getNetwork(no, subCS.getGlobal());
- else
- net = netList.getNetwork(no, pp, exportIndex);
+ if (subCS.isGlobal())
+ net = netList.getNetwork(no, subCS.getGlobal()); else
+ net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && getSegmentedNets((Cell)no.getProto()) != null) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit());
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit());
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE);
}
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
else if (fun == PrimitiveNode.Function.WRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE);
}
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) {
extra = "rnwod "+extra;
}
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) {
extra = "rpwod "+extra;
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit());
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit());
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics)
{
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap, 2);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else
{
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
private void emitEmbeddedSpice(Variable cardVar, VarContext context, SegmentedNets segmentedNets, HierarchyEnumerator.CellInfo info, boolean flatNetNames)
{
Object obj = cardVar.getObject();
if (!(obj instanceof String) && !(obj instanceof String[])) return;
if (!cardVar.isDisplay()) return;
if (obj instanceof String)
{
StringBuffer buf = replacePortsAndVars((String)obj, context.getNodable(), context.pop(), null, segmentedNets, info, flatNetNames);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
} else
{
String [] strings = (String [])obj;
for(int i=0; i<strings.length; i++)
{
StringBuffer buf = replacePortsAndVars(strings[i], context.getNodable(), context.pop(), null, segmentedNets, info, flatNetNames);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
}
}
}
/**
* Check if the specified cell is parameterized. Note that this
* recursively checks all cells below this cell as well, and marks
* all cells that contain LE gates, or whose subcells contain LE gates,
* as parameterized.
* @return true if cell has been marked as parameterized
*/
private boolean checkIfParameterized(Cell cell) {
//System.out.println("Checking Cell "+cell.describe());
boolean mark = false;
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
if (!ni.isCellInstance()) continue;
if (ni.isIconOfParent()) continue;
if (ni.getVar(LENetlister.ATTR_LEGATE) != null) {
// make sure cell also has that var
Cell np = (Cell)ni.getProto();
if (np.contentsView() != null) np = np.contentsView();
if (np.getVar(LENetlister.ATTR_LEGATE) != null)
mark = true; continue;
}
if (ni.getVar(LENetlister.ATTR_LEKEEPER) != null) {
// make sure cell also has that var
Cell np = (Cell)ni.getProto();
if (np.contentsView() != null) np = np.contentsView();
if (np.getVar(LENetlister.ATTR_LEKEEPER) != null)
mark = true; continue;
}
Cell proto = ((Cell)ni.getProto()).contentsView();
if (proto == null) proto = (Cell)ni.getProto();
if (checkIfParameterized(proto)) { mark = true; }
}
if (mark)
uniquifyCells.put(cell, cell);
//System.out.println("---> "+cell.describe()+" is marked "+mark);
return mark;
}
/*
* Method to create a parameterized name for node instance "ni".
* If the node is not parameterized, returns zero.
* If it returns a name, that name must be deallocated when done.
*/
protected String parameterizedName(Nodable no, VarContext context)
{
Cell cell = (Cell)no.getProto();
StringBuffer uniqueCellName = new StringBuffer(getUniqueCellName(cell));
if (uniquifyCells.get(cell) != null) {
// if this cell is marked to be make unique, make a unique name out of the var context
VarContext vc = context.push(no);
uniqueCellName.append("_"+vc.getInstPath("."));
} else {
boolean useCellParams = !useCDL && Simulation.isSpiceUseCellParameters();
if (canParameterizeNames() && no.isCellInstance() && !SCLibraryGen.isStandardCell(cell))
{
// if there are parameters, append them to this name
List<Variable> paramValues = new ArrayList<Variable>();
for(Iterator<Variable> it = no.getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (!no.getNodeInst().isParam(var.getKey())) continue;
// if (!var.isParam()) continue;
Variable cellvar = cell.getVar(var.getKey());
if (useCellParams && (cellvar.getCode() == TextDescriptor.Code.SPICE)) {
continue;
}
paramValues.add(var);
}
for(Variable var : paramValues)
{
String eval = var.describe(context, no);
//Object eval = context.evalVar(var, no);
if (eval == null) continue;
//uniqueCellName += "-" + var.getTrueName() + "-" + eval.toString();
uniqueCellName.append("-" + eval.toString());
}
}
}
// if it is over the length limit, truncate it
int limit = maxNameLength();
if (limit > 0 && uniqueCellName.length() > limit)
{
Integer i = uniqueNames.get(uniqueCellName.toString());
if (i == null) {
i = new Integer(uniqueID);
uniqueID++;
uniqueNames.put(uniqueCellName.toString(), i);
}
uniqueCellName = uniqueCellName.delete(limit-10, uniqueCellName.length());
uniqueCellName.append("-ID"+i);
}
// make it safe
return getSafeCellName(uniqueCellName.toString());
}
private static class StringBufferQuoteParity
{
private StringBuffer sb = new StringBuffer();
private int quoteCount;
void append(String str)
{
sb.append(str);
for(int i=0; i<str.length(); i++)
if (str.charAt(i) == '\'') quoteCount++;
}
void append(char c)
{
sb.append(c);
if (c == '\'') quoteCount++;
}
boolean inQuotes() { return (quoteCount&1) != 0; }
StringBuffer getStringBuffer() { return sb; }
}
/**
* Replace ports and vars in 'line'. Ports and Vars should be
* referenced via $(name)
* @param line the string to search and replace within
* @param no the nodable up the hierarchy that has the parameters on it
* @param context the context of the nodable
* @param cni the cell net info of cell in which the nodable exists (if cni is
* null, no port name replacement will be done)
* @return the modified line
*/
private StringBuffer replacePortsAndVars(String line, Nodable no, VarContext context,
CellNetInfo cni, SegmentedNets segmentedNets,
HierarchyEnumerator.CellInfo info, boolean flatNetNames) {
StringBufferQuoteParity infstr = new StringBufferQuoteParity();
NodeProto prototype = null;
PrimitiveNode prim = null;
if (no != null)
{
prototype = no.getProto();
if (prototype instanceof PrimitiveNode) prim = (PrimitiveNode)prototype;
}
for(int pt = 0; pt < line.length(); pt++)
{
// see if the character is part of a substitution expression
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
// not part of substitution: just emit it
infstr.append(chr);
continue;
}
// may be part of substitution expression: look for closing parenthesis
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
if (prototype != null) {
pp = prototype.findPortProto(paramName);
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && no != null)
{
String nodeName = getSafeNetName(no.getName(), false);
// nodeName = nodeName.replaceAll("[\\[\\]]", "_");
infstr.append(nodeName);
} else if (paramName.equalsIgnoreCase("width") && prim != null)
{
NodeInst ni = (NodeInst)no;
PrimitiveNodeSize npSize = ni.getPrimitiveNodeSize(context);
if (npSize != null) infstr.append(npSize.getWidth().toString());
} else if (paramName.equalsIgnoreCase("length") && prim != null)
{
NodeInst ni = (NodeInst)no;
PrimitiveNodeSize npSize = ni.getPrimitiveNodeSize(context);
if (npSize != null) infstr.append(npSize.getLength().toString());
} else if (cni != null && pp != null)
{
// port name found: use its spice node
Network net = cni.getNetList().getNetwork(no, pp, 0);
CellSignal cs = cni.getCellSignal(net);
String portName = cs.getName();
if (segmentedNets.getUseParasitics()) {
PortInst pi = no.getNodeInst().findPortInstFromProto(pp);
portName = segmentedNets.getNetName(pi);
}
if (flatNetNames) {
portName = info.getUniqueNetName(net, ".");
}
infstr.append(portName);
} else if (no != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null)
{
// no port name found, look for variable name
Variable attrVar = null;
//Variable.Key varKey = Variable.findKey("ATTR_" + paramName);
if (varKey != null) {
attrVar = no.getVar(varKey);
if (attrVar == null) attrVar = no.getParameter(varKey);
}
if (attrVar == null) infstr.append("??"); else
{
String pVal = "?";
Variable parentVar = attrVar;
if (prototype != null && prototype instanceof Cell)
parentVar = ((Cell)prototype).getVar(attrVar.getKey());
if (!useCDL && Simulation.isSpiceUseCellParameters() &&
parentVar.getCode() == TextDescriptor.Code.SPICE) {
Object obj = context.evalSpice(attrVar, false);
if (obj != null)
pVal = obj.toString();
} else {
pVal = String.valueOf(context.evalVar(attrVar, no));
}
// if (attrVar.getCode() != TextDescriptor.Code.NONE)
if (infstr.inQuotes()) pVal = trimSingleQuotes(pVal); else
pVal = formatParam(pVal, attrVar.getUnit());
infstr.append(pVal);
}
} else {
// look for the network name
boolean found = false;
String hierName = null;
String [] names = paramName.split("\\.");
if (names.length > 1 && flatNetNames) {
// hierarchical name, down hierarchy
Netlist thisNetlist = info.getNetlist();
VarContext thisContext = context;
if (no != null) {
// push it back on, it got popped off in "embedSpice..."
thisContext = thisContext.push(no);
}
for (int i=0; i<names.length-1; i++) {
boolean foundno = false;
for (Iterator<Nodable> it = thisNetlist.getNodables(); it.hasNext(); ) {
Nodable subno = it.next();
if (subno.getName().equals(names[i])) {
if (subno.getProto() instanceof Cell) {
thisNetlist = thisNetlist.getNetlist(subno);
thisContext = thisContext.push(subno);
}
foundno = true;
continue;
}
}
if (!foundno) {
System.out.println("Unable to find "+names[i]+" in "+paramName);
break;
}
}
Network net = findNet(thisNetlist, names[names.length-1]);
if (net != null) {
HierarchyEnumerator.NetNameProxy proxy = new HierarchyEnumerator.NetNameProxy(
thisContext, ".x", net);
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
}
} else {
// net may be exported and named at higher level, use getUniqueName
Network net = findNet(info.getNetlist(), paramName);
if (net != null) {
if (flatNetNames) {
HierarchyEnumerator.NetNameProxy proxy = info.getUniqueNetNameProxy(net, ".x");
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
} else {
hierName = cni.getCellSignal(net).getName();
}
}
}
// convert to spice format
if (hierName != null) {
if (flatNetNames) {
if (hierName.indexOf(".x") > 0) {
hierName = "x"+hierName;
}
// remove x in front of net name
int i = hierName.lastIndexOf(".x");
if (i > 0)
hierName = hierName.substring(0, i+1) + hierName.substring(i+2);
else {
i = hierName.lastIndexOf("."+paramName);
if (i > 0) {
hierName = hierName.substring(0, i) + "_" + hierName.substring(i+1);
}
}
}
infstr.append(hierName);
found = true;
}
if (!found) {
System.out.println("Unable to lookup key $("+paramName+") in cell "+context.getInstPath("."));
}
}
}
return infstr.getStringBuffer();
}
private Network findNet(Netlist netlist, String netName) {
Network foundnet = null;
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(netName)) {
foundnet = net;
break;
}
}
return foundnet;
}
/**
* Get the global associated with this net. Returns null if net is
* not a global.
* @param net
* @return global associated with this net, or null if not global
*/
private Global getGlobal(Network net) {
Netlist netlist = net.getNetlist();
for (int i=0; i<netlist.getGlobals().size(); i++) {
Global g = netlist.getGlobals().get(i);
if (netlist.getNetwork(g) == net)
return g;
}
return null;
}
// /**
// * Check if the global cell signal is exported as with a global name,
// * rather than just being a global tied to some other export.
// * I.e., returns true if global "gnd" has been exported using name "gnd".
// * @param cs
// * @return true if global signal exported with global name
// */
// private boolean isGlobalExport(CellSignal cs) {
// if (!cs.isGlobal() || !cs.isExported()) return false;
// for (Iterator<Export> it = cs.getNetwork().getExports(); it.hasNext(); ) {
// Export ex = it.next();
// for (int i=0; i<ex.getNameKey().busWidth(); i++) {
// String name = ex.getNameKey().subname(i).canonicString();
// if (cs.getName().equals(name)) {
// return true;
// }
// }
// }
// return false;
// }
private boolean ignoreSubcktPort(CellSignal cs)
{
if (Simulation.isSpiceUseNodeNames() && spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) return true;
}
return false;
}
/**
* Class to take care of added networks in cell due to
* extracting resistance of arcs. Takes care of naming,
* addings caps at portinst locations (due to PI model end caps),
* and storing resistance of arcs.
* <P>
* A network is broken into segments at all PortInsts along the network.
* Each PortInst is given a new net segment name. These names are used
* to write out caps and resistors. Each Arc writes out a PI model
* (a cap on each end and a resistor in the middle). Sometimes, an arc
* has very little or zero resistance, or we want to ignore it. Then
* we must short two portinsts together into the same net segment.
* However, we do not discard the capacitance, but continue to add it up.
*/
private static class SegmentedNets {
private static Comparator<PortInst> PORT_INST_COMPARATOR = new Comparator<PortInst>() {
public int compare(PortInst p1, PortInst p2) {
if (p1 == p2) return 0;
int cmp = p1.getNodeInst().compareTo(p2.getNodeInst());
if (cmp != 0) return cmp;
if (p1.getPortIndex() < p2.getPortIndex()) return -1;
return 1;
}
};
private static class NetInfo implements Comparable {
private String netName = "unassigned";
private double cap = 0;
private TreeSet<PortInst> joinedPorts = new TreeSet<PortInst>(PORT_INST_COMPARATOR); // list of portInsts on this new net
/**
* Compares NetInfos by thier first PortInst.
* @param obj the other NetInfo.
* @return a comparison between the NetInfos.
*/
public int compareTo(Object obj) {
NetInfo that = (NetInfo)obj;
if (this.joinedPorts.isEmpty()) return that.joinedPorts.isEmpty() ? 0 : -1;
if (that.joinedPorts.isEmpty()) return 1;
return PORT_INST_COMPARATOR.compare(this.joinedPorts.first(), that.joinedPorts.first());
}
}
private HashMap<PortInst,NetInfo> segmentedNets; // key: portinst, obj: PortInstInfo
private HashMap<ArcInst,Double> arcRes; // key: arcinst, obj: Double (arc resistance)
boolean verboseNames = false; // true to give renamed nets verbose names
private CellNetInfo cni; // the Cell's net info
boolean useParasitics = false; // disable or enable netname remapping
private HashMap<Network,Integer> netCounters; // key: net, obj: Integer - for naming segments
private Cell cell;
private List<List<String>> shortedExports; // list of lists of export names shorted together
private HashMap<ArcInst,Double> longArcCaps; // for arcs to be broken up into multiple PI models, need to record cap
private HashMap<Network,Network> extractedNets; // keep track of extracted nets
private SegmentedNets(Cell cell, boolean verboseNames, CellNetInfo cni, boolean useParasitics) {
segmentedNets = new HashMap<PortInst,NetInfo>();
arcRes = new HashMap<ArcInst,Double>();
this.verboseNames = verboseNames;
this.cni = cni;
this.useParasitics = useParasitics;
netCounters = new HashMap<Network,Integer>();
this.cell = cell;
shortedExports = new ArrayList<List<String>>();
longArcCaps = new HashMap<ArcInst,Double>();
extractedNets = new HashMap<Network,Network>();
}
// don't call this method outside of SegmentedNets
// Add a new PortInst net segment
private NetInfo putSegment(PortInst pi, double cap) {
// create new info for PortInst
NetInfo info = segmentedNets.get(pi);
if (info == null) {
info = new NetInfo();
info.netName = getNewName(pi, info);
info.cap += cap;
if (isPowerGround(pi)) info.cap = 0; // note if you remove this line,
// you have to explicity short all
// power portinsts together, or you can get duplicate caps
info.joinedPorts.add(pi);
segmentedNets.put(pi, info);
} else {
info.cap += cap;
//assert(info.joinedPorts.contains(pi)); // should already contain pi if info already exists
}
return info;
}
// don't call this method outside of SegmentedNets
// Get a new name for the net segment associated with the portinst
private String getNewName(PortInst pi, NetInfo info) {
Network net = cni.getNetList().getNetwork(pi);
CellSignal cs = cni.getCellSignal(net);
if (!useParasitics || (!Simulation.isParasiticsExtractPowerGround() &&
isPowerGround(pi))) return cs.getName();
Integer i = netCounters.get(net);
if (i == null) {
i = new Integer(0);
netCounters.put(net, i);
}
// get new name
String name = info.netName;
Export ex = pi.getExports().hasNext() ? pi.getExports().next() : null;
//if (ex != null && ex.getName().equals(cs.getName())) {
if (ex != null) {
name = ex.getName();
} else {
if (i.intValue() == 0 && !cs.isExported()) // get rid of #0 if net not exported
name = cs.getName();
else {
if (verboseNames)
name = cs.getName() + "#" + i.intValue() + pi.getNodeInst().getName() + "_" + pi.getPortProto().getName();
else
name = cs.getName() + "#" + i.intValue();
}
i = new Integer(i.intValue() + 1);
netCounters.put(net, i);
}
//System.out.println("Created new segmented net name "+name+" for port "+pi.getPortProto().getName()+
// " on node "+pi.getNodeInst().getName()+" on net "+net.getName());
return name;
}
// short two net segments together by their portinsts
private void shortSegments(PortInst p1, PortInst p2) {
if (!segmentedNets.containsKey(p1))
putSegment(p1, 0);
if (!segmentedNets.containsKey(p2));
putSegment(p2, 0);
NetInfo info1 = segmentedNets.get(p1);
NetInfo info2 = segmentedNets.get(p2);
if (info1 == info2) return; // already joined
// short
//System.out.println("Shorted together "+info1.netName+ " and "+info2.netName);
info1.joinedPorts.addAll(info2.joinedPorts);
info1.cap += info2.cap;
if (TextUtils.STRING_NUMBER_ORDER.compare(info2.netName, info1.netName) < 0) {
// if (info2.netName.compareTo(info1.netName) < 0) {
info1.netName = info2.netName;
}
//info1.netName += info2.netName;
// replace info2 with info1, info2 is no longer used
// need to do for every portinst in merged segment
for (PortInst pi : info1.joinedPorts)
segmentedNets.put(pi, info1);
}
// get the segment name for the portinst.
// if no parasitics, this is just the CellSignal name.
private String getNetName(PortInst pi) {
if (!useParasitics || (isPowerGround(pi) &&
!Simulation.isParasiticsExtractPowerGround())) {
CellSignal cs = cni.getCellSignal(cni.getNetList().getNetwork(pi));
//System.out.println("CellSignal name for "+pi.getNodeInst().getName()+"."+pi.getPortProto().getName()+" is "+cs.getName());
//System.out.println("NETWORK NAMED "+cs.getName());
return cs.getName();
}
NetInfo info = segmentedNets.get(pi);
if (info == null) {
CellSignal cs = cni.getCellSignal(cni.getNetList().getNetwork(pi));
return cs.getName();
//info = putSegment(pi, 0);
}
//System.out.println("NETWORK INAMED "+info.netName);
return info.netName;
}
private void addArcRes(ArcInst ai, double res) {
// short out if both conns are power/ground
if (isPowerGround(ai.getHeadPortInst()) && isPowerGround(ai.getTailPortInst()) &&
!Simulation.isParasiticsExtractPowerGround()) {
shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
return;
}
arcRes.put(ai, new Double(res));
}
private boolean isPowerGround(PortInst pi) {
Network net = cni.getNetList().getNetwork(pi);
CellSignal cs = cni.getCellSignal(net);
if (cs.isPower() || cs.isGround()) return true;
if (cs.getName().startsWith("vdd")) return true;
if (cs.getName().startsWith("gnd")) return true;
return false;
}
/**
* Return list of NetInfos for unique segments
* @return a list of al NetInfos
*/
private TreeSet<NetInfo> getUniqueSegments() {
return new TreeSet<NetInfo>(segmentedNets.values());
}
private boolean getUseParasitics() {
return useParasitics;
}
// list of export names (Strings)
private void addShortedExports(List<String> exports) {
shortedExports.add(exports);
}
// list of lists of export names (Strings)
private Iterator<List<String>> getShortedExports() { return shortedExports.iterator(); }
public static int getNumPISegments(double res, double maxSeriesResistance) {
if (res <= 0) return 1;
int arcPImodels = 1;
arcPImodels = (int)(res/maxSeriesResistance); // need preference here
if ((res % maxSeriesResistance) != 0) arcPImodels++;
return arcPImodels;
}
// for arcs of larger than max series resistance, we need to break it up into
// multiple PI models. So, we need to store the cap associated with the arc
private void addArcCap(ArcInst ai, double cap) {
longArcCaps.put(ai, new Double(cap));
}
private double getArcCap(ArcInst ai) {
Double d = longArcCaps.get(ai);
return d.doubleValue();
}
public void addExtractedNet(Network net) {
extractedNets.put(net, net);
}
public boolean isExtractedNet(Network net) {
return extractedNets.containsKey(net);
}
}
private SegmentedNets getSegmentedNets(Cell cell) {
for (SegmentedNets seg : segmentedParasiticInfo) {
if (seg.cell == cell) return seg;
}
return null;
}
private void backAnnotateLayout()
{
Set<Cell> cellsToClear = new HashSet<Cell>();
List<PortInst> capsOnPorts = new ArrayList<PortInst>();
List<String> valsOnPorts = new ArrayList<String>();
List<ArcInst> resOnArcs = new ArrayList<ArcInst>();
List<Double> valsOnArcs = new ArrayList<Double>();
for (SegmentedNets segmentedNets : segmentedParasiticInfo)
{
Cell cell = segmentedNets.cell;
if (cell.getView() != View.LAYOUT) continue;
// gather cells to clear capacitor values
cellsToClear.add(cell);
// gather capacitor updates
for (SegmentedNets.NetInfo info : segmentedNets.getUniqueSegments())
{
PortInst pi = info.joinedPorts.iterator().next();
if (info.cap > cell.getTechnology().getMinCapacitance())
{
capsOnPorts.add(pi);
valsOnPorts.add(TextUtils.formatDouble(info.cap, 2) + "fF");
}
}
// gather resistor updates
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
resOnArcs.add(ai);
valsOnArcs.add(res);
}
}
new BackAnnotateJob(cellsToClear, capsOnPorts, valsOnPorts, resOnArcs, valsOnArcs);
}
private static class BackAnnotateJob extends Job
{
private Set<Cell> cellsToClear;
private List<PortInst> capsOnPorts;
private List<String> valsOnPorts;
private List<ArcInst> resOnArcs;
private List<Double> valsOnArcs;
private BackAnnotateJob(Set<Cell> cellsToClear, List<PortInst> capsOnPorts, List<String> valsOnPorts,
List<ArcInst> resOnArcs, List<Double> valsOnArcs)
{
super("Spice Layout Back Annotate", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.capsOnPorts = capsOnPorts;
this.valsOnPorts = valsOnPorts;
this.resOnArcs = resOnArcs;
this.valsOnArcs = valsOnArcs;
this.cellsToClear = cellsToClear;
startJob();
}
public boolean doIt() throws JobException
{
TextDescriptor ctd = TextDescriptor.getPortInstTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE);
TextDescriptor rtd = TextDescriptor.getArcTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE);
int capCount = 0;
int resCount = 0;
// clear caps on layout
for(Cell cell : cellsToClear)
{
// delete all C's already on layout
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
for (Iterator<PortInst> pit = ni.getPortInsts(); pit.hasNext(); )
{
PortInst pi = pit.next();
Variable var = pi.getVar(ATTR_C);
if (var != null) pi.delVar(var.getKey());
}
}
}
// add new C's
for(int i=0; i<capsOnPorts.size(); i++)
{
PortInst pi = capsOnPorts.get(i);
String str = valsOnPorts.get(i);
pi.newVar(ATTR_C, str, ctd);
resCount++;
}
// add new R's
for(int i=0; i<resOnArcs.size(); i++)
{
ArcInst ai = resOnArcs.get(i);
Double res = valsOnArcs.get(i);
// delete R if no new one
Variable var = ai.getVar(ATTR_R);
if (res == null && var != null)
ai.delVar(ATTR_R);
// change R if new one
if (res != null)
{
ai.newVar(ATTR_R, res, rtd);
resCount++;
}
}
System.out.println("Back-annotated "+resCount+" Resistors and "+capCount+" Capacitors");
return true;
}
}
/**
* These are nets that are either extracted when nothing else is extracted,
* or not extracted during extraction. They are specified via the top level
* net cell + name, any traversal of that net down the hierarchy is also not extracted.
*/
private static class ExemptedNets {
private HashMap<Cell,List<Net>> netsByCell; // key: cell, value: List of ExemptedNets.Net objects
private Set<Integer> exemptedNetIDs;
private static class Net {
private String name;
private double replacementCap;
}
private ExemptedNets(File file) {
netsByCell = new HashMap<Cell,List<Net>>();
exemptedNetIDs = new TreeSet<Integer>();
try {
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String line;
int lineno = 1;
System.out.println("Using exempted nets file "+file.getAbsolutePath());
while ((line = br.readLine()) != null) {
processLine(line, lineno);
lineno++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
return;
}
}
private void processLine(String line, int lineno) {
if (line == null) return;
if (line.trim().equals("")) return;
if (line.startsWith("#")) return; // comment
String parts[] = line.trim().split("\\s+");
if (parts.length < 3) {
System.out.println("Error on line "+lineno+": Expected 'LibraryName CellName NetName', but was "+line);
return;
}
Cell cell = getCell(parts[0], parts[1]);
if (cell == null) return;
double cap = 0;
if (parts.length > 3) {
try {
cap = Double.parseDouble(parts[3]);
} catch (NumberFormatException e) {
System.out.println("Error on line "+lineno+" "+e.getMessage());
}
}
List<Net> list = netsByCell.get(cell);
if (list == null) {
list = new ArrayList<Net>();
netsByCell.put(cell, list);
}
Net n = new Net();
n.name = parts[2];
n.replacementCap = cap;
list.add(n);
}
private Cell getCell(String library, String cell) {
Library lib = Library.findLibrary(library);
if (lib == null) {
System.out.println("Could not find library "+library);
return null;
}
Cell c = lib.findNodeProto(cell);
if (c == null) {
System.out.println("Could not find cell "+cell+" in library "+library);
return null;
}
return c;
}
/**
* Get the netIDs for all exempted nets in the cell specified by the CellInfo
* @param info
*/
private void setExemptedNets(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
List<Net> netNames = netsByCell.get(cell);
if (netNames == null) return; // nothing for this cell
for (Net n : netNames) {
String netName = n.name;
Network net = findNetwork(info, netName);
if (net == null) {
System.out.println("Cannot find network "+netName+" in cell "+cell.describe(true));
continue;
}
// get the global ID
System.out.println("exemptedNets: specified net "+cell.describe(false)+" "+netName);
int netID = info.getNetID(net);
exemptedNetIDs.add(new Integer(netID));
}
}
private Network findNetwork(HierarchyEnumerator.CellInfo info, String name) {
for (Iterator<Network> it = info.getNetlist().getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(name)) return net;
}
return null;
}
private boolean isExempted(int netID) {
return exemptedNetIDs.contains(new Integer(netID));
}
private double getReplacementCap(Cell cell, Network net) {
List<Net> netNames = netsByCell.get(cell);
if (netNames == null) return 0; // nothing for this cell
for (Net n : netNames) {
if (net.hasName(n.name)) {
return n.replacementCap;
}
}
return 0;
}
}
/****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/
/**
* Method to adjust a cell name to be safe for Spice output.
* @param name the cell name.
* @return the name, adjusted for Spice output.
*/
protected String getSafeCellName(String name)
{
return getSafeNetName(name, false);
}
/** Method to return the proper name of Power */
protected String getPowerName(Network net)
{
if (net != null)
{
// favor "vdd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("vdd")) return "vdd";
}
}
return null;
}
/** Method to return the proper name of Ground */
protected String getGroundName(Network net)
{
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) return "0";
if (net != null)
{
// favor "gnd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("gnd")) return "gnd";
}
}
return null;
}
/** Method to return the proper name of a Global signal */
protected String getGlobalName(Global glob) { return glob.getName(); }
/** Method to report that export names do NOT take precedence over
* arc names when determining the name of the network. */
protected boolean isNetworksUseExportedNames() { return false; }
/** Method to report that library names are NOT always prepended to cell names. */
protected boolean isLibraryNameAlwaysAddedToCellName() { return false; }
/** Method to report that aggregate names (busses) are not used. */
protected boolean isAggregateNamesSupported() { return false; }
/** Abstract method to decide whether aggregate names (busses) can have gaps in their ranges. */
protected boolean isAggregateNameGapsSupported() { return false; }
/** Method to report that not to choose best export name among exports connected to signal. */
protected boolean isChooseBestExportName() { return false; }
/** Method to report whether input and output names are separated. */
protected boolean isSeparateInputAndOutput() { return false; }
/** If the netlister has requirments not to netlist certain cells and their
* subcells, override this method.
* If this cell has a spice template, skip it
*/
protected boolean skipCellAndSubcells(Cell cell)
{
// skip if there is a template
Variable varTemplate = null;
varTemplate = getEngineTemplate(cell);
if (varTemplate != null) return true;
// look for a model file for the current cell, can come from pref or on cell
String fileName = null;
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
fileName = CellModelPrefs.spiceModelPrefs.getModelFile(cell);
}
varTemplate = cell.getVar(SPICE_NETLIST_FILE_KEY);
if (varTemplate != null) {
Object obj = varTemplate.getObject();
if (obj instanceof String) {
String str = (String)obj;
if (!str.equals("") && !str.equals("*Undefined"))
fileName = str;
}
}
if (fileName != null) {
if (!modelOverrides.containsKey(cell))
{
String absFileName = fileName;
if (!fileName.startsWith("/") && !fileName.startsWith("\\")) {
File spiceFile = new File(filePath);
absFileName = (new File(spiceFile.getParent(), fileName)).getPath();
}
boolean alreadyIncluded = false;
for (String includeFile : modelOverrides.values()) {
if (absFileName.equals(includeFile))
alreadyIncluded = true;
}
if (alreadyIncluded) {
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
multiLinePrint(true, "* "+fileName+" (already included) \n");
} else {
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
addIncludeFile(fileName);
}
modelOverrides.put(cell, absFileName);
}
return true;
}
return false;
}
/**
* Method called when a cell is skipped.
* Performs any checking to validate that no error occurs.
*/
protected void validateSkippedCell(HierarchyEnumerator.CellInfo info) {
String fileName = modelOverrides.get(info.getCell());
if (fileName != null) {
// validate included file
SpiceNetlistReader reader = new SpiceNetlistReader();
try {
reader.readFile(fileName, false);
HierarchyEnumerator.CellInfo parentInfo = info.getParentInfo();
Nodable no = info.getParentInst();
String parameterizedName = info.getCell().getName();
if (no != null && parentInfo != null) {
parameterizedName = parameterizedName(no, parentInfo.getContext());
}
CellNetInfo cni = getCellNetInfo(parameterizedName);
SpiceSubckt subckt = reader.getSubckt(parameterizedName);
if (cni != null && subckt != null) {
if (subckt == null) {
System.out.println("Error: No subckt for "+parameterizedName+" found in included file: "+fileName);
} else {
List<String> signals = new ArrayList<String>();
for (Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); ) {
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
signals.add(cs.getName());
}
List<String> subcktSignals = subckt.getPorts();
if (signals.size() != subcktSignals.size()) {
System.out.println("Warning: wrong number of ports for subckt "+
parameterizedName+": expected "+signals.size()+", but found "+
subcktSignals.size()+", in included file "+fileName);
}
int len = Math.min(signals.size(), subcktSignals.size());
for (int i=0; i<len; i++) {
String s1 = signals.get(i);
String s2 = subcktSignals.get(i);
if (!s1.equalsIgnoreCase(s2)) {
System.out.println("Warning: port "+i+" of subckt "+parameterizedName+
" is named "+s1+" in Electric, but "+s2+" in included file "+fileName);
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Error validating included file for cell "+info.getCell().describe(true)+": "+e.getMessage());
}
}
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
protected String getSafeNetName(String name, boolean bus)
{
return getSafeNetName(name, bus, legalSpiceChars, spiceEngine);
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
public static String getSafeNetName(String name)
{
String legalSpiceChars = SPICELEGALCHARS;
if (Simulation.getSpiceEngine() == Simulation.SpiceEngine.SPICE_ENGINE_P)
legalSpiceChars = PSPICELEGALCHARS;
return getSafeNetName(name, false, legalSpiceChars, Simulation.getSpiceEngine());
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
private static String getSafeNetName(String name, boolean bus, String legalSpiceChars, Simulation.SpiceEngine spiceEngine)
{
// simple names are trivially accepted as is
boolean allAlNum = true;
int len = name.length();
if (len <= 0) return name;
for(int i=0; i<len; i++)
{
boolean valid = TextUtils.isLetterOrDigit(name.charAt(i));
if (i == 0) valid = Character.isLetter(name.charAt(i));
if (!valid)
{
allAlNum = false;
break;
}
}
if (allAlNum) return name;
StringBuffer sb = new StringBuffer();
if (TextUtils.isDigit(name.charAt(0)) &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_G &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_P &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_2) sb.append('_');
for(int t=0; t<name.length(); t++)
{
char chr = name.charAt(t);
boolean legalChar = TextUtils.isLetterOrDigit(chr);
if (!legalChar)
{
for(int j=0; j<legalSpiceChars.length(); j++)
{
char legalChr = legalSpiceChars.charAt(j);
if (chr == legalChr) { legalChar = true; break; }
}
}
if (!legalChar) chr = '_';
sb.append(chr);
}
return sb.toString();
}
/** Tell the Hierarchy enumerator how to short resistors */
@Override
protected Netlist.ShortResistors getShortResistors() {
// TODO use the value of Simulation.getSpiceShortResistors()
// switch (Simulation.getSpiceShortResistors())
// {
// case 0: return Netlist.ShortResistors.NO;
// case 1: return Netlist.ShortResistors.PARASITIC;
// case 2: return Netlist.ShortResistors.ALL;
// }
if (useCDL && Simulation.getCDLIgnoreResistors())
return Netlist.ShortResistors.PARASITIC;
// this option is used for writing spice netlists for LVS and RCX
if (Simulation.isSpiceIgnoreParasiticResistors())
return Netlist.ShortResistors.PARASITIC;
return Netlist.ShortResistors.NO;
}
private Netlist.ShortResistors getShortResistorsFlat() {
return Netlist.ShortResistors.ALL;
}
/**
* Method to tell whether the topological analysis should mangle cell names that are parameterized.
*/
protected boolean canParameterizeNames() { return true; } //return !useCDL; }
/**
* Method to tell set a limit on the number of characters in a name.
* @return the limit to name size (SPICE limits to 32 character names?????).
*/
protected int maxNameLength() { if (useCDL) return CDLMAXLENSUBCKTNAME; return SPICEMAXLENSUBCKTNAME; }
protected boolean enumerateLayoutView(Cell cell) {
return (CellModelPrefs.spiceModelPrefs.isUseLayoutView(cell));
}
/******************** DECK GENERATION SUPPORT ********************/
/**
* write a header for "cell" to spice deck "sim_spice_file"
* The model cards come from a file specified by tech:~.SIM_spice_model_file
* or else tech:~.SIM_spice_header_level%ld
* The spice model file can be located in el_libdir
*/
private void writeHeader(Cell cell)
{
// Print the header line for SPICE
multiLinePrint(true, "*** SPICE deck for cell " + cell.noLibDescribe() +
" from library " + cell.getLibrary().getName() + "\n");
emitCopyright("*** ", "");
if (User.isIncludeDateAndVersionInOutput())
{
multiLinePrint(true, "*** Created on " + TextUtils.formatDate(topCell.getCreationDate()) + "\n");
multiLinePrint(true, "*** Last revised on " + TextUtils.formatDate(topCell.getRevisionDate()) + "\n");
multiLinePrint(true, "*** Written on " + TextUtils.formatDate(new Date()) +
" by Electric VLSI Design System, version " + Version.getVersion() + "\n");
} else
{
multiLinePrint(true, "*** Written by Electric VLSI Design System\n");
}
String foundry = layoutTechnology.getSelectedFoundry() == null ? "" : (", foundry "+layoutTechnology.getSelectedFoundry().toString());
multiLinePrint(true, "*** Layout tech: "+layoutTechnology.getTechName()+foundry+"\n");
multiLinePrint(true, "*** UC SPICE *** , MIN_RESIST " + layoutTechnology.getMinResistance() +
", MIN_CAPAC " + layoutTechnology.getMinCapacitance() + "FF\n");
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
if (useParasitics) {
for (Layer layer : layoutTechnology.getLayersSortedByHeight()) {
if (layer.isPseudoLayer()) continue;
double edgecap = layer.getEdgeCapacitance();
double areacap = layer.getCapacitance();
double res = layer.getResistance();
if (edgecap != 0 || areacap != 0 || res != 0) {
multiLinePrint(true, "*** "+layer.getName()+":\tareacap="+areacap+"FF/um^2,\tedgecap="+edgecap+"FF/um,\tres="+res+"ohms/sq\n");
}
}
}
multiLinePrint(false, ".OPTIONS NOMOD NOPAGE\n");
// if sizes to be written in lambda, tell spice conversion factor
if (Simulation.isSpiceWriteTransSizeInLambda())
{
double scale = layoutTechnology.getScale();
multiLinePrint(true, "*** Lambda Conversion ***\n");
multiLinePrint(false, ".opt scale=" + TextUtils.formatDouble(scale / 1000.0, 3) + "U\n\n");
}
// see if spice model/option cards from file if specified
String headerFile = Simulation.getSpiceHeaderCardInfo();
if (headerFile.length() > 0 && !headerFile.startsWith(SPICE_NOEXTENSION_PREFIX))
{
if (headerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String headerPath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = headerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Header Card '" + fileName + "' is included");
return;
}
System.out.println("Spice Header Card '" + fileName + "' cannot be loaded");
} else
{
// normal header file specified
File test = new File(headerFile);
if (!test.exists())
System.out.println("Warning: cannot find model file '" + headerFile + "'");
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(headerFile);
return;
}
}
// no header files: write predefined header for this level and technology
int level = TextUtils.atoi(Simulation.getSpiceLevel());
String [] header = null;
switch (level)
{
case 1: header = layoutTechnology.getSpiceHeaderLevel1(); break;
case 2: header = layoutTechnology.getSpiceHeaderLevel2(); break;
case 3: header = layoutTechnology.getSpiceHeaderLevel3(); break;
}
if (header != null)
{
for(int i=0; i<header.length; i++)
multiLinePrint(false, header[i] + "\n");
return;
}
System.out.println("WARNING: no model cards for SPICE level " + level +
" in " + layoutTechnology.getTechName() + " technology");
}
/**
* Write a trailer from an external file, defined as a variable on
* the current technology in this library: tech:~.SIM_spice_trailer_file
* if it is available.
*/
private void writeTrailer(Cell cell)
{
// get spice trailer cards from file if specified
String trailerFile = Simulation.getSpiceTrailerCardInfo();
if (trailerFile.length() > 0 && !trailerFile.startsWith(SPICE_NOEXTENSION_PREFIX))
{
if (trailerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String trailerpath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = trailerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = trailerpath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Trailer Card '" + fileName + "' is included");
}
else
System.out.println("Spice Trailer Card '" + fileName + "' cannot be loaded");
} else
{
// normal trailer file specified
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(trailerFile);
System.out.println("Spice Trailer Card '" + trailerFile + "' is included");
}
}
}
/**
* Function to write a two port device to the file. Complain about any missing connections.
* Determine the port connections from the portprotos in the instance
* prototype. Get the part number from the 'part' number value;
* increment it. The type of device is declared in type; extra is the string
* data acquired before calling here.
* If the device is connected to the same net at both ends, do not
* write it. Is this OK?
*/
private void writeTwoPort(NodeInst ni, String partName, String extra, CellNetInfo cni, Netlist netList, VarContext context, SegmentedNets segmentedNets)
{
PortInst port0 = ni.getPortInst(0);
PortInst port1 = ni.getPortInst(1);
Network net0 = netList.getNetwork(port0);
Network net1 = netList.getNetwork(port1);
CellSignal cs0 = cni.getCellSignal(net0);
CellSignal cs1 = cni.getCellSignal(net1);
// make sure the component is connected to nets
if (cs0 == null || cs1 == null)
{
String message = "WARNING: " + ni + " component not fully connected in " + ni.getParent();
dumpErrorMessage(message);
}
if (cs0 != null && cs1 != null && cs0 == cs1)
{
String message = "WARNING: " + ni + " component appears to be shorted on net " + net0.toString() +
" in " + ni.getParent();
dumpErrorMessage(message);
return;
}
if (ni.getName() != null) partName += getSafeNetName(ni.getName(), false);
// add Mfactor if there
StringBuffer sbExtra = new StringBuffer(extra);
writeMFactor(context, ni, sbExtra);
String name0 = cs0.getName();
String name1 = cs1.getName();
if (segmentedNets.getUseParasitics()) {
name0 = segmentedNets.getNetName(port0);
name1 = segmentedNets.getNetName(port1);
}
multiLinePrint(false, partName + " " + name1 + " " + name0 + " " + sbExtra.toString() + "\n");
}
/**
* This adds formatting to a Spice parameter value. It adds single quotes
* around the param string if they do not already exist.
* @param param the string param value (without the name= part).
* @return a param string with single quotes around it
*/
private String formatParam(String param, TextDescriptor.Unit u)
{
// first remove quotes
String value = trimSingleQuotes(param);
// see if the result evaluates to a number
if (TextUtils.isANumberPostFix(value)) return value;
// if purely numeric, try converting to proper units
try {
Double v = Double.valueOf(value);
if (u == TextDescriptor.Unit.DISTANCE)
return TextUtils.formatDoublePostFix(v.doubleValue());
return value;
} catch (NumberFormatException e) {}
// not a number: if Spice engine cannot handle quotes, return stripped value
switch (spiceEngine)
{
case SPICE_ENGINE_2:
case SPICE_ENGINE_3:
return value;
}
// not a number but Spice likes quotes, enclose it
return "'" + value + "'";
}
private String trimSingleQuotes(String param) {
if (param.startsWith("'") && param.endsWith("'")) {
return param.substring(1, param.length()-1);
}
return param;
}
/******************** PARASITIC CALCULATIONS ********************/
/**
* Method to recursively determine the area of diffusion and capacitance
* associated with port "pp" of nodeinst "ni". If the node is mult_layer, then
* determine the dominant capacitance layer, and add its area; all other
* layers will be added as well to the extra_area total.
* Continue out of the ports on a complex cell
*/
private void addNodeInformation(Netlist netList, HashMap<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}
/**
* Method to recursively determine the area of diffusion, capacitance, (NOT
* resistance) on arc "ai". If the arc contains active device diffusion, then
* it will contribute to the area of sources and drains, and the other layers
* will be ignored. This is not quite the same as the rule used for
* contact (node) structures. Note: the earlier version of this
* function assumed that diffusion arcs would always have zero capacitance
* values for the other layers; this produces an error if any of these layers
* have non-zero values assigned for other reasons. So we will check for the
* function of the arc, and if it contains active device, we will ignore any
* other layers
*/
private void addArcInformation(PolyMerge merge, ArcInst ai)
{
boolean isDiffArc = ai.isDiffusionArc(); // check arc function
if (useNewParasitics && !isDiffArc) {
// all cap besides diffusion is handled by segmented nets
return;
}
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (layer.isDiffusionLayer()||
(!isDiffArc && layer.getCapacitance() > 0.0))
merge.addPolygon(layer, poly);
}
}
/******************** TEXT METHODS ********************/
/**
* Method to insert an "include" of file "filename" into the stream "io".
*/
private void addIncludeFile(String fileName)
{
if (useCDL) {
multiLinePrint(false, ".include "+ fileName + "\n");
return;
}
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_S)
{
multiLinePrint(false, ".include " + fileName + "\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_CALIBRE)
{
multiLinePrint(false, ".include '" + fileName + "'\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P)
{
multiLinePrint(false, ".INC " + fileName + "\n");
}
}
/******************** SUPPORT ********************/
private static final boolean CELLISEMPTYDEBUG = false;
private HashMap<Cell,Boolean> checkedCells = new HashMap<Cell,Boolean>();
private boolean cellIsEmpty(Cell cell)
{
Boolean b = checkedCells.get(cell);
if (b != null) return b.booleanValue();
boolean empty = true;
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
if (useParasitics) return false;
List<Cell> emptyCells = new ArrayList<Cell>();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
// if node is a cell, check if subcell is empty
if (ni.isCellInstance()) {
// ignore own icon
if (ni.isIconOfParent()) {
continue;
}
Cell iconCell = (Cell)ni.getProto();
Cell schCell = iconCell.contentsView();
if (schCell == null) schCell = iconCell;
if (cellIsEmpty(schCell)) {
if (CELLISEMPTYDEBUG) emptyCells.add(schCell);
continue;
}
empty = false;
break;
}
// otherwise, this is a primitive
PrimitiveNode.Function fun = ni.getFunction();
// Passive devices used by spice/CDL
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
empty = false;
break;
}
// active devices used by Spice/CDL
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
empty = false;
break;
}
// check for spice code on pins
if (ni.getVar(SPICE_CARD_KEY) != null) {
empty = false;
break;
}
}
// look for a model file on the current cell
if (modelOverrides.get(cell) != null) {
empty = false;
}
// check for spice template
if (getEngineTemplate(cell) != null) {
empty = false;
}
// empty
if (CELLISEMPTYDEBUG && empty) {
System.out.println(cell+" is empty and contains the following empty cells:");
for (Cell c : emptyCells)
System.out.println(" "+c.describe(true));
}
checkedCells.put(cell, new Boolean(empty));
return empty;
}
/******************** LOW-LEVEL OUTPUT METHODS ********************/
/**
* Method to report an error that is built in the infinite string.
* The error is sent to the messages window and also to the SPICE deck "f".
*/
private void dumpErrorMessage(String message)
{
multiLinePrint(true, "*** " + message + "\n");
System.out.println(message);
}
/**
* Formatted output to file "stream". All spice output is in upper case.
* The buffer can contain no more than 1024 chars including the newlinelastMoveTo
* and null characters.
* Doesn't return anything.
*/
private void multiLinePrint(boolean isComment, String str)
{
// put in line continuations, if over 78 chars long
char contChar = '+';
if (isComment) contChar = '*';
int lastSpace = -1;
int count = 0;
boolean insideQuotes = false;
int lineStart = 0;
for (int pt = 0; pt < str.length(); pt++)
{
char chr = str.charAt(pt);
// if (sim_spice_machine == SPICE2)
// {
// if (islower(*pt)) *pt = toupper(*pt);
// }
if (chr == '\n')
{
printWriter.print(str.substring(lineStart, pt+1));
count = 0;
lastSpace = -1;
lineStart = pt+1;
} else
{
if (chr == ' ' && !insideQuotes) lastSpace = pt;
if (chr == '\'') insideQuotes = !insideQuotes;
count++;
if (count >= spiceMaxLenLine && !insideQuotes && lastSpace > -1)
{
String partial = str.substring(lineStart, lastSpace+1);
printWriter.print(partial + "\n" + contChar);
count = count - partial.length();
lineStart = lastSpace+1;
lastSpace = -1;
}
}
}
if (lineStart < str.length())
{
String partial = str.substring(lineStart);
printWriter.print(partial);
}
}
public static class FlatSpiceCodeVisitor extends HierarchyEnumerator.Visitor {
private PrintWriter printWriter;
private PrintWriter spicePrintWriter;
private String filePath;
Spice spice; // just used for file writing and formatting
SegmentedNets segNets;
public FlatSpiceCodeVisitor(String filePath, Spice spice) {
this.spice = spice;
this.spicePrintWriter = spice.printWriter;
this.filePath = filePath;
spice.spiceMaxLenLine = 1000;
segNets = null;
}
public boolean enterCell(HierarchyEnumerator.CellInfo info) {
return true;
}
public void exitCell(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CODE_FLAT_KEY);
if (cardVar != null) {
if (printWriter == null) {
try {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath)));
} catch (IOException e) {
System.out.println("Unable to open "+filePath+" for write.");
return;
}
spice.printWriter = printWriter;
segNets = new SegmentedNets(null, false, null, false);
}
spice.emitEmbeddedSpice(cardVar, info.getContext(), segNets, info, true);
}
}
}
public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
return true;
}
public void close() {
if (printWriter != null) {
System.out.println(filePath+" written");
spice.printWriter = spicePrintWriter;
printWriter.close();
}
spice.spiceMaxLenLine = SPICEMAXLENLINE;
}
}
}
| false | true | protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics)
{
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
double cap = 0;
double res = 0;
//System.out.println("--Processing arc "+ai.getName());
boolean extractNet = true;
if (segmentedNets.isPowerGround(ai.getHeadPortInst()))
extractNet = false;
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
extractNet = false;
Network net = netList.getNetwork(ai, 0);
if (extractNet && Simulation.isParasiticsUseExemptedNetsFile()) {
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
extractNet = false;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net))) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
extractNet = true;
}
} else {
extractNet = false;
}
}
}
if (extractNet) {
// figure out res and cap, see if we should ignore it
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaBaseWidth() * scale / 1000; // width in microns
// double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer()) {
if (Simulation.isParasiticsExtractsC()) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
}
if (Simulation.isParasiticsExtractsR()) {
res = length/width * layer.getResistance();
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (res <= cell.getTechnology().getMinResistance()) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
//System.out.println("Using resistance of "+res+" for arc "+ai.getName());
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
segmentedNets.addExtractedNet(net);
} else {
//System.out.println(" not extracting arc "+ai.getName());
// don't need to short arcs on networks that aren't extracted, since it is
// guaranteed that both ends of the arc are named the same.
//segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
//System.out.println("--Processing gate "+ni.getName());
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = ni.getTransistorAltGatePort();
Network gateNet0 = netList.getNetwork(gate0);
if ((gate0 != gate1) && segmentedNets.isExtractedNet(gateNet0)) {
//System.out.println("Shorting gate "+ni.getName()+" ports "
// +gate0.getPortProto().getName()+" and "
// +gate1.getPortProto().getName());
segmentedNets.shortSegments(gate0, gate1);
}
}
// merge wells
} else {
//System.out.println("--Processing subcell "+ni.getName());
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
Network net = netList.getNetwork(pi);
if (segmentedNets.isExtractedNet(net))
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
PortProto pp = subCS.getExport();
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (Simulation.isSpiceUseNodeNames() && spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (pp == null) continue;
}
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal());
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && getSegmentedNets((Cell)no.getProto()) != null) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit());
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit());
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE);
}
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
else if (fun == PrimitiveNode.Function.WRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE);
}
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) {
extra = "rnwod "+extra;
}
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) {
extra = "rpwod "+extra;
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit());
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit());
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics)
{
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap, 2);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else
{
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
| protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell) {
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// make sure power and ground appear at the top level
if (cell == topCell && !Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
// create list of electrical nets in this cell
HashMap<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
// create SpiceNet objects for all networks in the cell
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
// create a "SpiceNet" for the network
SpiceNet spNet = new SpiceNet();
spNet.network = net;
spNet.transistorCount = 0;
spNet.diffArea = 0;
spNet.diffPerim = 0;
spNet.nonDiffCapacitance = 0;
spNet.merge = new PolyMerge();
spiceNetMap.put(net, spNet);
}
// create list of segemented networks for parasitic extraction
boolean verboseSegmentedNames = Simulation.isParasiticsUseVerboseNaming();
boolean useParasitics = useNewParasitics && (!useCDL) &&
Simulation.isSpiceUseParasitics() && (cell.getView() == View.LAYOUT);
SegmentedNets segmentedNets = new SegmentedNets(cell, verboseSegmentedNames, cni, useParasitics);
segmentedParasiticInfo.add(segmentedNets);
if (useParasitics)
{
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
//System.out.println("\n Finding parasitics for cell "+cell.describe(false));
HashMap<Network,Network> exemptedNetsFound = new HashMap<Network,Network>();
for (Iterator<ArcInst> ait = cell.getArcs(); ait.hasNext(); ) {
ArcInst ai = ait.next();
double cap = 0;
double res = 0;
//System.out.println("--Processing arc "+ai.getName());
boolean extractNet = true;
if (segmentedNets.isPowerGround(ai.getHeadPortInst()))
extractNet = false;
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC)
extractNet = false;
Network net = netList.getNetwork(ai, 0);
if (extractNet && Simulation.isParasiticsUseExemptedNetsFile()) {
// ignore nets in exempted nets file
if (Simulation.isParasiticsIgnoreExemptedNets()) {
// check if this net is exempted
if (exemptedNets.isExempted(info.getNetID(net))) {
extractNet = false;
cap = 0;
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Not extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
cap = exemptedNets.getReplacementCap(cell, net);
}
}
// extract only nets in exempted nets file
} else {
if (exemptedNets.isExempted(info.getNetID(net))) {
if (!exemptedNetsFound.containsKey(net)) {
System.out.println("Extracting net "+cell.describe(false)+" "+net.getName());
exemptedNetsFound.put(net, net);
extractNet = true;
}
} else {
extractNet = false;
}
}
}
if (extractNet) {
// figure out res and cap, see if we should ignore it
double length = ai.getLambdaLength() * scale / 1000; // length in microns
double width = ai.getLambdaBaseWidth() * scale / 1000; // width in microns
// double width = ai.getLambdaFullWidth() * scale / 1000; // width in microns
double area = length * width;
double fringe = length*2;
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != layoutTechnology) continue;
// if (layer.isPseudoLayer()) continue;
if (!layer.isDiffusionLayer()) {
if (Simulation.isParasiticsExtractsC()) {
double areacap = area * layer.getCapacitance();
double fringecap = fringe * layer.getEdgeCapacitance();
cap = areacap + fringecap;
}
if (Simulation.isParasiticsExtractsR()) {
res = length/width * layer.getResistance();
}
}
}
int arcPImodels = SegmentedNets.getNumPISegments(res, layoutTechnology.getMaxSeriesResistance());
// add caps
segmentedNets.putSegment(ai.getHeadPortInst(), cap/(arcPImodels+1));
segmentedNets.putSegment(ai.getTailPortInst(), cap/(arcPImodels+1));
if (res <= cell.getTechnology().getMinResistance()) {
// short arc
segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
} else {
//System.out.println("Using resistance of "+res+" for arc "+ai.getName());
segmentedNets.addArcRes(ai, res);
if (arcPImodels > 1)
segmentedNets.addArcCap(ai, cap); // need to store cap later to break it up
}
segmentedNets.addExtractedNet(net);
} else {
//System.out.println(" not extracting arc "+ai.getName());
// don't need to short arcs on networks that aren't extracted, since it is
// guaranteed that both ends of the arc are named the same.
//segmentedNets.shortSegments(ai.getHeadPortInst(), ai.getTailPortInst());
}
}
// Don't take into account gate resistance: so we need to short two PortInsts
// of gate together if this is layout
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
if (!ni.isCellInstance()) {
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
//System.out.println("--Processing gate "+ni.getName());
PortInst gate0 = ni.getTransistorGatePort();
PortInst gate1 = ni.getTransistorAltGatePort();
Network gateNet0 = netList.getNetwork(gate0);
if ((gate0 != gate1) && segmentedNets.isExtractedNet(gateNet0)) {
//System.out.println("Shorting gate "+ni.getName()+" ports "
// +gate0.getPortProto().getName()+" and "
// +gate1.getPortProto().getName());
segmentedNets.shortSegments(gate0, gate1);
}
}
// merge wells
} else {
//System.out.println("--Processing subcell "+ni.getName());
// short together pins if shorted by subcell
Cell subCell = (Cell)ni.getProto();
SegmentedNets subNets = getSegmentedNets(subCell);
// list of lists of shorted exports
if (subNets != null) { // subnets may be null if mixing schematics with layout technologies
for (Iterator<List<String>> it = subNets.getShortedExports(); it.hasNext(); ) {
List<String> exports = it.next();
PortInst pi1 = null;
// list of exports shorted together
for (String exportName : exports) {
// get portinst on node
PortInst pi = ni.findPortInst(exportName);
if (pi1 == null) {
pi1 = pi; continue;
}
Network net = netList.getNetwork(pi);
if (segmentedNets.isExtractedNet(net))
segmentedNets.shortSegments(pi1, pi);
}
}
}
}
} // for (cell.getNodes())
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun == PrimitiveNode.Function.TRAEMES || fun == PrimitiveNode.Function.TRA4EMES ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRA4DMES ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS) nmosTrans++; else
if (fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && cs.getExport() != null) {
Network net = cs.getNetwork();
HashMap<String,List<String>> shortedExportsMap = new HashMap<String,List<String>>();
// For a single logical network, we need to:
// 1) treat certain exports as separate so as not to short resistors on arcs between the exports
// 2) join certain exports that do not have resistors on arcs between them, and record this information
// so that the next level up knows to short networks connection to those exports.
for (Iterator<Export> it = net.getExports(); it.hasNext(); ) {
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = segmentedNets.getNetName(pi);
// exports are shorted if their segmented net names are the same (case (2))
List<String> shortedExports = shortedExportsMap.get(name);
if (shortedExports == null) {
shortedExports = new ArrayList<String>();
shortedExportsMap.put(name, shortedExports);
// this is the first occurance of this segmented network,
// use the name as the export (1)
infstr.append(" " + name);
}
shortedExports.add(e.getName());
}
// record shorted exports
for (List<String> shortedExports : shortedExportsMap.values()) {
if (shortedExports.size() > 1) {
segmentedNets.addShortedExports(shortedExports);
}
}
} else {
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
}
// for(Iterator it = cell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// infstr.append(" " + paramVar.getTrueName() + "=" + paramVar.getPureValue(-1));
// }
}
// Writing M factor
//writeMFactor(cell, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// look for a SPICE template on the prototype
Variable varTemplate = null;
varTemplate = getEngineTemplate(subCell);
// varTemplate = subCell.getVar(preferedEngineTemplateKey);
// if (varTemplate == null)
// varTemplate = subCell.getVar(SPICE_TEMPLATE_KEY);
// handle templates
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts) {
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto))
continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with
// swapped-in layout subcells
if (pp != null && (cell.getView() == View.SCHEMATIC) && (subCni.getCell().getView() == View.LAYOUT)) {
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); ) {
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName())) {
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found) {
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
net = netList.getNetwork(no, subCS.getGlobal()); else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
if (useParasitics && !cs.isGlobal() && getSegmentedNets((Cell)no.getProto()) != null) {
// connect to all exports (except power and ground of subcell net)
SegmentedNets subSegmentedNets = getSegmentedNets((Cell)no.getProto());
Network subNet = subCS.getNetwork();
List<String> exportNames = new ArrayList<String>();
for (Iterator<Export> it = subNet.getExports(); it.hasNext(); ) {
// get subcell export, unless collapsed due to less than min R
Export e = it.next();
PortInst pi = e.getOriginalPort();
String name = subSegmentedNets.getNetName(pi);
if (exportNames.contains(name)) continue;
exportNames.add(name);
// ok, there is a port on the subckt on this subcell for this export,
// now get the appropriate network in this cell
pi = no.getNodeInst().findPortInstFromProto(no.getProto().findPortProto(e.getNameKey()));
name = segmentedNets.getNetName(pi);
infstr.append(" " + name);
}
} else {
String name = cs.getName();
if (segmentedNets.getUseParasitics()) {
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) {
infstr.append(" /" + subCni.getParameterizedName());
} else {
infstr.append(" " + subCni.getParameterizedName());
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
Variable instVar = no.getVar(paramVar.getKey());
String paramStr = "??";
if (instVar != null) {
if (paramVar.getCode() != TextDescriptor.Code.SPICE) continue;
Object obj = context.evalSpice(instVar, false);
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit());
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
// for(Iterator it = subCell.getVariables(); it.hasNext(); )
// {
// Variable paramVar = it.next();
// if (!paramVar.isParam()) continue;
// Variable instVar = no.getVar(paramVar.getKey());
// String paramStr = "??";
// if (instVar != null) paramStr = formatParam(trimSingleQuotes(String.valueOf(context.evalVar(instVar))));
// infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
// }
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (resistVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit());
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE);
}
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
else if (fun == PrimitiveNode.Function.WRESIST) {
partName = "XR";
double width = ni.getYSize();
double length = ni.getXSize();
SizeOffset offset = ni.getSizeOffset();
width = width - offset.getHighYOffset() - offset.getLowYOffset();
length = length - offset.getHighXOffset() - offset.getLowXOffset();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE);
}
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) {
extra = "rnwod "+extra;
}
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) {
extra = "rpwod "+extra;
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (capacVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit());
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (inductVar.getCode() == TextDescriptor.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit());
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
// biasn = subnet != NOSPNET ? subnet : 0;
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets.getUseParasitics()) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets.getUseParasitics()) {
if (ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
}
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w, 2));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd, 3));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (!useCDL)
{
if (Simulation.isSpiceUseParasitics() && cell.getView() == View.LAYOUT)
{
if (useNewParasitics)
{
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.cap > cell.getTechnology().getMinCapacitance()) {
if (netInfo.netName.equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.netName + " 0 " + TextUtils.formatDouble(netInfo.cap, 2) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.arcRes.get(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap, 2);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue(), 2) + "\n");
resCount++;
}
}
} else
{
// print parasitic capacitances
boolean first = true;
int capacNum = 1;
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
Network net = cs.getNetwork();
if (net == cni.getGroundNet()) continue;
SpiceNet spNet = spiceNetMap.get(net);
if (spNet.nonDiffCapacitance > layoutTechnology.getMinCapacitance())
{
if (first)
{
first = false;
multiLinePrint(true, "** Extracted Parasitic Elements:\n");
}
multiLinePrint(false, "C" + capacNum + " " + cs.getName() + " 0 " + TextUtils.formatDouble(spNet.nonDiffCapacitance, 2) + "fF\n");
capacNum++;
}
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
|
diff --git a/src/ICS/SND/Utilities/HibernateUtil.java b/src/ICS/SND/Utilities/HibernateUtil.java
index 476157a..63acc78 100644
--- a/src/ICS/SND/Utilities/HibernateUtil.java
+++ b/src/ICS/SND/Utilities/HibernateUtil.java
@@ -1,33 +1,32 @@
package ICS.SND.Utilities;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import ICS.SND.Entities.Entry;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration config = new Configuration().configure("hibernate.cfg.xml");
config.addPackage("ICS.SND.Entities").addAnnotatedClass(Entry.class);
- SessionFactory factory = config.buildSessionFactory();
- return factory;
+ return config.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
| true | true | private static SessionFactory buildSessionFactory() {
try {
Configuration config = new Configuration().configure("hibernate.cfg.xml");
config.addPackage("ICS.SND.Entities").addAnnotatedClass(Entry.class);
SessionFactory factory = config.buildSessionFactory();
return factory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
| private static SessionFactory buildSessionFactory() {
try {
Configuration config = new Configuration().configure("hibernate.cfg.xml");
config.addPackage("ICS.SND.Entities").addAnnotatedClass(Entry.class);
return config.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
|
diff --git a/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/SelectionAwareExpressionEditor.java b/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/SelectionAwareExpressionEditor.java
index 9648a529fc..943a053874 100644
--- a/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/SelectionAwareExpressionEditor.java
+++ b/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/provider/SelectionAwareExpressionEditor.java
@@ -1,98 +1,98 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.expression.editor.provider;
import java.util.ArrayList;
import java.util.List;
import org.bonitasoft.studio.common.log.BonitaStudioLog;
import org.bonitasoft.studio.expression.editor.ExpressionEditorPlugin;
import org.bonitasoft.studio.model.expression.Expression;
import org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.jface.dialogs.DialogTray;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
/**
* @author Romain Bioteau
*
*/
public abstract class SelectionAwareExpressionEditor implements IExpressionEditor {
private final List<Listener> listeners = new ArrayList<Listener>();
@Override
public void addListener(Listener listener) {
listeners.add(listener) ;
}
@Override
public void dispose() {
listeners.clear() ;
}
protected void fireSelectionChanged(){
for(Listener l : listeners){
l.handleEvent(new Event()) ;
}
}
@Override
public List<Listener> getListeners(){
return listeners ;
}
@Override
public boolean provideDialogTray() {
return false;
}
@Override
public DialogTray createDialogTray() {
return null;
}
@Override
public IObservable getContentObservable() {
return null;
}
@Override
public Control createExpressionEditor(Composite contentComposite,
boolean isPassword) {
return createExpressionEditor(contentComposite);
}
protected boolean compatibleReturnType(Expression inputExpression,Expression e) {
final String currentReturnType = inputExpression.getReturnType();
final String expressionReturnType = e.getReturnType();
if(currentReturnType.equals(expressionReturnType)){
return true;
}
try{
Class<?> currentReturnTypeClass = Class.forName(currentReturnType);
Class<?> expressionReturnTypeClass = Class.forName(expressionReturnType);
return currentReturnTypeClass.isAssignableFrom(expressionReturnTypeClass);
}catch (Exception ex) {
- BonitaStudioLog.warning("Failed to determine the compatbility between "+expressionReturnType+" and "+currentReturnType, ExpressionEditorPlugin.PLUGIN_ID);
+ BonitaStudioLog.debug("Failed to determine the compatbility between "+expressionReturnType+" and "+currentReturnType, ExpressionEditorPlugin.PLUGIN_ID);
}
return true;
}
}
| true | true | protected boolean compatibleReturnType(Expression inputExpression,Expression e) {
final String currentReturnType = inputExpression.getReturnType();
final String expressionReturnType = e.getReturnType();
if(currentReturnType.equals(expressionReturnType)){
return true;
}
try{
Class<?> currentReturnTypeClass = Class.forName(currentReturnType);
Class<?> expressionReturnTypeClass = Class.forName(expressionReturnType);
return currentReturnTypeClass.isAssignableFrom(expressionReturnTypeClass);
}catch (Exception ex) {
BonitaStudioLog.warning("Failed to determine the compatbility between "+expressionReturnType+" and "+currentReturnType, ExpressionEditorPlugin.PLUGIN_ID);
}
return true;
}
| protected boolean compatibleReturnType(Expression inputExpression,Expression e) {
final String currentReturnType = inputExpression.getReturnType();
final String expressionReturnType = e.getReturnType();
if(currentReturnType.equals(expressionReturnType)){
return true;
}
try{
Class<?> currentReturnTypeClass = Class.forName(currentReturnType);
Class<?> expressionReturnTypeClass = Class.forName(expressionReturnType);
return currentReturnTypeClass.isAssignableFrom(expressionReturnTypeClass);
}catch (Exception ex) {
BonitaStudioLog.debug("Failed to determine the compatbility between "+expressionReturnType+" and "+currentReturnType, ExpressionEditorPlugin.PLUGIN_ID);
}
return true;
}
|
diff --git a/src/be/ibridge/kettle/job/JobMeta.java b/src/be/ibridge/kettle/job/JobMeta.java
index 477be6a3..24310a5a 100644
--- a/src/be/ibridge/kettle/job/JobMeta.java
+++ b/src/be/ibridge/kettle/job/JobMeta.java
@@ -1,1716 +1,1716 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.job;
import java.util.ArrayList;
import org.eclipse.core.runtime.IProgressMonitor;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.DBCache;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.NotePadMeta;
import be.ibridge.kettle.core.Point;
import be.ibridge.kettle.core.Rectangle;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.SQLStatement;
import be.ibridge.kettle.core.TransAction;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.job.entry.JobEntryCopy;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.job.entry.eval.JobEntryEval;
import be.ibridge.kettle.job.entry.special.JobEntrySpecial;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.repository.RepositoryDirectory;
/**
* Defines a Job and provides methods to load, save, verify, etc.
*
* @author Matt
* @since 11-08-2003
*
*/
public class JobMeta implements Cloneable, XMLInterface
{
public LogWriter log;
private long id;
private String name;
private String filename;
public ArrayList jobentries;
public ArrayList jobcopies;
public ArrayList jobhops;
public ArrayList notes;
public ArrayList databases;
private RepositoryDirectory directory;
public String arguments[];
private boolean changed, changed_entries, changed_hops, changed_notes;
private DatabaseMeta logconnection;
private String logTable;
public DBCache dbcache;
private ArrayList undo;
private int max_undo;
private int undo_position;
public static final int TYPE_UNDO_CHANGE = 1;
public static final int TYPE_UNDO_NEW = 2;
public static final int TYPE_UNDO_DELETE = 3;
public static final int TYPE_UNDO_POSITION = 4;
public static final String STRING_SPECIAL_START = "START";
public static final String STRING_SPECIAL_DUMMY = "DUMMY";
// Remember the size and position of the different windows...
public boolean max[] = new boolean[1];
public Rectangle size[] = new Rectangle[1];
public String created_user, modified_user;
public Value created_date, modified_date;
private boolean useBatchId;
private long batchId;
private boolean batchIdPassed;
private boolean logfieldUsed;
public JobMeta(LogWriter l)
{
log=l;
clear();
}
public long getID()
{
return id;
}
public void setID(long id)
{
this.id = id;
}
public void clear()
{
name = null;
jobcopies = new ArrayList();
jobentries = new ArrayList();
jobhops = new ArrayList();
notes = new ArrayList();
databases = new ArrayList();
logconnection = null;
logTable = null;
arguments = null;
max_undo = Const.MAX_UNDO;
dbcache = DBCache.getInstance();
undo = new ArrayList();
undo_position=-1;
addDefaults();
setChanged(false);
modified_user = "-";
modified_date = null;
directory = new RepositoryDirectory();
}
public void addDefaults()
{
addStart(); // Add starting point!
addDummy(); // Add dummy!
addOK(); // errors == 0 evaluation
addError(); // errors != 0 evaluation
clearChanged();
}
private void addStart()
{
JobEntrySpecial je = new JobEntrySpecial(STRING_SPECIAL_START, true, false);
JobEntryCopy jge = new JobEntryCopy(log);
jge.setID(-1L);
jge.setEntry(je);
jge.setLocation(50,50);
jge.setDrawn(false);
jge.setDescription("A job starts to process here.");
addJobEntry(jge);
}
private void addDummy()
{
JobEntrySpecial dummy = new JobEntrySpecial(STRING_SPECIAL_DUMMY, false, true);
JobEntryCopy dummyge = new JobEntryCopy(log);
dummyge.setID(-1L);
dummyge.setEntry(dummy);
dummyge.setLocation(50,50);
dummyge.setDrawn(false);
dummyge.setDescription("A dummy entry.");
addJobEntry(dummyge);
}
public void addOK()
{
JobEntryEval ok = new JobEntryEval("OK", "errors == 0");
JobEntryCopy jgok = new JobEntryCopy(log);
jgok.setEntry(ok);
jgok.setLocation(0,0);
jgok.setDrawn(false);
jgok.setDescription("This comparisson is true when no errors have occured.");
addJobEntry(jgok);
}
public void addError()
{
JobEntryEval err = new JobEntryEval("ERROR", "errors != 0");
JobEntryCopy jgerr = new JobEntryCopy(log);
jgerr.setEntry(err);
jgerr.setLocation(0,0);
jgerr.setDrawn(false);
jgerr.setDescription("This comparisson is true when one or more errors have occured.");
addJobEntry(jgerr);
}
public JobEntryCopy getStart()
{
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy cge = getJobEntry(i);
if (cge.isStart()) return cge;
}
return null;
}
public JobEntryCopy getDummy()
{
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy cge = getJobEntry(i);
if (cge.isDummy()) return cge;
}
return null;
}
public boolean equals(Object obj)
{
return name.equalsIgnoreCase(((JobMeta)obj).name);
}
public Object clone()
{
try
{
Object retval = super.clone();
return retval;
}
catch(CloneNotSupportedException e)
{
return null;
}
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
/**
* @return Returns the directory.
*/
public RepositoryDirectory getDirectory()
{
return directory;
}
/**
* @param directory The directory to set.
*/
public void setDirectory(RepositoryDirectory directory)
{
this.directory = directory;
}
public String getFilename()
{
return filename;
}
public void setFilename(String filename)
{
this.filename=filename;
}
public DatabaseMeta getLogConnection()
{
return logconnection;
}
public void setLogConnection(DatabaseMeta ci)
{
logconnection=ci;
}
/**
* @return Returns the databases.
*/
public ArrayList getDatabases()
{
return databases;
}
/**
* @param databases The databases to set.
*/
public void setDatabases(ArrayList databases)
{
this.databases = databases;
}
public void setChanged()
{
setChanged(true);
}
public void setChanged(boolean ch)
{
changed=ch;
}
public void clearChanged()
{
changed_entries = false;
changed_hops = false;
changed_notes = false;
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy entry = getJobEntry(i);
entry.setChanged(false);
}
for (int i=0;i<nrJobHops();i++)
{
JobHopMeta hop = getJobHop(i);
hop.setChanged(false);
}
changed=false;
}
public boolean hasChanged()
{
if (changed || changed_notes || changed_entries || changed_hops) return true;
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy entry = getJobEntry(i);
if (entry.hasChanged()) return true;
}
for (int i=0;i<nrJobHops();i++)
{
JobHopMeta hop = getJobHop(i);
if (hop.hasChanged()) return true;
}
return false;
}
private void saveRepJob(Repository rep)
throws KettleException
{
try
{
// The ID has to be assigned, even when it's a new item...
rep.insertJob(
getID(),
directory.getID(),
getName(),
logconnection==null?-1:logconnection.getID(),
logTable,
modified_user,
modified_date,
useBatchId,
batchIdPassed,
logfieldUsed
);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job info to repository", dbe);
}
}
public boolean showReplaceWarning(Repository rep)
{
if (getID()<0)
{
try
{
if ( rep.getJobID( getName(), directory.getID() )>0 ) return true;
}
catch(KettleDatabaseException dbe)
{
return true;
}
}
return false;
}
public String getXML()
{
DatabaseMeta ci = getLogConnection();
StringBuffer retval = new StringBuffer();
retval.append("<job>"+Const.CR);
retval.append(" "+XMLHandler.addTagValue("name", getName()));
retval.append(" "+XMLHandler.addTagValue("directory", directory.getPath()));
for (int i=0;i<nrDatabases();i++)
{
DatabaseMeta dbinfo = getDatabase(i);
retval.append(dbinfo.getXML());
}
retval.append(" "+XMLHandler.addTagValue("logconnection", ci==null?"":ci.getName()));
retval.append(" "+XMLHandler.addTagValue("logtable", logTable));
retval.append( " " + XMLHandler.addTagValue("use_batchid", useBatchId));
retval.append( " " + XMLHandler.addTagValue("pass_batchid", batchIdPassed));
retval.append( " " + XMLHandler.addTagValue("use_logfield", logfieldUsed));
retval.append(" <entries>"+Const.CR);
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy jge = getJobEntry(i);
retval.append(jge.getXML());
}
retval.append(" </entries>"+Const.CR);
retval.append(" <hops>"+Const.CR);
for (int i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
retval.append(hi.getXML());
}
retval.append(" </hops>"+Const.CR);
retval.append(" <notepads>"+Const.CR);
for (int i=0;i<nrNotes();i++)
{
NotePadMeta ni= getNote(i);
retval.append(ni.getXML());
}
retval.append(" </notepads>"+Const.CR);
retval.append(" </job>"+Const.CR);
return retval.toString();
}
/**
* Load the job from the XML file specified.
* @param log the logging channel
* @param fname The filename to load as a job
* @throws KettleXMLException
*/
public JobMeta(LogWriter log, String fname)
throws KettleXMLException
{
this.log = log;
try
{
Document doc = XMLHandler.loadXMLFile(fname);
if (doc!=null)
{
// Clear the job
clear();
setFilename(fname);
// The jobnode
Node jobnode = XMLHandler.getSubNode(doc, "job");
loadXML(jobnode);
}
else
{
throw new KettleXMLException("Error reading/validating information from XML file: "+fname);
}
}
catch(Exception e)
{
throw new KettleXMLException("Unable to load the job from XML file ["+fname+"]", e);
}
}
public JobMeta(LogWriter log, Node jobnode)
throws KettleXMLException
{
this.log = log;
loadXML(jobnode);
}
public void loadXML(Node jobnode)
throws KettleXMLException
{
try
{
//
// get job info:
//
name = XMLHandler.getTagValue(jobnode, "name");
//
// Read the database connections
//
int nr = XMLHandler.countNodes(jobnode, "connection");
for (int i=0;i<nr;i++)
{
Node dbnode = XMLHandler.getSubNodeByNr(jobnode, "connection", i);
DatabaseMeta dbinf = new DatabaseMeta(dbnode);
addDatabase(dbinf);
}
/*
* Get the log database connection & log table
*/
String logcon = XMLHandler.getTagValue(jobnode, "logconnection");
logconnection = findDatabase(logcon);
logTable = XMLHandler.getTagValue(jobnode, "logtable");
useBatchId = "Y".equalsIgnoreCase(XMLHandler.getTagValue(jobnode, "use_batchid"));
batchIdPassed = "Y".equalsIgnoreCase(XMLHandler.getTagValue(jobnode, "pass_batchid"));
logfieldUsed = "Y".equalsIgnoreCase(XMLHandler.getTagValue(jobnode, "use_logfield"));
/*
* read the job entries...
*/
Node entriesnode = XMLHandler.getSubNode(jobnode, "entries");
int tr = XMLHandler.countNodes(entriesnode, "entry");
for (int i=0;i<tr;i++)
{
Node entrynode = XMLHandler.getSubNodeByNr(entriesnode, "entry", i);
//System.out.println("Reading entry:\n"+entrynode);
JobEntryCopy je = new JobEntryCopy(entrynode, databases, null);
JobEntryCopy prev = findJobEntry(je.getName(), 0);
if (prev!=null)
{
if (je.getNr()==0) // See if the #0 already exists!
{
// Replace previous version with this one: remove it first
int idx = indexOfJobEntry(prev);
removeJobEntry(idx);
}
else
if (je.getNr()>0) // Use previously defined JobEntry info!
{
je.setEntry(prev.getEntry());
// See if entry.5 already exists...
prev = findJobEntry(je.getName(), je.getNr());
if (prev!=null) // remove the old one!
{
int idx = indexOfJobEntry(prev);
removeJobEntry(idx);
}
}
}
// Add the JobEntryCopy...
addJobEntry(je);
}
Node hopsnode = XMLHandler.getSubNode(jobnode, "hops");
int ho = XMLHandler.countNodes(hopsnode, "hop");
for (int i=0;i<ho;i++)
{
Node hopnode = XMLHandler.getSubNodeByNr(hopsnode, "hop", i);
JobHopMeta hi = new JobHopMeta(hopnode, this);
jobhops.add(hi);
}
// Read the notes...
Node notepadsnode = XMLHandler.getSubNode(jobnode, "notepads");
int nrnotes = XMLHandler.countNodes(notepadsnode, "notepad");
for (int i=0;i<nrnotes;i++)
{
Node notepadnode = XMLHandler.getSubNodeByNr(notepadsnode, "notepad", i);
NotePadMeta ni = new NotePadMeta(notepadnode);
notes.add(ni);
}
// Do we have the special entries?
if (findJobEntry(STRING_SPECIAL_START, 0)==null) addStart();
if (findJobEntry(STRING_SPECIAL_DUMMY, 0)==null) addDummy();
}
catch(Exception e)
{
throw new KettleXMLException("Unable to load job info from XML node", e);
}
}
/**
* Read the database connections in the repository and add them to this job
* if they are not yet present.
*
* @param rep The repository to load the database connections from.
*/
public void readDatabases(Repository rep)
{
try
{
long dbids[] = rep.getDatabaseIDs();
for (int i=0;i<dbids.length;i++)
{
DatabaseMeta ci = new DatabaseMeta(rep, dbids[i]);
if (indexOfDatabase(ci)<0)
{
addDatabase(ci);
ci.setChanged(false);
}
}
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error reading databases from repository:"+Const.CR+dbe.getMessage());
}
catch(KettleException ke)
{
log.logError(toString(), "Error reading databases from repository:"+Const.CR+ke.getMessage());
}
setChanged(false);
}
/**
* Find a database connection by it's name
* @param name The database name to look for
* @return The database connection or null if nothing was found.
*/
public DatabaseMeta findDatabase(String name)
{
for (int i=0;i<nrDatabases();i++)
{
DatabaseMeta ci = getDatabase(i);
if (ci.getName().equalsIgnoreCase(name))
{
return ci;
}
}
return null;
}
public void saveRep(Repository rep)
throws KettleException
{
saveRep(rep, null);
}
public void saveRep(Repository rep, IProgressMonitor monitor)
throws KettleException
{
try
{
int nrWorks = 2+nrDatabases()+nrNotes()+nrJobEntries()+nrJobHops();
if (monitor!=null) monitor.beginTask("Saving transformation "+directory+Const.FILE_SEPARATOR+getName(), nrWorks);
// Before we start, make sure we have a valid job ID!
// Two possibilities:
// 1) We have a ID: keep it
// 2) We don't have an ID: look it up.
// If we find a transformation with the same name: ask!
//
if (monitor!=null) monitor.subTask("Handling previous version of job...");
setID( rep.getJobID(getName(), directory.getID()) );
// If no valid id is available in the database, assign one...
if (getID()<=0)
{
setID( rep.getNextJobID() );
}
else
{
// If we have a valid ID, we need to make sure everything is cleared out
// of the database for this id_job, before we put it back in...
rep.delAllFromJob(getID());
}
if (monitor!=null) monitor.worked(1);
// Now, save the job entry in R_JOB
// Note, we save this first so that we have an ID in the database.
// Everything else depends on this ID, including recursive job entries to the save job. (retry)
if (monitor!=null) monitor.subTask("Saving job details...");
log.logDetailed(toString(), "Saving job info to repository...");
saveRepJob(rep);
if (monitor!=null) monitor.worked(1);
//
// Save the notes
//
log.logDetailed(toString(), "Saving notes to repository...");
for (int i=0;i<nrNotes();i++)
{
if (monitor!=null) monitor.subTask("Saving note #"+(i+1)+"/"+nrNotes());
NotePadMeta ni = getNote(i);
ni.saveRep(rep, getID());
if (ni.getID()>0)
{
rep.insertJobNote(getID(), ni.getID());
}
if (monitor!=null) monitor.worked(1);
}
//
// Save the job entries
//
log.logDetailed(toString(), "Saving "+nrJobEntries()+" ChefGraphEntries to repository...");
for (int i=0;i<nrJobEntries();i++)
{
if (monitor!=null) monitor.subTask("Saving job entry #"+(i+1)+"/"+nrJobEntries());
JobEntryCopy cge = getJobEntry(i);
cge.saveRep(rep, getID());
if (monitor!=null) monitor.worked(1);
}
log.logDetailed(toString(), "Saving job hops to repository...");
for (int i=0;i<nrJobHops();i++)
{
if (monitor!=null) monitor.subTask("Saving job hop #"+(i+1)+"/"+nrJobHops());
JobHopMeta hi = getJobHop(i);
hi.saveRep(rep, getID());
if (monitor!=null) monitor.worked(1);
}
// Commit this transaction!!
rep.commit();
clearChanged();
if (monitor!=null) monitor.done();
}
catch(KettleDatabaseException dbe)
{
rep.rollback();
throw new KettleException("Unable to save Job in repository, database rollback performed.", dbe);
}
}
/**
* Load a job in a directory
* @param log the logging channel
* @param rep The Repository
* @param jobname The name of the job
* @param repdir The directory in which the job resides.
* @throws KettleException
*/
public JobMeta(LogWriter log, Repository rep, String jobname, RepositoryDirectory repdir)
throws KettleException
{
this(log, rep, jobname, repdir, null);
}
/**
* Load a job in a directory
* @param log the logging channel
* @param rep The Repository
* @param jobname The name of the job
* @param repdir The directory in which the job resides.
* @throws KettleException
*/
public JobMeta(LogWriter log, Repository rep, String jobname, RepositoryDirectory repdir, IProgressMonitor monitor)
throws KettleException
{
this.log = log;
try
{
// Clear everything...
clear();
directory = repdir;
// Get the transformation id
setID( rep.getJobID(jobname, repdir.getID()) );
// If no valid id is available in the database, then give error...
if (getID()>0)
{
// Load the notes...
long noteids[] = rep.getJobNoteIDs(getID());
long jecids[] = rep.getJobEntryCopyIDs(getID());
long hopid[] = rep.getJobHopIDs(getID());
int nrWork = 2+noteids.length+jecids.length+hopid.length;
if (monitor!=null) monitor.beginTask("Loading job "+repdir+Const.FILE_SEPARATOR+jobname, nrWork);
//
// Load the common database connections
//
if (monitor!=null) monitor.subTask("Reading the available database from the repository");
readDatabases(rep);
if (monitor!=null) monitor.worked(1);
//
// get job info:
//
if (monitor!=null) monitor.subTask("Reading the job information");
Row jobrow = rep.getJob(getID());
name = jobrow.searchValue("NAME").getString();
logTable = jobrow.searchValue("TABLE_NAME_LOG").getString();
long id_logdb = jobrow.searchValue("ID_DATABASE_LOG").getInteger();
if (id_logdb>0)
{
// Get the logconnection
logconnection = new DatabaseMeta(rep, id_logdb);
}
useBatchId = jobrow.getBoolean("USE_BATCH_ID", false);
batchIdPassed = jobrow.getBoolean("PASS_BATCH_ID", false);
logfieldUsed = jobrow.getBoolean("USE_LOGFIELD", false);
if (monitor!=null) monitor.worked(1);
log.logDetailed(toString(), "Loading "+noteids.length+" notes");
for (int i=0;i<noteids.length;i++)
{
if (monitor!=null) monitor.subTask("Reading note #"+(i+1)+"/"+noteids.length);
- NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]);
+ NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]);
if (indexOfNote(ni)<0) addNote(ni);
if (monitor!=null) monitor.worked(1);
}
// Load the job entries...
log.logDetailed(toString(), "Loading "+jecids.length+" job entries");
for (int i=0;i<jecids.length;i++)
{
if (monitor!=null) monitor.subTask("Reading job entry #"+(i+1)+"/"+(jecids.length));
JobEntryCopy jec = new JobEntryCopy(log, rep, getID(), jecids[i], jobentries, databases);
int idx = indexOfJobEntry(jec);
if (idx < 0)
{
if (jec.getName()!=null && jec.getName().length()>0) addJobEntry(jec);
}
else
{
setJobEntry(idx, jec); // replace it!
}
if (monitor!=null) monitor.worked(1);
}
// Load the hops...
log.logDetailed(toString(), "Loading "+hopid.length+" job hops");
for (int i=0;i<hopid.length;i++)
{
if (monitor!=null) monitor.subTask("Reading job hop #"+(i+1)+"/"+(jecids.length));
JobHopMeta hi = new JobHopMeta(rep, hopid[i], this, jobcopies);
jobhops.add(hi);
if (monitor!=null) monitor.worked(1);
}
// Finally, clear the changed flags...
clearChanged();
if (monitor!=null) monitor.subTask("Finishing load");
if (monitor!=null) monitor.done();
}
else
{
throw new KettleException("Can't find job : "+jobname);
}
}
catch(KettleException dbe)
{
throw new KettleException("An error occurred reading job ["+jobname+"] from the repository", dbe);
}
}
public JobEntryCopy getChefGraphEntry(int x, int y, int iconsize)
{
int i, s;
s = nrJobEntries();
for (i=s-1;i>=0;i--) // Back to front because drawing goes from start to end
{
JobEntryCopy je = getJobEntry(i);
Point p = je.getLocation();
if (p!=null)
{
if ( x >= p.x && x <= p.x+iconsize
&& y >= p.y && y <= p.y+iconsize
)
{
return je;
}
}
}
return null;
}
public int nrJobEntries() { return jobcopies.size(); }
public int nrJobHops() { return jobhops.size(); }
public int nrNotes() { return notes.size(); }
public int nrDatabases() { return databases.size(); }
public JobHopMeta getJobHop(int i) { return (JobHopMeta)jobhops.get(i); }
public JobEntryCopy getJobEntry(int i) { return (JobEntryCopy)jobcopies.get(i); }
public NotePadMeta getNote(int i) { return (NotePadMeta)notes.get(i); }
public DatabaseMeta getDatabase(int i) { return (DatabaseMeta)databases.get(i); }
public void addJobEntry(JobEntryCopy je)
{
jobcopies.add(je);
setChanged();
}
public void addJobHop(JobHopMeta hi)
{
jobhops.add(hi);
setChanged();
}
public void addNote(NotePadMeta ni)
{
notes.add(ni);
setChanged();
}
public void addDatabase(DatabaseMeta ci)
{
databases.add(ci);
setChanged();
}
public void addJobEntry(int p, JobEntryCopy si)
{
jobcopies.add(p, si);
changed_entries = true;
}
public void addJobHop(int p, JobHopMeta hi)
{
jobhops.add(p, hi);
changed_hops = true;
}
public void addNote(int p, NotePadMeta ni)
{
notes.add(p, ni);
changed_notes = true;
}
public void addDatabase(int p, DatabaseMeta ci)
{
databases.add(p, ci);
setChanged();
}
public void removeJobEntry(int i) { jobcopies.remove(i); setChanged(); }
public void removeJobHop(int i) { jobhops.remove(i); setChanged(); }
public void removeNote(int i) { notes.remove(i); setChanged(); }
public void removeDatabase(int i)
{
if (i<0 || i>=databases.size()) return;
databases.remove(i);
setChanged();
}
public int indexOfJobHop(JobHopMeta he) { return jobhops.indexOf(he); }
public int indexOfNote(NotePadMeta ni) { return notes.indexOf(ni); }
public int indexOfJobEntry(JobEntryCopy ge) { return jobcopies.indexOf(ge); }
public int indexOfDatabase(DatabaseMeta di) { return databases.indexOf(di); }
public void setJobEntry(int idx, JobEntryCopy jec)
{
jobcopies.set(idx, jec);
}
/**
* Find an existing JobEntryCopy by it's name and number
* @param name The name of the job entry copy
* @param nr The number of the job entry copy
* @return The JobEntryCopy or null if nothing was found!
*/
public JobEntryCopy findJobEntry(String name, int nr)
{
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy jec = getJobEntry(i);
if (jec.getName().equalsIgnoreCase(name) && jec.getNr()==nr)
{
return jec;
}
}
return null;
}
public JobEntryCopy findJobEntry(String full_name_nr)
{
int i;
for (i=0;i<nrJobEntries();i++)
{
// log.logDebug("findChefGraphEntry()", "looking at nr: "+i);
JobEntryCopy jec = getJobEntry(i);
JobEntryInterface je = jec.getEntry();
if (je.toString().equalsIgnoreCase(full_name_nr))
{
return jec;
}
}
return null;
}
public JobHopMeta findJobHop(String name)
{
int i;
for (i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
if (hi.toString().equalsIgnoreCase(name))
{
return hi;
}
}
return null;
}
public JobHopMeta findJobHopFrom(JobEntryCopy jge)
{
int i;
for (i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
if (hi.from_entry.equals(jge)) // return the first
{
return hi;
}
}
return null;
}
public JobHopMeta findJobHop(JobEntryCopy from, JobEntryCopy to)
{
int i;
for (i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
if (hi.isEnabled())
{
if (hi!=null && hi.from_entry!=null && hi.to_entry!=null &&
hi.from_entry.equals(from) && hi.to_entry.equals(to)
)
{
return hi;
}
}
}
return null;
}
public JobHopMeta findJobHopTo(JobEntryCopy jge)
{
int i;
for (i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
if (hi!=null && hi.to_entry!=null && hi.to_entry.equals(jge)) // Return the first!
{
return hi;
}
}
return null;
}
public int findNrPrevChefGraphEntries(JobEntryCopy from)
{
return findNrPrevChefGraphEntries(from, false);
}
public JobEntryCopy findPrevChefGraphEntry(JobEntryCopy to, int nr)
{
return findPrevChefGraphEntry(to, nr, false);
}
public int findNrPrevChefGraphEntries(JobEntryCopy to, boolean info)
{
int count=0;
int i;
for (i=0;i<nrJobHops();i++) // Look at all the hops;
{
JobHopMeta hi = getJobHop(i);
if (hi.isEnabled() && hi.to_entry.equals(to))
{
count++;
}
}
return count;
}
public JobEntryCopy findPrevChefGraphEntry(JobEntryCopy to, int nr, boolean info)
{
int count=0;
int i;
for (i=0;i<nrJobHops();i++) // Look at all the hops;
{
JobHopMeta hi = getJobHop(i);
if (hi.isEnabled() && hi.to_entry.equals(to))
{
if (count==nr)
{
return hi.from_entry;
}
count++;
}
}
return null;
}
public int findNrNextChefGraphEntries(JobEntryCopy from)
{
int count=0;
int i;
for (i=0;i<nrJobHops();i++) // Look at all the hops;
{
JobHopMeta hi = getJobHop(i);
if (hi.isEnabled() && hi.from_entry.equals(from)) count++;
}
return count;
}
public JobEntryCopy findNextChefGraphEntry(JobEntryCopy from, int cnt)
{
int count=0;
int i;
for (i=0;i<nrJobHops();i++) // Look at all the hops;
{
JobHopMeta hi = getJobHop(i);
if (hi.isEnabled() && hi.from_entry.equals(from))
{
if (count==cnt)
{
return hi.to_entry;
}
count++;
}
}
return null;
}
public boolean hasLoop(JobEntryCopy entry)
{
return hasLoop(entry, null);
}
public boolean hasLoop(JobEntryCopy entry, JobEntryCopy lookup)
{
return false;
}
public boolean isEntryUsedInHops(JobEntryCopy jge)
{
JobHopMeta fr = findJobHopFrom(jge);
JobHopMeta to = findJobHopTo(jge);
if (fr!=null || to!=null) return true;
return false;
}
public int countEntries(String name)
{
int count=0;
int i;
for (i=0;i<nrJobEntries();i++) // Look at all the hops;
{
JobEntryCopy je = getJobEntry(i);
if (je.getName().equalsIgnoreCase(name)) count++;
}
return count;
}
public int generateJobEntryNameNr(String basename)
{
int nr=1;
JobEntryCopy e = findJobEntry(basename+" "+nr, 0);
while(e!=null)
{
nr++;
e = findJobEntry(basename+" "+nr, 0);
}
return nr;
}
public int findUnusedNr(String name)
{
int nr=1;
JobEntryCopy je = findJobEntry(name, nr);
while (je!=null)
{
nr++;
//log.logDebug("findUnusedNr()", "Trying unused nr: "+nr);
je = findJobEntry(name, nr);
}
return nr;
}
public int findMaxNr(String name)
{
int max=0;
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy je = getJobEntry(i);
if (je.getName().equalsIgnoreCase(name))
{
if (je.getNr()>max) max=je.getNr();
}
}
return max;
}
/**
* Proposes an alternative job entry name when the original already exists...
* @param entryname The job entry name to find an alternative for..
* @return The alternative stepname.
*/
public String getAlternativeJobentryName(String entryname)
{
String newname = entryname;
JobEntryCopy jec = findJobEntry(newname);
int nr = 1;
while (jec!=null)
{
nr++;
newname = entryname + " "+nr;
jec = findJobEntry(newname);
}
return newname;
}
public JobEntryCopy[] getAllChefGraphEntries(String name)
{
int count=0;
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy je = getJobEntry(i);
if (je.getName().equalsIgnoreCase(name)) count++;
}
JobEntryCopy retval[] = new JobEntryCopy[count];
count=0;
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy je = getJobEntry(i);
if (je.getName().equalsIgnoreCase(name))
{
retval[count]=je;
count++;
}
}
return retval;
}
public JobHopMeta[] getAllJobHopsUsing(String name)
{
int count=0;
for (int i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
if (hi.from_entry.getName().equalsIgnoreCase(name) ||
hi.to_entry.getName().equalsIgnoreCase(name) )
{
count++;
}
}
JobHopMeta retval[] = new JobHopMeta[count];
count=0;
for (int i=0;i<nrJobHops();i++)
{
JobHopMeta hi = getJobHop(i);
if (hi.from_entry.getName().equalsIgnoreCase(name) ||
hi.to_entry.getName().equalsIgnoreCase(name) )
{
retval[count]=hi;
count++;
}
}
return retval;
}
public NotePadMeta getNote(int x, int y)
{
int i, s;
s = notes.size();
for (i=s-1;i>=0;i--) // Back to front because drawing goes from start to end
{
NotePadMeta ni = (NotePadMeta )notes.get(i);
Point loc = ni.getLocation();
Point p = new Point(loc.x, loc.y);
if ( x >= p.x && x <= p.x+ni.width+2*Const.NOTE_MARGIN
&& y >= p.y && y <= p.y+ni.height+2*Const.NOTE_MARGIN
)
{
return ni;
}
}
return null;
}
public void selectAll()
{
int i;
for (i=0;i<nrJobEntries();i++)
{
JobEntryCopy ce = getJobEntry(i);
ce.setSelected(true);
}
}
public void unselectAll()
{
int i;
for (i=0;i<nrJobEntries();i++)
{
JobEntryCopy ce = getJobEntry(i);
ce.setSelected(false);
}
}
public void selectInRect(Rectangle rect)
{
int i;
for (i = 0; i < nrJobEntries(); i++)
{
JobEntryCopy je = getJobEntry(i);
Point p = je.getLocation();
if (((p.x >= rect.x && p.x <= rect.x + rect.width)
|| (p.x >= rect.x + rect.width && p.x <= rect.x))
&& ((p.y >= rect.y && p.y <= rect.y + rect.height)
|| (p.y >= rect.y + rect.height && p.y <= rect.y))
)
je.setSelected(true);
}
}
public int getMaxUndo()
{
return max_undo;
}
public void setMaxUndo(int mu)
{
max_undo=mu;
while (undo.size()>mu && undo.size()>0) undo.remove(0);
}
public int getUndoSize()
{
if (undo==null) return 0;
return undo.size();
}
public void addUndo(Object from[], Object to[], int pos[], Point prev[], Point curr[], int type_of_change)
{
// First clean up after the current position.
// Example: position at 3, size=5
// 012345
// ^
// remove 34
// Add 4
// 01234
while (undo.size()>undo_position+1 && undo.size()>0)
{
int last = undo.size()-1;
undo.remove(last);
}
TransAction ta = new TransAction();
switch(type_of_change)
{
case TYPE_UNDO_CHANGE : ta.setChanged(from, to, pos); break;
case TYPE_UNDO_DELETE : ta.setDelete(from, pos); break;
case TYPE_UNDO_NEW : ta.setNew(from, pos); break;
case TYPE_UNDO_POSITION : ta.setPosition(from, pos, prev, curr); break;
}
undo.add(ta);
undo_position++;
if (undo.size()>max_undo)
{
undo.remove(0);
undo_position--;
}
}
// get previous undo, change position
public TransAction previousUndo()
{
if (undo.size()==0 || undo_position<0) return null; // No undo left!
TransAction retval = (TransAction)undo.get(undo_position);
undo_position--;
return retval;
}
/**
* View current undo, don't change undo position
*
* @return The current undo transaction
*/
public TransAction viewThisUndo()
{
if (undo.size()==0 || undo_position<0) return null; // No undo left!
TransAction retval = (TransAction)undo.get(undo_position);
return retval;
}
// View previous undo, don't change position
public TransAction viewPreviousUndo()
{
if (undo.size()==0 || undo_position<0) return null; // No undo left!
TransAction retval = (TransAction)undo.get(undo_position);
return retval;
}
public TransAction nextUndo()
{
int size=undo.size();
if (size==0 || undo_position>=size-1) return null; // no redo left...
undo_position++;
TransAction retval = (TransAction)undo.get(undo_position);
return retval;
}
public TransAction viewNextUndo()
{
int size=undo.size();
if (size==0 || undo_position>=size-1) return null; // no redo left...
TransAction retval = (TransAction)undo.get(undo_position+1);
return retval;
}
public Point getMaximum()
{
int maxx = 0, maxy = 0;
for (int i = 0; i < nrJobEntries(); i++)
{
JobEntryCopy entry = getJobEntry(i);
Point loc = entry.getLocation();
if (loc.x > maxx)
maxx = loc.x;
if (loc.y > maxy)
maxy = loc.y;
}
for (int i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
Point loc = ni.getLocation();
if (loc.x + ni.width > maxx)
maxx = loc.x + ni.width;
if (loc.y + ni.height > maxy)
maxy = loc.y + ni.height;
}
return new Point(maxx + 100, maxy + 100);
}
public Point[] getSelectedLocations()
{
int sels = nrSelected();
Point retval[] = new Point[sels];
for (int i=0;i<sels;i++)
{
JobEntryCopy si = getSelected(i);
Point p = si.getLocation();
retval[i] = new Point(p.x, p.y); // explicit copy of location
}
return retval;
}
public JobEntryCopy[] getSelectedEntries()
{
int sels = nrSelected();
if (sels==0) return null;
JobEntryCopy retval[] = new JobEntryCopy[sels];
for (int i=0;i<sels;i++)
{
JobEntryCopy je = getSelected(i);
retval[i] = je;
}
return retval;
}
public int nrSelected()
{
int i, count;
count = 0;
for (i = 0; i < nrJobEntries(); i++)
{
JobEntryCopy je = getJobEntry(i);
if (je.isSelected()) count++;
}
return count;
}
public JobEntryCopy getSelected(int nr)
{
int i, count;
count = 0;
for (i = 0; i < nrJobEntries(); i++)
{
JobEntryCopy je = getJobEntry(i);
if (je.isSelected())
{
if (nr == count) return je;
count++;
}
}
return null;
}
public int[] getEntryIndexes(JobEntryCopy entries[])
{
int retval[] = new int[entries.length];
for (int i=0;i<entries.length;i++) retval[i]=indexOfJobEntry(entries[i]);
return retval;
}
public JobEntryCopy findStart()
{
for (int i=0;i<nrJobEntries();i++)
{
if (getJobEntry(i).isStart()) return getJobEntry(i);
}
return null;
}
/**
* TODO: finish this method...
*
public void getSQL()
{
ArrayList stats = new ArrayList();
for (int i=0;i<nrJobEntries();i++)
{
JobEntryCopy jec = getJobEntry(i);
if (jec.getType() == JobEntryInterface.TYPE_JOBENTRY_TRANSFORMATION)
{
JobEntryTrans jet = (JobEntryTrans)jec.getEntry();
String transname = jet.getTransname();
String directory = jet.getDirectory().getPath();
}
else
if (jec.getType() == JobEntryInterface.TYPE_JOBENTRY_JOB)
{
}
}
}
*/
public String toString()
{
if (getName()!=null) return getName();
else return getClass().getName();
}
/**
* @return Returns the batchId.
*/
public long getBatchId()
{
return batchId;
}
/**
* @param batchId The batchId to set.
*/
public void setBatchId(long batchId)
{
this.batchId = batchId;
}
/**
* @return Returns the logfieldUsed.
*/
public boolean isLogfieldUsed()
{
return logfieldUsed;
}
/**
* @param logfieldUsed The logfieldUsed to set.
*/
public void setLogfieldUsed(boolean logfieldUsed)
{
this.logfieldUsed = logfieldUsed;
}
/**
* @return Returns the useBatchId.
*/
public boolean isBatchIdUsed()
{
return useBatchId;
}
/**
* @param useBatchId The useBatchId to set.
*/
public void setUseBatchId(boolean useBatchId)
{
this.useBatchId = useBatchId;
}
/**
* @return Returns the batchIdPassed.
*/
public boolean isBatchIdPassed()
{
return batchIdPassed;
}
/**
* @param batchIdPassed The batchIdPassed to set.
*/
public void setBatchIdPassed(boolean batchIdPassed)
{
this.batchIdPassed = batchIdPassed;
}
/**
* Builds a list of all the SQL statements that this transformation needs in order to work properly.
*
* @return An ArrayList of SQLStatement objects.
*/
public ArrayList getSQLStatements(Repository repository, IProgressMonitor monitor) throws KettleException
{
if (monitor != null) monitor.beginTask("Getting the SQL needed for this job...", nrJobEntries() + 1);
ArrayList stats = new ArrayList();
for (int i = 0; i < nrJobEntries(); i++)
{
JobEntryCopy copy = getJobEntry(i);
if (monitor != null) monitor.subTask("Getting SQL statements for job entry copy [" + copy + "]");
ArrayList list = copy.getEntry().getSQLStatements(repository);
stats.addAll(list);
if (monitor != null) monitor.worked(1);
}
// Also check the sql for the logtable...
if (monitor != null) monitor.subTask("Getting SQL statements for the job (logtable, etc.)");
if (logconnection != null && logTable != null && logTable.length() > 0)
{
Database db = new Database(logconnection);
try
{
db.connect();
Row fields = Database.getJobLogrecordFields(useBatchId, logfieldUsed);
String sql = db.getDDL(logTable, fields);
if (sql != null && sql.length() > 0)
{
SQLStatement stat = new SQLStatement("<this job>", logconnection, sql);
stats.add(stat);
}
}
catch (KettleDatabaseException dbe)
{
SQLStatement stat = new SQLStatement("<this job>", logconnection, null);
stat.setError("Error obtaining job log table info: " + dbe.getMessage());
stats.add(stat);
}
finally
{
db.disconnect();
}
}
if (monitor != null) monitor.worked(1);
if (monitor != null) monitor.done();
return stats;
}
/**
* @return Returns the logTable.
*/
public String getLogTable()
{
return logTable;
}
/**
* @param logTable The logTable to set.
*/
public void setLogTable(String logTable)
{
this.logTable = logTable;
}
}
| true | true | public JobMeta(LogWriter log, Repository rep, String jobname, RepositoryDirectory repdir, IProgressMonitor monitor)
throws KettleException
{
this.log = log;
try
{
// Clear everything...
clear();
directory = repdir;
// Get the transformation id
setID( rep.getJobID(jobname, repdir.getID()) );
// If no valid id is available in the database, then give error...
if (getID()>0)
{
// Load the notes...
long noteids[] = rep.getJobNoteIDs(getID());
long jecids[] = rep.getJobEntryCopyIDs(getID());
long hopid[] = rep.getJobHopIDs(getID());
int nrWork = 2+noteids.length+jecids.length+hopid.length;
if (monitor!=null) monitor.beginTask("Loading job "+repdir+Const.FILE_SEPARATOR+jobname, nrWork);
//
// Load the common database connections
//
if (monitor!=null) monitor.subTask("Reading the available database from the repository");
readDatabases(rep);
if (monitor!=null) monitor.worked(1);
//
// get job info:
//
if (monitor!=null) monitor.subTask("Reading the job information");
Row jobrow = rep.getJob(getID());
name = jobrow.searchValue("NAME").getString();
logTable = jobrow.searchValue("TABLE_NAME_LOG").getString();
long id_logdb = jobrow.searchValue("ID_DATABASE_LOG").getInteger();
if (id_logdb>0)
{
// Get the logconnection
logconnection = new DatabaseMeta(rep, id_logdb);
}
useBatchId = jobrow.getBoolean("USE_BATCH_ID", false);
batchIdPassed = jobrow.getBoolean("PASS_BATCH_ID", false);
logfieldUsed = jobrow.getBoolean("USE_LOGFIELD", false);
if (monitor!=null) monitor.worked(1);
log.logDetailed(toString(), "Loading "+noteids.length+" notes");
for (int i=0;i<noteids.length;i++)
{
if (monitor!=null) monitor.subTask("Reading note #"+(i+1)+"/"+noteids.length);
NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]);
if (indexOfNote(ni)<0) addNote(ni);
if (monitor!=null) monitor.worked(1);
}
// Load the job entries...
log.logDetailed(toString(), "Loading "+jecids.length+" job entries");
for (int i=0;i<jecids.length;i++)
{
if (monitor!=null) monitor.subTask("Reading job entry #"+(i+1)+"/"+(jecids.length));
JobEntryCopy jec = new JobEntryCopy(log, rep, getID(), jecids[i], jobentries, databases);
int idx = indexOfJobEntry(jec);
if (idx < 0)
{
if (jec.getName()!=null && jec.getName().length()>0) addJobEntry(jec);
}
else
{
setJobEntry(idx, jec); // replace it!
}
if (monitor!=null) monitor.worked(1);
}
// Load the hops...
log.logDetailed(toString(), "Loading "+hopid.length+" job hops");
for (int i=0;i<hopid.length;i++)
{
if (monitor!=null) monitor.subTask("Reading job hop #"+(i+1)+"/"+(jecids.length));
JobHopMeta hi = new JobHopMeta(rep, hopid[i], this, jobcopies);
jobhops.add(hi);
if (monitor!=null) monitor.worked(1);
}
// Finally, clear the changed flags...
clearChanged();
if (monitor!=null) monitor.subTask("Finishing load");
if (monitor!=null) monitor.done();
}
else
{
throw new KettleException("Can't find job : "+jobname);
}
}
catch(KettleException dbe)
{
throw new KettleException("An error occurred reading job ["+jobname+"] from the repository", dbe);
}
}
| public JobMeta(LogWriter log, Repository rep, String jobname, RepositoryDirectory repdir, IProgressMonitor monitor)
throws KettleException
{
this.log = log;
try
{
// Clear everything...
clear();
directory = repdir;
// Get the transformation id
setID( rep.getJobID(jobname, repdir.getID()) );
// If no valid id is available in the database, then give error...
if (getID()>0)
{
// Load the notes...
long noteids[] = rep.getJobNoteIDs(getID());
long jecids[] = rep.getJobEntryCopyIDs(getID());
long hopid[] = rep.getJobHopIDs(getID());
int nrWork = 2+noteids.length+jecids.length+hopid.length;
if (monitor!=null) monitor.beginTask("Loading job "+repdir+Const.FILE_SEPARATOR+jobname, nrWork);
//
// Load the common database connections
//
if (monitor!=null) monitor.subTask("Reading the available database from the repository");
readDatabases(rep);
if (monitor!=null) monitor.worked(1);
//
// get job info:
//
if (monitor!=null) monitor.subTask("Reading the job information");
Row jobrow = rep.getJob(getID());
name = jobrow.searchValue("NAME").getString();
logTable = jobrow.searchValue("TABLE_NAME_LOG").getString();
long id_logdb = jobrow.searchValue("ID_DATABASE_LOG").getInteger();
if (id_logdb>0)
{
// Get the logconnection
logconnection = new DatabaseMeta(rep, id_logdb);
}
useBatchId = jobrow.getBoolean("USE_BATCH_ID", false);
batchIdPassed = jobrow.getBoolean("PASS_BATCH_ID", false);
logfieldUsed = jobrow.getBoolean("USE_LOGFIELD", false);
if (monitor!=null) monitor.worked(1);
log.logDetailed(toString(), "Loading "+noteids.length+" notes");
for (int i=0;i<noteids.length;i++)
{
if (monitor!=null) monitor.subTask("Reading note #"+(i+1)+"/"+noteids.length);
NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]);
if (indexOfNote(ni)<0) addNote(ni);
if (monitor!=null) monitor.worked(1);
}
// Load the job entries...
log.logDetailed(toString(), "Loading "+jecids.length+" job entries");
for (int i=0;i<jecids.length;i++)
{
if (monitor!=null) monitor.subTask("Reading job entry #"+(i+1)+"/"+(jecids.length));
JobEntryCopy jec = new JobEntryCopy(log, rep, getID(), jecids[i], jobentries, databases);
int idx = indexOfJobEntry(jec);
if (idx < 0)
{
if (jec.getName()!=null && jec.getName().length()>0) addJobEntry(jec);
}
else
{
setJobEntry(idx, jec); // replace it!
}
if (monitor!=null) monitor.worked(1);
}
// Load the hops...
log.logDetailed(toString(), "Loading "+hopid.length+" job hops");
for (int i=0;i<hopid.length;i++)
{
if (monitor!=null) monitor.subTask("Reading job hop #"+(i+1)+"/"+(jecids.length));
JobHopMeta hi = new JobHopMeta(rep, hopid[i], this, jobcopies);
jobhops.add(hi);
if (monitor!=null) monitor.worked(1);
}
// Finally, clear the changed flags...
clearChanged();
if (monitor!=null) monitor.subTask("Finishing load");
if (monitor!=null) monitor.done();
}
else
{
throw new KettleException("Can't find job : "+jobname);
}
}
catch(KettleException dbe)
{
throw new KettleException("An error occurred reading job ["+jobname+"] from the repository", dbe);
}
}
|
diff --git a/gndms/src/de/zib/gndms/gndms/security/HostAndUserDetailsService.java b/gndms/src/de/zib/gndms/gndms/security/HostAndUserDetailsService.java
index c513aa46..836cb503 100644
--- a/gndms/src/de/zib/gndms/gndms/security/HostAndUserDetailsService.java
+++ b/gndms/src/de/zib/gndms/gndms/security/HostAndUserDetailsService.java
@@ -1,156 +1,155 @@
package de.zib.gndms.gndms.security;
/*
* Copyright 2008-2011 Zuse Institute Berlin (ZIB)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import de.zib.gndms.stuff.misc.X509DnConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
/**
* @author Maik Jorra
* @email [email protected]
* @date 20.03.12 17:39
* @brief
*/
public class HostAndUserDetailsService implements AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {
private GridMapUserDetailsService userDetailsService;
private String allowedHostsFileName;
private boolean reverseDNSTest = true;
protected Logger logger = LoggerFactory.getLogger( this.getClass() );
@Override
public UserDetails loadUserDetails(
final PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken )
throws UsernameNotFoundException
{
- // todo check host cert
String dn = ( String ) preAuthenticatedAuthenticationToken.getPrincipal();
try {
if( GridMapUserDetailsService.searchInGridMapfile( allowedHostsFileName, dn ) ) {
if ( reverseDNSTest )
try {
if( ! reverseDNSLookup( X509DnConverter.openSslDnExtractCn( dn ),
preAuthenticatedAuthenticationToken.getDetails() ) ) {
logger.info( "Host-CN revers DNS lookup failed for: " + dn );
throw new BadCredentialsException( "Host-CN reverse DNS lookup failed."
);
}
} catch ( UnknownHostException e ) {
throw new BadCredentialsException( "", e );
}
GNDMSUserDetails userDetails = new GNDMSUserDetails();
userDetails.setAuthorities( Collections.<GrantedAuthority>emptyList() );
userDetails.setDn( dn );
userDetails.setIsUser( false );
return userDetails;
} else {
final SecurityContext context = SecurityContextHolder.getContext();
if( context != null && context.getAuthentication() != null ) {
final Object principal = context.getAuthentication().getPrincipal();
if( principal instanceof GNDMSUserDetails ) {
// now this must be the Request header authentication
final GNDMSUserDetails gndmsUserDetails = ( GNDMSUserDetails ) principal;
if( gndmsUserDetails.isUser() )
// the x509 cert from the previous filter must have been a user cert
// check if the dn's match
if (! dn.equals( gndmsUserDetails.getUsername() ) )
throw new UsernameNotFoundException( "Certificate vs HttpHeader: dn " +
"mismatch");
}
}
return userDetailsService.loadUserByUsername( dn );
}
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}
private boolean reverseDNSLookup( final String hostName, final Object details ) throws UnknownHostException {
String requestSourceIp = null;
if( details instanceof WebAuthenticationDetails ) {
requestSourceIp = ((WebAuthenticationDetails) details).getRemoteAddress();
InetAddress addr = InetAddress.getByName( hostName );
if( ! addr.getHostAddress().equals( requestSourceIp ) ) {
logger.info( "Revers dns lookup fail for host: \"" +hostName + "\" got: " +
requestSourceIp );
return false;
}
return true;
}
return false;
}
public GridMapUserDetailsService getUserDetailsService() {
return userDetailsService;
}
public void setUserDetailsService( final GridMapUserDetailsService userDetailsService ) {
this.userDetailsService = userDetailsService;
}
public void setReverseDNSTest( final boolean reverseDNSTest ) {
this.reverseDNSTest = reverseDNSTest;
}
public void setAllowedHostsFileName( final String allowedHostsFileName ) {
this.allowedHostsFileName = allowedHostsFileName;
}
public String getAllowedHostsFileName() {
return allowedHostsFileName;
}
public boolean isReverseDNSTest() {
return reverseDNSTest;
}
}
| true | true | public UserDetails loadUserDetails(
final PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken )
throws UsernameNotFoundException
{
// todo check host cert
String dn = ( String ) preAuthenticatedAuthenticationToken.getPrincipal();
try {
if( GridMapUserDetailsService.searchInGridMapfile( allowedHostsFileName, dn ) ) {
if ( reverseDNSTest )
try {
if( ! reverseDNSLookup( X509DnConverter.openSslDnExtractCn( dn ),
preAuthenticatedAuthenticationToken.getDetails() ) ) {
logger.info( "Host-CN revers DNS lookup failed for: " + dn );
throw new BadCredentialsException( "Host-CN reverse DNS lookup failed."
);
}
} catch ( UnknownHostException e ) {
throw new BadCredentialsException( "", e );
}
GNDMSUserDetails userDetails = new GNDMSUserDetails();
userDetails.setAuthorities( Collections.<GrantedAuthority>emptyList() );
userDetails.setDn( dn );
userDetails.setIsUser( false );
return userDetails;
} else {
final SecurityContext context = SecurityContextHolder.getContext();
if( context != null && context.getAuthentication() != null ) {
final Object principal = context.getAuthentication().getPrincipal();
if( principal instanceof GNDMSUserDetails ) {
// now this must be the Request header authentication
final GNDMSUserDetails gndmsUserDetails = ( GNDMSUserDetails ) principal;
if( gndmsUserDetails.isUser() )
// the x509 cert from the previous filter must have been a user cert
// check if the dn's match
if (! dn.equals( gndmsUserDetails.getUsername() ) )
throw new UsernameNotFoundException( "Certificate vs HttpHeader: dn " +
"mismatch");
}
}
return userDetailsService.loadUserByUsername( dn );
}
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}
| public UserDetails loadUserDetails(
final PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken )
throws UsernameNotFoundException
{
String dn = ( String ) preAuthenticatedAuthenticationToken.getPrincipal();
try {
if( GridMapUserDetailsService.searchInGridMapfile( allowedHostsFileName, dn ) ) {
if ( reverseDNSTest )
try {
if( ! reverseDNSLookup( X509DnConverter.openSslDnExtractCn( dn ),
preAuthenticatedAuthenticationToken.getDetails() ) ) {
logger.info( "Host-CN revers DNS lookup failed for: " + dn );
throw new BadCredentialsException( "Host-CN reverse DNS lookup failed."
);
}
} catch ( UnknownHostException e ) {
throw new BadCredentialsException( "", e );
}
GNDMSUserDetails userDetails = new GNDMSUserDetails();
userDetails.setAuthorities( Collections.<GrantedAuthority>emptyList() );
userDetails.setDn( dn );
userDetails.setIsUser( false );
return userDetails;
} else {
final SecurityContext context = SecurityContextHolder.getContext();
if( context != null && context.getAuthentication() != null ) {
final Object principal = context.getAuthentication().getPrincipal();
if( principal instanceof GNDMSUserDetails ) {
// now this must be the Request header authentication
final GNDMSUserDetails gndmsUserDetails = ( GNDMSUserDetails ) principal;
if( gndmsUserDetails.isUser() )
// the x509 cert from the previous filter must have been a user cert
// check if the dn's match
if (! dn.equals( gndmsUserDetails.getUsername() ) )
throw new UsernameNotFoundException( "Certificate vs HttpHeader: dn " +
"mismatch");
}
}
return userDetailsService.loadUserByUsername( dn );
}
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}
|
diff --git a/rhogen-wizard/src/rhogenwizard/buildfile/CustomConverter.java b/rhogen-wizard/src/rhogenwizard/buildfile/CustomConverter.java
index a02e91c..cbf89ff 100644
--- a/rhogen-wizard/src/rhogenwizard/buildfile/CustomConverter.java
+++ b/rhogen-wizard/src/rhogenwizard/buildfile/CustomConverter.java
@@ -1,250 +1,250 @@
package rhogenwizard.buildfile;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.yaml.snakeyaml.Yaml;
public class CustomConverter extends AbstractStructureConverter
{
private static final String shiftLevel = " ";
private static final String crCode = "\n";
private static final char rubyCommentsCode = '#';
Map<String, String> m_commentsStorage = new HashMap<String, String>();
@Override
public String convertStructure()
{
StringBuilder sb = new StringBuilder();
Iterator it = m_dataStructure.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
Object key = (Object) pairs.getKey();
Object val = pairs.getValue();
saveSelector(sb, "", key.toString(), val);
}
return addComments(sb.toString());
}
private String addComments(String rawYmlData)
{
StringTokenizer st = new StringTokenizer(rawYmlData, crCode);
StringBuilder sb = new StringBuilder();
while (st.hasMoreTokens())
{
String tokenString = st.nextToken();
String trimString = tokenString.trim();
String comments = m_commentsStorage.get(trimString);
if (comments != null)
{
sb.append(comments);
sb.append(crCode);
}
sb.append(tokenString);
sb.append(crCode);
}
return sb.toString();
}
void saveSelector(StringBuilder sb, String prefix, String name, Object val)
{
if (val instanceof List)
{
saveList(sb, prefix, name, (List)val);
}
else if (val instanceof Map)
{
saveMap(sb, prefix, name, (Map)val);
}
else
{
saveValue(sb, prefix, name, val);
}
}
private void saveValue(StringBuilder sb, String prefix, String name, Object l)
{
sb.append(prefix);
sb.append(name);
sb.append(": ");
if (l != null)
{
if (l instanceof String)
{
String itemValue = l.toString();
itemValue = itemValue.replace("\\", "/");
if (itemValue.length() != 0)
{
char firstChar = itemValue.charAt(0);
char lstChar = itemValue.charAt(itemValue.length() - 1);
if (firstChar == '*' || lstChar == '*')
{
sb.append("\"");
sb.append(itemValue.toString());
sb.append("\"");
}
else
{
sb.append(itemValue.toString());
}
}
}
else
{
sb.append(l.toString());
}
}
sb.append(crCode);
}
private void saveList(StringBuilder sb, String prefix, String name, List l)
{
sb.append(prefix);
sb.append(name);
sb.append(":");
sb.append(crCode);
for (int i=0; i<l.size(); ++i)
{
Object val = l.get(i);
sb.append(prefix);
sb.append(shiftLevel + "- ");
String renderVal = val.toString();
if (renderVal.length() != 0)
{
char firstChar = renderVal.charAt(0);
char lstChar = renderVal.charAt(renderVal.length() - 1);
if (firstChar == '*' || lstChar == '*')
{
sb.append("\"");
sb.append(val.toString());
sb.append("\"");
}
else
{
sb.append(val.toString());
}
}
sb.append(crCode);
}
}
private void saveMap(StringBuilder sb, String prefix, String name, Map m)
{
if (name != null)
{
sb.append(prefix);
sb.append(name);
sb.append(":");
sb.append(crCode);
}
Iterator it = m.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
Object key = (Object) pairs.getKey();
Object val = pairs.getValue();
saveSelector(sb, prefix + shiftLevel, key.toString(), val);
}
}
private void fillCommentsMap(String filePath)
{
try
{
FileInputStream fStream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
StringBuilder commentsBuilder = new StringBuilder();
while((strLine = br.readLine()) != null)
{
String trimLine = strLine.trim();
if (trimLine.length() != 0)
{
if (trimLine.charAt(0) == rubyCommentsCode)
{
commentsBuilder.append(strLine);
continue;
}
else
{
if (trimLine.contains("#"))
{
int startChar = trimLine.indexOf("#");
if (startChar > 0) {
- m_commentsStorage.put(trimLine.substring(0, startChar).trim(), trimLine.substring(startChar, trimLine.length() - 1).trim());
+ m_commentsStorage.put(trimLine.substring(0, startChar).trim(), trimLine.substring(startChar, trimLine.length() - 1));
continue;
}
}
}
}
if (commentsBuilder.length() != 0)
{
m_commentsStorage.put(strLine, commentsBuilder.toString());
commentsBuilder = new StringBuilder();
}
}
br.close();
in.close();
fStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public Map getDataStorage(String filePath) throws FileNotFoundException
{
File ymlFile = new File(filePath);
Yaml yaml = new Yaml();
FileReader fr = new FileReader(ymlFile);
fillCommentsMap(filePath);
return (Map) yaml.load(fr);
}
}
| true | true | private void fillCommentsMap(String filePath)
{
try
{
FileInputStream fStream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
StringBuilder commentsBuilder = new StringBuilder();
while((strLine = br.readLine()) != null)
{
String trimLine = strLine.trim();
if (trimLine.length() != 0)
{
if (trimLine.charAt(0) == rubyCommentsCode)
{
commentsBuilder.append(strLine);
continue;
}
else
{
if (trimLine.contains("#"))
{
int startChar = trimLine.indexOf("#");
if (startChar > 0) {
m_commentsStorage.put(trimLine.substring(0, startChar).trim(), trimLine.substring(startChar, trimLine.length() - 1).trim());
continue;
}
}
}
}
if (commentsBuilder.length() != 0)
{
m_commentsStorage.put(strLine, commentsBuilder.toString());
commentsBuilder = new StringBuilder();
}
}
br.close();
in.close();
fStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
| private void fillCommentsMap(String filePath)
{
try
{
FileInputStream fStream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
StringBuilder commentsBuilder = new StringBuilder();
while((strLine = br.readLine()) != null)
{
String trimLine = strLine.trim();
if (trimLine.length() != 0)
{
if (trimLine.charAt(0) == rubyCommentsCode)
{
commentsBuilder.append(strLine);
continue;
}
else
{
if (trimLine.contains("#"))
{
int startChar = trimLine.indexOf("#");
if (startChar > 0) {
m_commentsStorage.put(trimLine.substring(0, startChar).trim(), trimLine.substring(startChar, trimLine.length() - 1));
continue;
}
}
}
}
if (commentsBuilder.length() != 0)
{
m_commentsStorage.put(strLine, commentsBuilder.toString());
commentsBuilder = new StringBuilder();
}
}
br.close();
in.close();
fStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
|
diff --git a/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyTreeNumberingHooks.java b/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyTreeNumberingHooks.java
index 1ffcf7cb23..5d8bfb5b1a 100644
--- a/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyTreeNumberingHooks.java
+++ b/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyTreeNumberingHooks.java
@@ -1,87 +1,87 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.2.0
*
* This file is part of Qcadoo.
*
* Qcadoo 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.technologies;
import static com.qcadoo.mes.technologies.states.constants.TechnologyState.DRAFT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qcadoo.mes.technologies.constants.TechnologiesConstants;
import com.qcadoo.mes.technologies.constants.TechnologyFields;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.EntityTree;
import com.qcadoo.model.api.utils.TreeNumberingService;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.FormComponent;
@Service
public class TechnologyTreeNumberingHooks {
@Autowired
private TreeNumberingService treeNumberingService;
@Autowired
private DataDefinitionService dataDefinitionService;
private static final Logger LOG = LoggerFactory.getLogger(TechnologyTreeNumberingHooks.class);
public void rebuildTreeNumbering(final ViewDefinitionState view) {
FormComponent form = (FormComponent) view.getComponentByReference("form");
Long technologyId = form.getEntityId();
if (technologyId == null) {
return;
}
Entity technology = getTechnologyById(technologyId);
if (!isDraftTechnology(technology)) {
return;
}
EntityTree technologyTree = technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS);
if (technologyTree == null || technologyTree.getRoot() == null) {
return;
}
debug("Fire tree node number generator for tecnology with id = " + technologyId);
- treeNumberingService.generateNumbersAndUpdateTree(technologyTree);
+ treeNumberingService.generateTreeNumbers(technologyTree);
}
private Entity getTechnologyById(final Long id) {
return dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY).get(id);
}
private boolean isDraftTechnology(final Entity technology) {
return DRAFT.getStringValue().equals(technology.getStringField(TechnologyFields.STATE));
}
private void debug(final String message) {
if (LOG.isDebugEnabled()) {
LOG.debug(message);
}
}
}
| true | true | public void rebuildTreeNumbering(final ViewDefinitionState view) {
FormComponent form = (FormComponent) view.getComponentByReference("form");
Long technologyId = form.getEntityId();
if (technologyId == null) {
return;
}
Entity technology = getTechnologyById(technologyId);
if (!isDraftTechnology(technology)) {
return;
}
EntityTree technologyTree = technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS);
if (technologyTree == null || technologyTree.getRoot() == null) {
return;
}
debug("Fire tree node number generator for tecnology with id = " + technologyId);
treeNumberingService.generateNumbersAndUpdateTree(technologyTree);
}
| public void rebuildTreeNumbering(final ViewDefinitionState view) {
FormComponent form = (FormComponent) view.getComponentByReference("form");
Long technologyId = form.getEntityId();
if (technologyId == null) {
return;
}
Entity technology = getTechnologyById(technologyId);
if (!isDraftTechnology(technology)) {
return;
}
EntityTree technologyTree = technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS);
if (technologyTree == null || technologyTree.getRoot() == null) {
return;
}
debug("Fire tree node number generator for tecnology with id = " + technologyId);
treeNumberingService.generateTreeNumbers(technologyTree);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.