answer
stringlengths 17
10.2M
|
|---|
package com.androidsensei.soladroid.pomodoro.timer.ui;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.androidsensei.soladroid.R;
import com.androidsensei.soladroid.pomodoro.timer.logic.PomodoroFragmentStateManager;
import com.androidsensei.soladroid.pomodoro.timer.logic.PomodoroTimer;
import com.androidsensei.soladroid.trello.api.model.Card;
import com.androidsensei.soladroid.utils.AppConstants;
import com.androidsensei.soladroid.utils.SolaDroidBaseFragment;
public class PomodoroFragment extends SolaDroidBaseFragment {
/**
* This fragment's countdownTime manager.
*/
private PomodoroFragmentStateManager stateManager;
/**
* The Pomodoro count down timer used to determine the current countdownTime of the Pomodoro for the task at hand.
*/
private PomodoroTimer pomodoroTimer;
/**
* Text view to display the Pomodoro counter.
*/
private TextView pomodoroCounter;
/**
* Text view to display the timer view.
*/
private TextView pomodoroTimerView;
/**
* Text view to display the total time.
*/
private TextView pomodoroTotalTime;
/**
* The button section for running the Pomodoro.
*/
private View runningSection;
/**
* The button section for when a Pomodoro is finished.
*/
private View finishedSection;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_pomodoro, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Card trelloCard = (Card) getArguments().getSerializable(AppConstants.ARG_START_TASK_CARD);
stateManager = PomodoroFragmentStateManager.getInstance();
stateManager.setTrelloCard(trelloCard);
if (savedInstanceState == null) {
initCountdownTimer(PomodoroFragmentStateManager.CountdownTime.POMODORO, false);
} else {
initCountdownTimer(stateManager.countdownTime(), true);
setTimerButtonsState();
if (stateManager.pomodoroFinished() || stateManager.breakFinished()) {
toggleActionSections();
}
}
initTextViews();
setupPomodoroPauseButton();
setupPomodoroStopButton();
}
/**
* Initializes the views for the fragment.
*/
private void initTextViews() {
pomodoroCounter = (TextView) getView().findViewById(R.id.timer_pomodoro_counter);
pomodoroTotalTime = (TextView) getView().findViewById(R.id.timer_pomodoro_total);
pomodoroCounter.setText(getString(R.string.timer_pomodoro_counter, "" + stateManager.pomodoroCount()));
pomodoroTotalTime.setText(getString(R.string.timer_pomodoro_total, DateUtils.formatElapsedTime(stateManager.totalTime())));
setTimerView();
}
/**
* Initializes the timer view.
*/
private void setTimerView() {
pomodoroTimerView = (TextView) getView().findViewById(R.id.timer_pomodoro_timer);
pomodoroTimerView.setText("" + DateUtils.formatElapsedTime(pomodoroTimer.getRemainingTime()));
}
/**
* Toggles the finished and running sections of buttons based on their current countdownTime. They will become visible if
* they are invisible and viceversa.
*/
private void toggleActionSections() {
runningSection = getView().findViewById(R.id.timer_pomodoro_running_section);
finishedSection = getView().findViewById(R.id.timer_pomodoro_finished_section);
boolean isRunningVisbile = runningSection.getVisibility() == View.VISIBLE;
boolean isFinishedVisible = finishedSection.getVisibility() == View.VISIBLE;
runningSection.setVisibility(isRunningVisbile ? View.INVISIBLE : View.VISIBLE);
finishedSection.setVisibility(isFinishedVisible ? View.INVISIBLE : View.VISIBLE);
}
/**
* Setup the pause/resume button.
*/
private void setupPomodoroPauseButton() {
final Button pause = (Button) getView().findViewById(R.id.timer_pomodoro_pause);
final Button stop = (Button) getView().findViewById(R.id.timer_pomodoro_stop);
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (pomodoroTimer.isPaused()) {
pomodoroTimer.start();
pause.setText(getResources().getText(R.string.timer_pomodoro_pause));
stop.setEnabled(true);
} else {
pomodoroTimer.pause();
pause.setText(getResources().getText(R.string.timer_pomodoro_resume));
stop.setEnabled(false);
}
}
});
}
/**
* Preserve the state of the timer action buttons after a configuration change.
*/
private void setTimerButtonsState() {
final Button pause = (Button) getView().findViewById(R.id.timer_pomodoro_pause);
final Button stop = (Button) getView().findViewById(R.id.timer_pomodoro_stop);
if (pomodoroTimer.isPaused()) {
pause.setText(getResources().getText(R.string.timer_pomodoro_resume));
stop.setEnabled(false);
} else if (pomodoroTimer.isStopped()) {
stop.setText(getResources().getText(R.string.timer_pomodoro_start));
pause.setEnabled(false);
}
}
/**
* Setup the start/stop button.
*/
private void setupPomodoroStopButton() {
final Button stop = (Button) getView().findViewById(R.id.timer_pomodoro_stop);
final Button pause = (Button) getView().findViewById(R.id.timer_pomodoro_pause);
if (pomodoroTimer.isInitialized()) {
stop.setText(getResources().getText(R.string.timer_pomodoro_start));
pause.setEnabled(false);
}
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (pomodoroTimer.isStopped() || pomodoroTimer.isInitialized()) {
pomodoroTimer.start();
stop.setText(getResources().getText(R.string.timer_pomodoro_stop));
pause.setEnabled(true);
} else {
pomodoroTimer.stop();
stop.setText(getResources().getText(R.string.timer_pomodoro_start));
pause.setEnabled(false);
}
}
});
}
/**
* Creates and initializes the Pomodoro countdown timer.
*/
private void initCountdownTimer(final PomodoroFragmentStateManager.CountdownTime state, boolean configChanged) {
pomodoroTimer = stateManager.initTimer(configChanged, state, new PomodoroTimer.PomodoroCounterCallback() {
@Override
public void onTick(long secondsToNone) {
if (isAdded()) {
pomodoroTimerView.setText(DateUtils.formatElapsedTime(secondsToNone));
}
}
@Override
public void onFinish(long elapsedTime) {
stateManager.incrementTotalTime(elapsedTime);
stateManager.incrementPomodoroCount();
if (isAdded()) {
pomodoroCounter.setText(getString(R.string.timer_pomodoro_counter, "" + stateManager.pomodoroCount()));
pomodoroTotalTime.setText(getString(R.string.timer_pomodoro_total, DateUtils.formatElapsedTime(stateManager.totalTime())));
pomodoroTimerView.setText("" + DateUtils.formatElapsedTime(0));
toggleActionSections();
}
}
@Override
public void onStop(long elapsedTime) {
stateManager.incrementTotalTime(elapsedTime);
if (isAdded()) {
pomodoroTotalTime.setText(getString(R.string.timer_pomodoro_total, DateUtils.formatElapsedTime(stateManager.totalTime())));
pomodoroTimerView.setText("" + DateUtils.formatElapsedTime(state.value()));
}
}
});
}
/**
* Factory method for creating pomodoro fragment instances.
*
* @param card the Trello card we're currently working on - passed in the Fragment arguments
* @return the PomodoroFragment instance created with arguments set
*/
public static PomodoroFragment createFragment(Card card) {
PomodoroFragment fragment = new PomodoroFragment();
Bundle args = new Bundle();
args.putSerializable(AppConstants.ARG_START_TASK_CARD, card);
fragment.setArguments(args);
return fragment;
}
public PomodoroFragment() {
}
}
|
package com.macro.mall.dto;
import com.macro.mall.model.UmsPermission;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
public class UmsPermissionNode extends UmsPermission {
@Getter
@Setter
private List<UmsPermissionNode> children;
}
|
package de.fau.cs.mad.kwikshop.android.viewmodel;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.inject.Inject;
import de.fau.cs.mad.kwikshop.android.R;
import de.fau.cs.mad.kwikshop.android.model.*;
import de.fau.cs.mad.kwikshop.android.model.interfaces.ListManager;
import de.fau.cs.mad.kwikshop.android.model.interfaces.SimpleStorage;
import de.fau.cs.mad.kwikshop.android.model.messages.*;
import de.fau.cs.mad.kwikshop.android.restclient.RestClientFactory;
import de.fau.cs.mad.kwikshop.android.util.ItemComparator;
import de.fau.cs.mad.kwikshop.android.util.SharedPreferencesHelper;
import de.fau.cs.mad.kwikshop.android.view.DisplayHelper;
import de.fau.cs.mad.kwikshop.android.view.ItemSortType;
import de.fau.cs.mad.kwikshop.android.view.ShoppingListActivity;
import de.fau.cs.mad.kwikshop.android.viewmodel.common.*;
import de.fau.cs.mad.kwikshop.common.Group;
import de.fau.cs.mad.kwikshop.common.Item;
import de.fau.cs.mad.kwikshop.common.LastLocation;
import de.fau.cs.mad.kwikshop.common.Recipe;
import de.fau.cs.mad.kwikshop.common.RepeatType;
import de.fau.cs.mad.kwikshop.common.ShoppingList;
import de.fau.cs.mad.kwikshop.common.Unit;
import de.fau.cs.mad.kwikshop.common.sorting.BoughtItem;
import de.fau.cs.mad.kwikshop.common.sorting.ItemOrderWrapper;
import de.greenrobot.event.EventBus;
import se.walkercrou.places.Place;
public class ShoppingListViewModel extends ListViewModel<ShoppingList> {
//region Fields
private int tmp_item_id;
private boolean inShoppingMode = false;
private ArrayList<Item> swipedItemOrder = new ArrayList<>();
private List<Place> places;
private ItemSortType itemSortType = ItemSortType.MANUAL;
private final ObservableArrayList<ItemViewModel, Integer> checkedItems = new ObservableArrayList<>(new ItemIdExtractor());
private boolean findNearbySupermarketCanceled = false;
private Context context;
private final ResourceProvider resourceProvider;
private final RegularlyRepeatHelper repeatHelper;
private final ListManager<Recipe> recipeManager;
private final RestClientFactory clientFactory;
private final LocationManager locationManager;
private Place currentPlace;
//region Commands
private final Command<Integer> toggleIsBoughtCommand = new Command<Integer>() {
@Override
public void execute(Integer parameter) {
toggleIsBoughtCommandExecute(parameter);
}
};
private final Command<Integer> deleteItemCommand = new Command<Integer>() {
@Override
public void execute(Integer parameter) {
deleteItemCommandExecute(parameter);
}
};
private final Command<Void> sendBoughtItemsToServerCommand = new Command<Void>() {
@Override
public void execute(Void parameter) {
sendBoughtItemsToServerCommandExecute();
}
};
private final Command<Void> findNearbySupermarketCommand = new Command<Void>() {
@Override
public void execute(Void parameter) {
findNearbySupermarketCommandExecute();
}
};
final Command<Void> deleteCheckBoxCheckedCommand = new Command<Void>() {
@Override
public void execute(Void parameter) {
SharedPreferencesHelper.saveBoolean(SharedPreferencesHelper.ITEM_DELETION_SHOW_AGAIN_MSG, false, context);
}
};
final Command<Void> deletePositiveCommand = new Command<Void>() {
@Override
public void execute(Void parameter) {
listManager.deleteItem(listId, tmp_item_id);
}
};
final Command<Void> disableLocalizationCommand = new Command<Void>(){
@Override
public void execute(Void parameter) {
SharedPreferencesHelper.saveBoolean(SharedPreferencesHelper.LOCATION_PERMISSION, false, context);
}
};
final Command<Void> withdrawLocalizationPermissionCommand = new Command<Void>(){
@Override
public void execute(Void parameter) {
SharedPreferencesHelper.saveBoolean(SharedPreferencesHelper.LOCATION_PERMISSION, false, context);
}
};
final Command<Void> doNotShowLocalizationPermissionAgainCommand = new Command<Void>() {
@Override
public void execute(Void parameter) {
SharedPreferencesHelper.saveBoolean(SharedPreferencesHelper.LOCATION_PERMISSION_SHOW_AGAIN_MSG, false, context);
}
};
final Command<Void> showLocalizationPermissionAgainCommand = new Command<Void>() {
@Override
public void execute(Void parameter) {
SharedPreferencesHelper.saveBoolean(SharedPreferencesHelper.LOCATION_PERMISSION_SHOW_AGAIN_MSG, true, context );
}
};
//endregion
//endregion
//region Constructor
@Inject
public ShoppingListViewModel(Context context,
ViewLauncher viewLauncher,
ListManager<ShoppingList> shoppingListManager,
ListManager<Recipe> recipeManager,
SimpleStorage<Unit> unitStorage,
SimpleStorage<Group> groupStorage,
ItemParser itemParser,
DisplayHelper displayHelper,
AutoCompletionHelper autoCompletionHelper,
LocationFinderHelper locationFinderHelper,
ResourceProvider resourceProvider,
RegularlyRepeatHelper repeatHelper,
RestClientFactory clientFactory,
LocationManager locationManager) {
super(viewLauncher, shoppingListManager, unitStorage, groupStorage, itemParser, displayHelper,
autoCompletionHelper, locationFinderHelper);
if (context == null) throw new ArgumentNullException("context");
if (resourceProvider == null) {
throw new ArgumentNullException("resourceProvider");
}
if (repeatHelper == null) {
throw new ArgumentNullException("repeatHelper");
}
if (recipeManager == null) {
throw new ArgumentNullException("recipeManager");
}
if (clientFactory == null) {
throw new ArgumentNullException("clientFactory");
}
if(locationManager == null) {
throw new ArgumentNullException("locationManager");
}
this.context = context;
this.resourceProvider = resourceProvider;
this.repeatHelper = repeatHelper;
this.recipeManager = recipeManager;
this.clientFactory = clientFactory;
this.locationManager = locationManager;
}
//endregion
//region Properties
/**
* Gets how items are supposed to be sorted for the current shopping list
*/
public ItemSortType getItemSortType() {
return this.itemSortType;
}
/**
* Sets how items are supposed to be sorted for the current shopping list
*/
public void setItemSortType(ItemSortType value) {
this.itemSortType = value;
}
/**
* Gets the command to be executed when a item in the view is swiped
*/
public Command<Integer> getToggleIsBoughtCommand() {
return toggleIsBoughtCommand;
}
/**
* Gets the command to be executed when an item's delete-button is pressed
*/
public Command<Integer> getDeleteItemCommand() {
return deleteItemCommand;
}
public Command<Void> getSendBoughtItemsToServerCommand() {
return sendBoughtItemsToServerCommand;
}
public Command<Void> getFindNearbySupermarketCommand() {
return this.findNearbySupermarketCommand;
}
public ObservableArrayList<ItemViewModel, Integer> getCheckedItems() {
return checkedItems;
}
public void setInShoppingMode(boolean bool) {
this.inShoppingMode = bool;
}
public boolean getInShoppingMode() {
return this.inShoppingMode;
}
public int getBoughtItemsCount() {
ListIterator li = items.listIterator(items.size());
int i = 0;
while(li.hasPrevious()) {
ItemViewModel item = (ItemViewModel)li.previous();
if(item.getItem().isBought())
i++;
else
break;
}
return i;
}
public List<Item> getSwipedItemOrder(){ return this.swipedItemOrder; }
//endregion
//region Public Methods
@Override
public void itemsSwapped(int position1, int position2) {
Item item1 = items.get(position1).getItem();
Item item2 = items.get(position2).getItem();
item1.setOrder(position1);
item2.setOrder(position2);
listManager.saveListItem(listId, item1);
listManager.saveListItem(listId, item2);
}
public void deleteItem(int itemId, String title, String message, String positiveString, String negativeString, String checkBoxMessage) {
this.tmp_item_id = itemId;
if (SharedPreferencesHelper.loadBoolean(SharedPreferencesHelper.ITEM_DELETION_SHOW_AGAIN_MSG, true, context))
viewLauncher.showMessageDialogWithCheckbox(title, message, positiveString, deletePositiveCommand, null, null,
negativeString, NullCommand.VoidInstance,
checkBoxMessage, false, deleteCheckBoxCheckedCommand, null);
else
deletePositiveCommand.execute(null);
}
//TODO: this should be a command
public void showAddRecipeDialog(int listId) {
if (recipeManager.getLists().size() == 0) {
viewLauncher.showMessageDialog(resourceProvider.getString(R.string.recipe_add_recipe), resourceProvider.getString(R.string.recipe_no_recipe),
resourceProvider.getString(R.string.yes),
new Command<Void>() {
@Override
public void execute(Void parameter) {
viewLauncher.showAddRecipeView();
}
},
resourceProvider.getString(R.string.no), null);
} else {
viewLauncher.showAddRecipeDialog(listManager, recipeManager, listId, true);
}
}
public void moveBoughtItemsToEnd() {
Collections.sort(getItems(), new ItemComparator(displayHelper, ItemSortType.BOUGHTITEMS));
}
public void changeCheckBoxesVisibility(){
Iterator <ItemViewModel> itr = items.iterator();
while(itr.hasNext()){
updateItemViewModel(itr.next());
}
}
//endregion
//region Event Handlers
@SuppressWarnings("unused")
public void onEventMainThread(ShoppingListChangedEvent event) {
if (event.getListId() == this.listId) {
if (event.getChangeType() == ListChangeType.Deleted) {
finish();
} else if (event.getChangeType() == ListChangeType.PropertiesModified) {
loadList();
}
}
}
@SuppressWarnings("unused")
public void onEventMainThread(ItemChangedEvent event) {
if (event.getListType() == ListType.ShoppingList && event.getListId() == this.listId) {
switch (event.getChangeType()) {
case Added:
Item item = listManager.getListItem(listId, event.getItemId());
updateItem(new ItemViewModel(item));
sortItems();
updateOrderOfItems();
break;
case PropertiesModified:
Item item1 = listManager.getListItem(listId, event.getItemId());
updateItem(new ItemViewModel(item1));
updateOrderOfItems();
break;
case Deleted:
items.removeById(event.getItemId());
break;
}
}
}
@SuppressWarnings("unused")
public void onEventBackgroundThread(MoveAllItemsEvent event) {
boolean isBoughtNew = event.isMoveAllToBought();
ShoppingList list = listManager.getList(listId);
List<Item> changedItems = new LinkedList<>();
for (Item item : list.getItems()) {
if (item.isBought() != isBoughtNew) {
item.setBought(isBoughtNew);
changedItems.add(item);
}
}
for (Item item : changedItems) {
listManager.saveListItem(listId, item);
}
}
@SuppressWarnings("unused")
public void onEventMainThread(ItemSortType sortType) {
setItemSortType(sortType);
ShoppingList list = listManager.getList(listId);
list.setSortTypeInt(sortType.ordinal());
listManager.saveList(list.getId());
sortItems();
}
// results of place request
@SuppressWarnings("unused")
public void onEventMainThread(FindSupermarketsResult result) {
if(!findNearbySupermarketCanceled) {
viewLauncher.dismissProgressDialog();
setPlaces(result.getPlaces());
if(!LocationFinderHelper.checkPlaces(places)){
// no place info dialog
viewLauncher.showMessageDialog(
resourceProvider.getString(R.string.localization_no_place_dialog_title),
resourceProvider.getString(R.string.no_place_dialog_message),
resourceProvider.getString(R.string.dialog_OK),
NullCommand.VoidInstance,
resourceProvider.getString(R.string.dialog_retry),
getFindNearbySupermarketCommand()
);
return;
}
showSelectCurrentSupermarket(places);
}
}
//endregion
//region Command Implementations
@Override
protected void addItemCommandExecute() {
ensureIsInitialized();
getItems().enableEvents();
viewLauncher.showItemDetailsView(this.listId);
}
@Override
protected void selectItemCommandExecute(int itemId) {
ensureIsInitialized();
viewLauncher.showItemDetailsView(this.listId, itemId);
}
private void sendBoughtItemsToServerCommandExecute() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
List<BoughtItem> boughtItemOrder = new ArrayList<>();
for (Item item : swipedItemOrder) {
boughtItemOrder.add(new BoughtItem(item.getName(), item.getLocation().getPlaceId(), item.getLocation().getName()));
}
ItemOrderWrapper itemOrderWrapper = new ItemOrderWrapper(boughtItemOrder);
clientFactory.getShoppingListClient().postItemOrder(itemOrderWrapper);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
private void deleteItemCommandExecute(final int id) {
listManager.deleteItem(listId, id);
}
private void findNearbySupermarketCommandExecute() {
boolean isLocalizationEnabled = SharedPreferencesHelper.loadBoolean(SharedPreferencesHelper.LOCATION_PERMISSION, false, context);
findNearbySupermarketCanceled = false;
if(isLocalizationEnabled){
if(InternetHelper.checkInternetConnection(context)){
// progress dialog with listID to cancel progress
viewLauncher.showProgressDialogWithListID(
resourceProvider.getString(R.string.supermarket_finder_progress_dialog_message),
null,
listId,
true,
new Command<Integer>() {
@Override
public void execute(Integer parameter) {
if(parameter == listId) {
findNearbySupermarketCanceled = true;
}
}
}
);
// place request: radius 1500 result count 5
getNearbySupermarketPlaces(500, 10);
} else {
// no connection dialog
notificationOfNoConnectionWithLocationPermission();
}
} else {
if(SharedPreferencesHelper.loadBoolean(SharedPreferencesHelper.LOCATION_PERMISSION_SHOW_AGAIN_MSG, true, context)){
showAskForLocalizationPermission();
}
}
}
private void toggleIsBoughtCommandExecute(final int id) {
Item item = items.getById(id).getItem();
if(item != null) {
item.setBought(!item.isBought());
if (item.isBought()) {
//save location
if(currentPlace != null) {
// get location object for the place
LastLocation location = locationManager.getLocationForPlace(currentPlace);
item.setLocation(location);
}
swipedItemOrder.add(item);
Calendar now = Calendar.getInstance();
item.setLastBought(now.getTime());
if (item.getRepeatType() == RepeatType.Schedule && item.isRemindFromNextPurchaseOn()) {
Calendar remindDate = Calendar.getInstance();
switch (item.getPeriodType()) {
case DAYS:
remindDate.add(Calendar.DAY_OF_MONTH, item.getSelectedRepeatTime());
break;
case WEEKS:
remindDate.add(Calendar.DAY_OF_MONTH, item.getSelectedRepeatTime() * 7);
break;
case MONTHS:
remindDate.add(Calendar.MONTH, item.getSelectedRepeatTime());
break;
}
item.setRemindAtDate(remindDate.getTime());
repeatHelper.offerRepeatData(item);
DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.DEFAULT, SimpleDateFormat.DEFAULT, resourceProvider.getLocale());
String message = resourceProvider.getString(R.string.reminder_set_msg) + " " + dateFormat.format(remindDate.getTime());
viewLauncher.showToast(message, Toast.LENGTH_LONG);
}
} else {
swipedItemOrder.remove(item);
}
listManager.saveListItem(listId, item);
}
}
//endregion
//region Private / Protected Implementation
@Override
protected void loadList() {
ShoppingList shoppingList = listManager.getList(this.listId);
for(Item item : shoppingList.getItems()) {
updateItem(new ItemViewModel(item));
}
int sortTypeInt = shoppingList.getSortTypeInt();
switch (sortTypeInt) {
case 1:
setItemSortType(ItemSortType.GROUP);
break;
case 2:
setItemSortType(ItemSortType.ALPHABETICALLY);
break;
default:
setItemSortType(ItemSortType.MANUAL);
break;
}
sortItems();
//moveBoughtItemsToEnd();
this.setName(shoppingList.getName());
}
private void setPlaces(List<Place> places){
this.places = places;
}
private void updateItem(ItemViewModel item) {
if(item.getItem().isBought()) { // Add bought items at the end of the list
if (items.size() - 1 >= 0) {
items.setOrAddById(items.size() - 1, item);
} else {
items.setOrAddById(item);
}
} else {
items.setOrAddById(item);
}
items.notifyItemModified(item);
}
private void updateItemViewModel(ItemViewModel item) {
items.setOrAddById(item);
}
private void getNearbySupermarketPlaces(int radius, int resultCount){
SupermarketPlace.initiateSupermarketPlaceRequest(context, null, radius, resultCount);
}
private void notificationOfNoConnectionWithLocationPermission(){
viewLauncher.showMessageDialog(
resourceProvider.getString(R.string.localization_dialog_title),
resourceProvider.getString(R.string.localization_no_connection_message),
resourceProvider.getString(R.string.alert_dialog_connection_try),
findNearbySupermarketCommand,
resourceProvider.getString(R.string.localization_disable_localization),
disableLocalizationCommand
);
}
private void showAskForLocalizationPermission(){
viewLauncher.showMessageDialogWithCheckbox(
resourceProvider.getString(R.string.localization_dialog_title),
resourceProvider.getString(R.string.localization_dialog_message),
resourceProvider.getString(R.string.yes),
getFindNearbySupermarketCommand(),
null,
null,
resourceProvider.getString(R.string.no),
withdrawLocalizationPermissionCommand,
resourceProvider.getString(R.string.dont_show_this_message_again),
false,
doNotShowLocalizationPermissionAgainCommand,
showLocalizationPermissionAgainCommand
);
}
@SuppressWarnings("unchecked")
private void showSelectCurrentSupermarket(final List<Place> places){
if(places == null) {
return;
}
CharSequence[] placeNames = LocationFinderHelper.getNamesFromPlaces(places, context);
viewLauncher.showMessageDialogWithRadioButtons(
resourceProvider.getString(R.string.localization_supermarket_select_dialog_title),
placeNames,
resourceProvider.getString(R.string.dialog_OK),
new Command<Integer>() {
@Override
public void execute(Integer selectedIndex) {
if(selectedIndex >= 0 && selectedIndex < places.size()) {
currentPlace = places.get(selectedIndex);
}
}
},
resourceProvider.getString(R.string.dialog_retry),
new ParameterLessCommandWrapper<Integer>(getFindNearbySupermarketCommand()),
resourceProvider.getString(R.string.cancel),
NullCommand.IntegerInstance
);
}
private void sortItems() {
Collections.sort(getItems(), new ItemComparator(displayHelper, getItemSortType()));
moveBoughtItemsToEnd();
updateOrderOfItems();
listener.onItemSortTypeChanged();
}
//endregion
}
|
package cc.blynk.common.stats;
import cc.blynk.common.model.messages.ResponseMessage;
import cc.blynk.common.model.messages.protocol.HardwareMessage;
import cc.blynk.common.model.messages.protocol.PingMessage;
import cc.blynk.common.model.messages.protocol.appllication.*;
import cc.blynk.common.model.messages.protocol.hardware.TweetMessage;
import com.codahale.metrics.Meter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
public class GlobalStats {
private static final Logger log = LogManager.getLogger(GlobalStats.class);
private Meter incomeMessages;
private Map<Class<?>, LongAdder> specificCounters;
public GlobalStats() {
this.incomeMessages = new Meter();
this.specificCounters = new HashMap<>();
specificCounters.put(GetTokenMessage.class, new LongAdder());
specificCounters.put(RefreshTokenMessage.class, new LongAdder());
specificCounters.put(HardwareMessage.class, new LongAdder());
specificCounters.put(LoadProfileMessage.class, new LongAdder());
specificCounters.put(LoginMessage.class, new LongAdder());
specificCounters.put(PingMessage.class, new LongAdder());
specificCounters.put(RegisterMessage.class, new LongAdder());
specificCounters.put(SaveProfileMessage.class, new LongAdder());
specificCounters.put(ActivateDashboardMessage.class, new LongAdder());
specificCounters.put(DeActivateDashboardMessage.class, new LongAdder());
specificCounters.put(TweetMessage.class, new LongAdder());
specificCounters.put(ResponseMessage.class, new LongAdder());
}
public void mark(Class<?> clazz) {
specificCounters.get(clazz).increment();
}
public void mark() {
incomeMessages.mark(1);
}
public void log() {
//do not log low traffic. it is not interesting =).
if (incomeMessages.getOneMinuteRate() > 1) {
log.debug("1 min rate : {}", String.format("%.2f", incomeMessages.getOneMinuteRate()));
for (Map.Entry<Class<?>, LongAdder> counterEntry : specificCounters.entrySet()) {
log.debug("{} : {}", counterEntry.getKey().getSimpleName(), counterEntry.getValue().sum());
}
log.debug("
}
}
}
|
package volley.core.network;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import java.lang.reflect.Field;
import java.util.Map;
public abstract class CoreBaseRequest<T> {
/**
* @return base url of the server
*/
protected abstract String baseUrl();
/**
* GET, POST, PUT, DELETE
* @return integer value of Http Method
*/
protected abstract int httpMethod();
/**
* @param methodCode integer value of HTTP Methods
* @return String value of HTTP Methods defined in {@link com.android.volley.Request.Method}
*/
public static String getMethodName(int methodCode) throws IllegalAccessException {
Field[] fields = Request.Method.class.getDeclaredFields();
for (Field field : fields) {
if (methodCode == field.getInt(null)) {
return field.getName();
}
}
return null;
}
/**
* @return the url path that will be concatenated
*/
protected abstract String path();
/**
* @return response class of the action
*/
protected abstract Class<T> responseClass();
/**
* @return body of the action
*/
protected abstract String body();
/**
* @return headers, unless any authorization is needed
*/
protected abstract Map<String, String> getHeaders();
/**
* callback method for network responses
*/
protected void onSuccess(T response) {
// for rent
}
/**
* callback method for network errors
*/
protected void onError(VolleyError error) {
// for rent
}
/**
* @return listener back for network responses
*/
private Response.Listener<T> successListener() {
return new Response.Listener<T>() {
@Override
public void onResponse(T response) {
onSuccess(response);
}
};
}
/**
* @return listener back for error
*/
private Response.ErrorListener errorListener() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onError(error);
}
};
}
/**
* @return whole path of the URL
*/
private String requestUrl() {
return baseUrl() + path();
}
/**
* @return new built of Request class
*/
public Request<T> create() {
return new CoreGsonRequest<T>(
httpMethod(),
requestUrl(),
responseClass(),
getHeaders(),
successListener(),
errorListener(),
body()
);
}
}
|
package org.decimal4j.op.compare;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.decimal4j.api.Decimal;
import org.decimal4j.api.DecimalArithmetic;
import org.decimal4j.api.MutableDecimal;
import org.decimal4j.scale.ScaleMetrics;
import org.decimal4j.scale.Scales;
import org.decimal4j.test.AbstractDecimalTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Unit test for Decimal constants and constant setter methods of the
* {@link MutableDecimal}.
*/
@RunWith(Parameterized.class)
public class ConstantTest extends AbstractDecimalTest {
public ConstantTest(ScaleMetrics scaleMetrics, DecimalArithmetic arithmetic) {
super(arithmetic);
}
@Parameters(name = "{index}: scale={0}")
public static Iterable<Object[]> data() {
final List<Object[]> data = new ArrayList<Object[]>();
for (final ScaleMetrics s : Scales.VALUES) {
data.add(new Object[] { s, s.getDefaultArithmetic() });
}
return data;
}
@Test
public void testZero() {
assertUnscaled("should be zero", 0, immutableConstant("ZERO"));
assertUnscaled("should be zero", 0, immutableValueOf(long.class, 0L));
assertUnscaled("should be zero", 0, mutableConstant("zero"));
assertUnscaled("should be zero", 0, newMutable().setZero());
}
@Test
public void testOne() {
final long one = arithmetic.one();
assertUnscaled("should be one", one, immutableConstant("ONE"));
assertUnscaled("should be one", one, immutableValueOf(long.class, 1L));
assertUnscaled("should be one", one, mutableConstant("one"));
assertUnscaled("should be one", one, newMutable().setOne());
}
@Test
public void testTwo() {
final long two = 2*arithmetic.one();
assertUnscaled("should be two", two, immutableConstant("TWO"));
assertUnscaled("should be two", two, immutableValueOf(long.class, 2L));
assertUnscaled("should be two", two, mutableConstant("two"));
assertUnscaled("should be two", two, newMutable().set(2));
}
@Test
public void testThree() {
final long three = 3*arithmetic.one();
assertUnscaled("should be three", three, immutableConstant("THREE"));
assertUnscaled("should be three", three, immutableValueOf(long.class, 3L));
assertUnscaled("should be three", three, mutableConstant("three"));
assertUnscaled("should be three", three, newMutable().set(3));
}
@Test
public void testFour() {
final long four = 4*arithmetic.one();
assertUnscaled("should be four", four, immutableConstant("FOUR"));
assertUnscaled("should be four", four, immutableValueOf(long.class, 4L));
assertUnscaled("should be four", four, mutableConstant("four"));
assertUnscaled("should be four", four, newMutable().set(4));
}
@Test
public void testFive() {
final long five = 5*arithmetic.one();
assertUnscaled("should be five", five, immutableConstant("FIVE"));
assertUnscaled("should be five", five, immutableValueOf(long.class, 5L));
assertUnscaled("should be five", five, mutableConstant("five"));
assertUnscaled("should be five", five, newMutable().set(5));
}
@Test
public void testSix() {
final long six = 6*arithmetic.one();
assertUnscaled("should be six", six, immutableConstant("SIX"));
assertUnscaled("should be six", six, immutableValueOf(long.class, 6L));
assertUnscaled("should be six", six, mutableConstant("six"));
assertUnscaled("should be six", six, newMutable().set(6));
}
@Test
public void testSeven() {
final long seven = 7*arithmetic.one();
assertUnscaled("should be seven", seven, immutableConstant("SEVEN"));
assertUnscaled("should be seven", seven, immutableValueOf(long.class, 7L));
assertUnscaled("should be seven", seven, mutableConstant("seven"));
assertUnscaled("should be seven", seven, newMutable().set(7));
}
@Test
public void testEight() {
final long eight = 8*arithmetic.one();
assertUnscaled("should be eight", eight, immutableConstant("EIGHT"));
assertUnscaled("should be eight", eight, immutableValueOf(long.class, 8L));
assertUnscaled("should be eight", eight, mutableConstant("eight"));
assertUnscaled("should be eight", eight, newMutable().set(8));
}
@Test
public void testNine() {
final long nine = 9*arithmetic.one();
assertUnscaled("should be nine", nine, immutableConstant("NINE"));
assertUnscaled("should be nine", nine, immutableValueOf(long.class, 9L));
assertUnscaled("should be nine", nine, mutableConstant("nine"));
assertUnscaled("should be nine", nine, newMutable().set(9));
}
@Test
public void testUlp() {
assertUnscaled("should be 1", 1, immutableConstant("ULP"));
assertUnscaled("should be 1", 1, mutableConstant("ulp"));
assertUnscaled("should be 1", 1, newMutable().setUlp());
}
@Test
public void testMinusOne() {
final long minusOne = -arithmetic.one();
assertUnscaled("should be minus one", minusOne, immutableConstant("MINUS_ONE"));
assertUnscaled("should be minus one", minusOne, mutableConstant("minusOne"));
assertUnscaled("should be minus one", minusOne, newMutable().setMinusOne());
}
@Test
public void testTen() {
if (getScale() <= 17) {
final long ten = 10*arithmetic.one();
assertUnscaled("should be ten", ten, immutableConstant("TEN"));
assertUnscaled("should be ten", ten, mutableConstant("ten"));
}
}
@Test
public void testHundred() {
if (getScale() <= 16) {
final long ten = 100*arithmetic.one();
assertUnscaled("should be hundred", ten, immutableConstant("HUNDRED"));
assertUnscaled("should be hundred", ten, mutableConstant("hundred"));
}
}
@Test
public void testThousand() {
if (getScale() <= 15) {
final long ten = 1000*arithmetic.one();
assertUnscaled("should be thousand", ten, immutableConstant("THOUSAND"));
assertUnscaled("should be thousand", ten, mutableConstant("thousand"));
}
}
@Test
public void testMillion() {
if (getScale() <= 12) {
final long ten = 1000000*arithmetic.one();
assertUnscaled("should be million", ten, immutableConstant("MILLION"));
assertUnscaled("should be million", ten, mutableConstant("million"));
}
}
@Test
public void testBillion() {
if (getScale() <= 9) {
final long ten = 1000000000*arithmetic.one();
assertUnscaled("should be billion", ten, immutableConstant("BILLION"));
assertUnscaled("should be billion", ten, mutableConstant("billion"));
}
}
@Test
public void testTrillion() {
if (getScale() <= 6) {
final long ten = 1000000000000L*arithmetic.one();
assertUnscaled("should be trillion", ten, immutableConstant("TRILLION"));
assertUnscaled("should be trillion", ten, mutableConstant("trillion"));
}
}
@Test
public void testQuadrillion() {
if (getScale() <= 3) {
final long ten = 1000000000000000L*arithmetic.one();
assertUnscaled("should be quadrillion", ten, immutableConstant("QUADRILLION"));
assertUnscaled("should be quadrillion", ten, mutableConstant("quadrillion"));
}
}
@Test
public void testQuintillion() {
if (getScale() <= 0) {
final long ten = 1000000000000000000L*arithmetic.one();
assertUnscaled("should be quintillion", ten, immutableConstant("QUINTILLION"));
assertUnscaled("should be quintillion", ten, mutableConstant("quintillion"));
}
}
@Test
public void testHalf() {
if (getScale() > 0) {
final long half = arithmetic.one()/2;
assertUnscaled("should be half", half, immutableConstant("HALF"));
assertUnscaled("should be half", half, mutableConstant("half"));
}
}
@Test
public void testTenth() {
if (getScale() >= 1) {
final long tenth = arithmetic.one()/10;
assertUnscaled("should be tenth", tenth, immutableConstant("TENTH"));
assertUnscaled("should be tenth", tenth, mutableConstant("tenth"));
}
}
@Test
public void testHundredth() {
if (getScale() >= 2) {
final long hundredth = arithmetic.one()/100;
assertUnscaled("should be hundredth", hundredth, immutableConstant("HUNDREDTH"));
assertUnscaled("should be hundredth", hundredth, mutableConstant("hundredth"));
}
}
@Test
public void testThousandth() {
if (getScale() >= 3) {
final long thousanth = arithmetic.one()/1000;
assertUnscaled("should be thousanth", thousanth, immutableConstant("THOUSANDTH"));
assertUnscaled("should be thousanth", thousanth, mutableConstant("thousandth"));
}
}
@Test
public void testMillionth() {
if (getScale() >= 6) {
final long millionth = arithmetic.one()/1000000;
assertUnscaled("should be millionth", millionth, immutableConstant("MILLIONTH"));
assertUnscaled("should be millionth", millionth, mutableConstant("millionth"));
}
}
@Test
public void testBillionth() {
if (getScale() >= 9) {
final long billionth = arithmetic.one()/1000000000;
assertUnscaled("should be billionth", billionth, immutableConstant("BILLIONTH"));
assertUnscaled("should be billionth", billionth, mutableConstant("billionth"));
}
}
@Test
public void testTrillionth() {
if (getScale() >= 12) {
final long trillionth = arithmetic.one()/1000000000000L;
assertUnscaled("should be trillionth", trillionth, immutableConstant("TRILLIONTH"));
assertUnscaled("should be trillionth", trillionth, mutableConstant("trillionth"));
}
}
@Test
public void testQuadrillionth() {
if (getScale() >= 15) {
final long quadrillionth = arithmetic.one()/1000000000000000L;
assertUnscaled("should be quadrillionth", quadrillionth, immutableConstant("QUADRILLIONTH"));
assertUnscaled("should be quadrillionth", quadrillionth, mutableConstant("quadrillionth"));
}
}
@Test
public void testQuintillionth() {
if (getScale() >= 18) {
final long quintillionth = arithmetic.one()/1000000000000000000L;
assertUnscaled("should be quintillionth", quintillionth, immutableConstant("QUINTILLIONTH"));
assertUnscaled("should be quintillionth", quintillionth, mutableConstant("quintillionth"));
}
}
private void assertUnscaled(String msg, long unscaled, Decimal<?> value) {
assertEquals(msg, unscaled, value.unscaledValue());
}
private MutableDecimal<?> newMutable() {
return getDecimalFactory(getScaleMetrics()).newMutable().setUnscaled(RND.nextLong());
}
private Decimal<?> immutableConstant(String constantName) {
try {
final Class<?> clazz = Class.forName(getImmutableClassName());
return (Decimal<?>) clazz.getField(constantName).get(null);
} catch (Exception e) {
throw new RuntimeException("could not access static field '" + constantName + "', e=" + e, e);
}
}
private Decimal<?> mutableConstant(String methodName) {
try {
final Class<?> clazz = Class.forName(getMutableClassName());
return (Decimal<?>) clazz.getMethod(methodName).invoke(null);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException)e.getTargetException();
}
throw new RuntimeException("could not invoke static method '" + methodName + "', e=" + e, e);
} catch (Exception e) {
throw new RuntimeException("could not invoke static method '" + methodName + "', e=" + e, e);
}
}
private <V> Decimal<?> immutableValueOf(Class<V> paramType, V paramValue) {
try {
final Class<?> clazz = Class.forName(getImmutableClassName());
return (Decimal<?>) clazz.getMethod("valueOf", paramType).invoke(null, paramValue);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException)e.getTargetException();
}
throw new RuntimeException("could not invoke valueOf method, e=" + e, e);
} catch (Exception e) {
throw new RuntimeException("could not invoke valueOf method, e=" + e, e);
}
}
}
|
package io.mangoo.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.github.sommeri.less4j.Less4jException;
import com.github.sommeri.less4j.LessCompiler;
import com.github.sommeri.less4j.LessCompiler.CompilationResult;
import com.github.sommeri.less4j.core.DefaultLessCompiler;
import com.google.common.base.Charsets;
import io.bit3.jsass.CompilationException;
import io.bit3.jsass.Compiler;
import io.bit3.jsass.Options;
import io.bit3.jsass.Output;
import io.mangoo.configuration.Config;
import io.mangoo.enums.Default;
import io.mangoo.enums.Key;
import io.mangoo.enums.Mode;
import io.mangoo.enums.Suffix;
import net.jawr.web.minification.CSSMinifier;
import net.jawr.web.minification.JSMin;
import net.jawr.web.minification.JSMin.JSMinException;
/**
* Convenient class for minification of CSS and JS files
*
*
* @author svenkubiak
*
*/
@SuppressWarnings("all")
public final class MinificationUtils {
private static final Logger LOG = LogManager.getLogger(MinificationUtils.class);
private static final int HUNDRED_PERCENT = 100;
private static final String JS = "js";
private static final String CSS = "css";
private static final String LESS = "less";
private static final String SASS = "sass";
private static final String MIN = "min";
private static String basePath;
private static volatile Config config; //NOSONAR
private MinificationUtils() {
config = new Config(basePath + Default.CONFIG_PATH.toString(), Mode.DEV);
}
public static void setBasePath(String path) {
synchronized (MinificationUtils.class) {
basePath = path;
}
}
public static void setConfig(Config configuration) {
synchronized (Config.class) {
config = configuration;
}
}
/**
* Minifies a JS or CSS file to a corresponding JS or CSS file
*
* @param absolutePath The absolute path to the file
*/
public static void minify(String absolutePath) {
if (absolutePath == null || absolutePath.contains(MIN)) {
return;
}
if (config == null) {
System.setProperty(Key.APPLICATION_CONFIG.toString(), basePath + Default.CONFIG_PATH.toString());
config = new Config(basePath + Default.CONFIG_PATH.toString(), Mode.DEV);
}
if (config.isMinifyCSS() && absolutePath.endsWith(JS)) {
minifyJS(new File(absolutePath));
} else if (config.isMinifyJS() && absolutePath.endsWith(CSS)) {
minifyCSS(new File(absolutePath));
}
}
/**
* Compiles a LESS or SASS file to a corresponding CSS file
*
* @param absolutePath The absolute path to the file
*/
public static void preprocess(String absolutePath) {
if (absolutePath == null) {
return;
}
if (config == null) {
System.setProperty(Key.APPLICATION_CONFIG.toString(), basePath + Default.CONFIG_PATH.toString());
config = new Config(basePath + Default.CONFIG_PATH.toString(), Mode.DEV);
}
if (config.isPreprocessLess() && absolutePath.endsWith(LESS)) {
lessify(new File(absolutePath));
} else if (config.isPreprocessSass() && absolutePath.endsWith(SASS)) {
sassify(new File(absolutePath));
}
}
private static void lessify(File lessFile) {
LessCompiler compiler = new DefaultLessCompiler();
try {
File outputFile = getOutputFile(lessFile, Suffix.CSS);
CompilationResult compilationResult = compiler.compile(lessFile);
FileUtils.writeStringToFile(outputFile, compilationResult.getCss(), Default.ENCODING.toString());
logPreprocess(lessFile, outputFile);
} catch (Less4jException | IOException e) {
LOG.error("Failed to preprocess LESS file", e);
}
}
private static void sassify(File sassFile) {
File outputFile = getOutputFile(sassFile, Suffix.CSS);
URI inputURI = sassFile.toURI();
URI outputURI = outputFile.toURI();
Compiler compiler = new Compiler();
try {
Output output = compiler.compileFile(inputURI, outputURI, new Options());
FileUtils.writeStringToFile(outputFile, output.getCss(), Default.ENCODING.toString());
logPreprocess(sassFile, outputFile);
} catch (CompilationException | IOException e) {
LOG.error("Failed to preprocess SASS file", e);
}
}
private static void minifyJS(File inputFile) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File outputFile = getOutputFile(inputFile, Suffix.JS_MIN);
fileInputStream = new FileInputStream(inputFile);
fileOutputStream = new FileOutputStream(outputFile);
JSMin jsMin = new JSMin(fileInputStream, fileOutputStream);
jsMin.jsmin();
logMinification(inputFile, outputFile);
} catch (IOException | JSMinException e) {
LOG.error("Failed to minify JS", e);
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(fileOutputStream);
}
}
private static void logMinification(File inputFile, File outputFile) {
LOG.info(String.format("Minified asset %s (%db) -> %s (%db) [compressed to %d%% of original size]", inputFile.getName(), inputFile.length(), outputFile.getName(), outputFile.length(), ratioOfSize(inputFile, outputFile)));
}
private static void logPreprocess(File inputFile, File outputFile) {
LOG.info(String.format("Preprocessed asset %s -> %s", inputFile.getName(), outputFile.getName()));
}
private static void minifyCSS(File inputFile) {
try {
File outputFile = getOutputFile(inputFile, Suffix.CSS_MIN);
StringBuffer stringBuffer = new StringBuffer();
CSSMinifier cssMinifier = new CSSMinifier();
stringBuffer.append(FileUtils.readFileToString(inputFile, Default.ENCODING.toString()));
StringBuffer minifyCSS = cssMinifier.minifyCSS(stringBuffer);
FileUtils.write(outputFile, minifyCSS.toString(), Default.ENCODING.toString());
logMinification(inputFile, outputFile);
} catch (IOException e) {
LOG.error("Failed to minify CSS", e);
}
}
private static File getOutputFile(File inputfile, Suffix targetSuffix) {
String fileName = inputfile.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
fileName = fileName + targetSuffix.toString();
if (!basePath.endsWith("/")) {
basePath = basePath + "/";
}
String assetPath = config.getAssetsPath();
if (assetPath.startsWith("/")) {
assetPath = assetPath.substring(1);
}
if (!assetPath.endsWith("/")) {
assetPath = assetPath + "/";
}
String subpath = null;
if (Suffix.CSS.equals(targetSuffix) || Suffix.CSS_MIN.equals(targetSuffix)) {
subpath = Default.STYLESHEET_FOLDER.toString() + "/" + fileName;
} else if (Suffix.JS.equals(targetSuffix) || Suffix.JS_MIN.equals(targetSuffix)) {
subpath = Default.JAVASCRIPT_FOLDER.toString() + "/" + fileName;
}
return new File(basePath + assetPath + subpath);
}
private static long ratioOfSize(File inputFile, File outputFile) {
long inFile = Math.max(inputFile.length(), 1);
long outFile = Math.max(outputFile.length(), 1);
return (outFile * HUNDRED_PERCENT) / inFile;
}
}
|
package org.eann.sim.configuration;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.junit.Before;
import org.junit.Test;
public class ConfigTest {
private JAXBContext context;
@Before
public void setUp() throws Exception {
this.context = JAXBContext.newInstance(Config.class);
}
@Test
public void serialization() throws Exception {
Marshaller marshaller = this.context.createMarshaller();
Config config = new Config();
File file = new File("target/configuration.xml");
marshaller.marshal(config, file);
}
}
|
package info.nightscout.androidaps.plugins.ProfileNS;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.OKDialog;
import static butterknife.OnItemSelected.Callback.NOTHING_SELECTED;
public class NSProfileFragment extends SubscriberFragment {
@BindView(R.id.nsprofile_spinner)
Spinner profileSpinner;
@BindView(R.id.profileview_noprofile)
TextView noProfile;
@BindView(R.id.profileview_invalidprofile)
TextView invalidProfile;
@BindView(R.id.profileview_units)
TextView units;
@BindView(R.id.profileview_dia)
TextView dia;
@BindView(R.id.profileview_activeprofile)
TextView activeProfile;
@BindView(R.id.profileview_ic)
TextView ic;
@BindView(R.id.profileview_isf)
TextView isf;
@BindView(R.id.profileview_basal)
TextView basal;
@BindView(R.id.profileview_target)
TextView target;
@BindView(R.id.basal_graph)
ProfileGraph basalGraph;
@BindView(R.id.nsprofile_profileswitch)
Button activateButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.nsprofile_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
updateGUI();
return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
}
return null;
}
@Subscribe
public void onStatusEvent(final EventNSProfileUpdateGUI ev) {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(() -> updateGUI());
}
@Override
protected void updateGUI() {
ProfileStore profileStore = NSProfilePlugin.getPlugin().getProfile();
if (profileStore != null) {
ArrayList<CharSequence> profileList = profileStore.getProfileList();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, profileList);
profileSpinner.setAdapter(adapter);
// set selected to actual profile
for (int p = 0; p < profileList.size(); p++) {
if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName()))
profileSpinner.setSelection(p);
}
noProfile.setVisibility(View.GONE);
} else {
noProfile.setVisibility(View.VISIBLE);
}
}
@OnItemSelected(R.id.nsprofile_spinner)
public void onItemSelected(Spinner spinner, int position) {
String name = spinner.getItemAtPosition(position).toString();
ProfileStore store = NSProfilePlugin.getPlugin().getProfile();
if (store != null) {
Profile profile = store.getSpecificProfile(name);
if (profile != null) {
units.setText(profile.getUnits());
dia.setText(DecimalFormatter.to2Decimal(profile.getDia()) + " h");
activeProfile.setText(name);
ic.setText(profile.getIcList());
isf.setText(profile.getIsfList());
basal.setText(profile.getBasalList());
target.setText(profile.getTargetList());
basalGraph.show(profile);
}
if (profile.isValid("NSProfileFragment")) {
invalidProfile.setVisibility(View.GONE);
activateButton.setVisibility(View.VISIBLE);
} else {
invalidProfile.setVisibility(View.VISIBLE);
activateButton.setVisibility(View.GONE);
}
} else {
activateButton.setVisibility(View.GONE);
}
}
@OnItemSelected(value = R.id.nsprofile_spinner, callback = NOTHING_SELECTED)
public void onNothingSelected() {
invalidProfile.setVisibility(View.VISIBLE);
noProfile.setVisibility(View.VISIBLE);
units.setText("");
dia.setText("");
activeProfile.setText("");
ic.setText("");
isf.setText("");
basal.setText("");
target.setText("");
activateButton.setVisibility(View.GONE);
}
@OnClick(R.id.nsprofile_profileswitch)
public void onClickProfileSwitch() {
String name = profileSpinner.getSelectedItem() != null ? profileSpinner.getSelectedItem().toString() : "";
ProfileStore store = NSProfilePlugin.getPlugin().getProfile();
if (store != null) {
Profile profile = store.getSpecificProfile(name);
if (profile != null) {
OKDialog.showConfirmation(getActivity(), MainApp.gs(R.string.activate_profile) + ": " + name + " ?", () ->
NewNSTreatmentDialog.doProfileSwitch(store, name, 0, 100, 0)
);
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package JavaLineArray;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import java.awt.geom.Rectangle2D;
/**
* A class which imported many of the C++ functions from Trident
* Systems Dismounted Intelligence Situational Awareness System (DISM) for
* rendering Mil-Standard-2525 tactical lines. This class does not get instantiated
* Much of the code is still the original DISM code.
* @author Michael Deutch
*/
public final class DISMSupport
{
private static final int LEFT_SIDE=0;
private static final int RIGHT_SIDE=1;
private static final int COLINEAR=2;
private static final double CONST_PI = Math.PI;
private static final double maxLength=100;
private static final double minLength=2.5;
private static final String _className="DISMSupport";
// protected static void setMinLength(double mLength)
// minLength=mLength;
private static double GetTGFontSize(double iLength)
{
double result=-1;
try
{
if (iLength < 20)
result = 0;
else if (iLength < 50)
result = 1;
else if (iLength > 250)
result = 3;
else
result = 2;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className ,"GetTGFontSize",
new RendererException("Failed inside GetTGFontSize", exc));
}
return result;
}
private static void ArcApproximationDouble(double left, double top, double right, double bottom,
double startx, double starty, double endx, double endy, POINT2[] lpoints)
{
try
{
double dstartx = startx;
double dstarty = starty;
double dendx = endx;
double dendy = endy;
double a = 0;
double b = 0;
double ctrX = 0;
double ctrY = 0;
double x1, y1, x2, y2;
double startAngle, endAngle;
double angleIncrement = 0;
double t=0;
int i = 0;
if (left > right)
{
double temp = left;
left = right;
right = temp;
}
if (top > bottom)
{
double temp = top;
top = bottom;
bottom = temp;
}
a = (right - left) / 2.0;
b = (bottom - top) / 2.0;
ctrX = left + a;
ctrY = top + b;
x1 = dstartx - ctrX;
x2 = dendx - ctrX;
y1 = ctrY - dstarty;
y2 = ctrY - dendy;
if (y1 == 0)
{
if (x1 > 0) startAngle = 0;
else startAngle = CONST_PI;
}
else if (x1 == 0)
{
if (y1 > 0) startAngle = CONST_PI * 0.5;
else startAngle = CONST_PI * -0.5;
}
else startAngle = Math.atan2(y1, x1);
if (y2 == 0)
{
if (x2 > 0) endAngle = 0;
else endAngle = CONST_PI;
}
else if (x2 == 0)
{
if (y2 > 0) endAngle = CONST_PI * 0.5;
else endAngle = CONST_PI * -0.5;
}
else endAngle = Math.atan2(y2, x2);
if (endAngle <= startAngle) endAngle += 2 * CONST_PI;
angleIncrement = (endAngle - startAngle) / 16.0;
for (t = startAngle; i < 17; t += angleIncrement, i++)
{
lpoints[i].x = ctrX + a * Math.cos(t);
lpoints[i].y = ctrY - b * Math.sin(t);
}
return;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className ,"ArcApproximationDouble",
new RendererException("Failed inside ArcApproximationDouble", exc));
}
}
private static void DrawOpenRectangleDouble(POINT2[] points, POINT2[] pointsCorner, POINT2[] resultpts) {
try {
// draw open-ended rectangle
POINT2 point_mid = new POINT2();
int j = 0;
// POINT1 pts[4];
point_mid.x = (points[0].x + points[1].x) / 2;
point_mid.y = (points[0].y + points[1].y) / 2;
pointsCorner[0].x = points[0].x - point_mid.x + points[2].x;
pointsCorner[0].y = points[0].y - point_mid.y + points[2].y;
pointsCorner[1].x = points[1].x - point_mid.x + points[2].x;
pointsCorner[1].y = points[1].y - point_mid.y + points[2].y;
resultpts[0] = new POINT2(points[1]);
resultpts[1] = new POINT2(pointsCorner[1]);
resultpts[2] = new POINT2(pointsCorner[0]);
resultpts[3] = new POINT2(points[0]);
for (j = 0; j < 4; j++) {
resultpts[j].style = 0;
}
resultpts[3].style = 5;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"DrawOpenRectangleDouble",
new RendererException("Failed inside DrawOpenRectangleDouble", exc));
}
return;
}
private static int DetermineDirectionDouble(POINT2[] points) {
int result=0;
try {
double dP0P1M = 0;
double iP0P1B = 0;
if (points[0].x == points[1].x) {
//return (points[2].x < points[0].x);
if (points[2].x < points[0].x) {
return 1;
} else {
return 0;
}
} else {
// dP0P1M = slope of line between Point0 and Point1
dP0P1M = (double) (points[0].y - points[1].y) / (double) (points[0].x - points[1].x);
// iP0P1B = b component of y=mx+b equation of line
iP0P1B = (points[0].y - dP0P1M * points[0].x);
if (((points[2].y - iP0P1B) / dP0P1M) > points[2].x) {
return 1;
} else {
return 0;
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"DetermineDirectionDouble",
new RendererException("Failed inside DetermineDirectionDouble", exc));
}
return result;
}
private static void CalcEndpieceDeltasDouble(POINT2[] points, ref
<double[]> piDeltaX, ref <double[]> piDeltaY,
double dAngleDelta
)
{
try {
// find midpoint between point0 and point1
POINT2 pntMid = new POINT2();
double iDiagEOL_length = 0;
double dAngle1 = 0;
pntMid.x = (points[0].x + points[1].x) / 2;
pntMid.y = (points[0].y + points[1].y) / 2;
// iDiagEOL_length = length of the diagonal on end of line from line out to endpoint
iDiagEOL_length = ((Math.sqrt // height of graphic
(
(points[1].x - points[0].x) * (points[1].x - points[0].x) +
(points[1].y - points[0].y) * (points[1].y - points[0].y)) +
Math.sqrt // length of graphic
(
(points[2].x - pntMid.x) * (points[2].x - pntMid.x) +
(points[2].y - pntMid.y) * (points[2].y - pntMid.y))) / 20);
if ((double) iDiagEOL_length > maxLength/5) {
iDiagEOL_length = maxLength/5;
}
if ((double) iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
// dAngle1 = angle used to calculate the end-piece deltas
dAngle1 = Math.atan2(points[2].y - pntMid.y, points[2].x - pntMid.x) + dAngleDelta;
// dAngle1 = atan2(points[2].y - pntMid.y, points[2].x - pntMid.x) + dAngleDelta;
piDeltaX.value=new double[1];
piDeltaY.value=new double[1];
piDeltaX.value[0] = (iDiagEOL_length * Math.cos(dAngle1));
piDeltaY.value[0] = (iDiagEOL_length * Math.sin(dAngle1));
return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"CalcEndpieceDeltasDouble",
new RendererException("Failed inside CalcEndpieceDeltasDouble", exc));
}
}
/**
* Calculates the points for DELAY, WITHDRAW, WDRAWUP, RETIRE
*
* @param points OUT - the client points, also used for the returned points.
*/
protected static int GetDelayGraphicEtcDouble(POINT2[] points) {
int counter=0;
try {
POINT2[] pts = new POINT2[2];
POINT2[] savepoints = new POINT2[3];
double iLength = 0;
double iRadius = 0;
double iDiagEOL_length = 0;
double dAngle1 = 0;
double iDeltaX1 = 0;
double iDeltaY1 = 0;
double iDeltaX2 = 0;
double iDeltaY2 = 0;
POINT2 ptArcCenter = new POINT2();
POINT2[] arcpoints = new POINT2[17];
POINT2[] deltapoints = new POINT2[4];
int j = 0;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(arcpoints);
lineutility.InitializePOINT2Array(deltapoints);
points[counter] = new POINT2(savepoints[0]);
points[counter].style = 14;
counter++;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 5;
counter++;
iLength = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
iRadius = Math.sqrt((savepoints[2].x - savepoints[1].x) * (savepoints[2].x - savepoints[1].x) +
(savepoints[2].y - savepoints[1].y) * (savepoints[2].y - savepoints[1].y)) / 2;
iDiagEOL_length = (iLength + iRadius * 2) / 20;
if ((double) iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if ((double) iDiagEOL_length < minLength) { //was minLength
iDiagEOL_length = minLength;
}
dAngle1 = Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);
iDeltaX1 = (iDiagEOL_length * Math.cos(dAngle1 - CONST_PI / 4));
iDeltaY1 = (iDiagEOL_length * Math.sin(dAngle1 - CONST_PI / 4));
iDeltaX2 = (iDiagEOL_length * Math.cos(dAngle1 + CONST_PI / 4));
iDeltaY2 = (iDiagEOL_length * Math.sin(dAngle1 + CONST_PI / 4));
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints[j]);
counter++;
}
// draw the semicircle
ptArcCenter.x = (savepoints[1].x + savepoints[2].x) / 2;
ptArcCenter.y = (savepoints[1].y + savepoints[2].y) / 2;
boolean reverseArc = ReverseDelayArc(savepoints);
if (reverseArc == false) {
ArcApproximationDouble( (ptArcCenter.x - iRadius), (ptArcCenter.y - iRadius),
(ptArcCenter.x + iRadius), (ptArcCenter.y + iRadius),
savepoints[1].x, savepoints[1].y, savepoints[2].x, savepoints[2].y, arcpoints);
} else {
ArcApproximationDouble((ptArcCenter.x - iRadius), (ptArcCenter.y - iRadius),
(ptArcCenter.x + iRadius), (ptArcCenter.y + iRadius),
savepoints[2].x, savepoints[2].y, savepoints[1].x, savepoints[1].y, arcpoints);
}
for (j = 0; j < 17; j++) {
points[counter] = new POINT2(arcpoints[j]);
points[counter].style = 0;
counter++;
}
//clean up
pts = null;
savepoints = null;
arcpoints = null;
deltapoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDelayGraphicEtcDouble",
new RendererException("Failed inside GetDelayGraphicEtcDouble", exc));
}
return counter;
}
/**
* Calculates the points for SCREEN, COVER, GUARD, SARA.
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMCoverDouble(POINT2[] points,
int linetype) {
int counter = 0;
try {
// switch points[1] and points[2] if they are backwards
double dAngle0, dDeltaX0, dDeltaY0, dDeltaX1, dDeltaY1;
double iLengthPt0Pt1 = 0;
double iLengthPt0Pt2 = 0;
double iDelta = 0;
int j=0;
int t=1;
double iFontSize = 0;
double iLetterOffset = 0;
POINT2[] savepoints = new POINT2[3];
POINT2[] pts = new POINT2[2];
POINT2[] ptsJaggyLine = new POINT2[4];
//float scale = 1;
boolean goLeftThenRight=false;
int sign=1;
//added section for jaggy line orientation M. Deutch 6-24-11
POINT2 pt0=new POINT2(points[0]);
POINT2 pt1=new POINT2(points[1]);
POINT2 pt2=new POINT2(points[2]);
POINT2 pt3=new POINT2();
POINT2 pt4=new POINT2();
lineutility.LineRelativeToLine(pt1, pt2, pt0, pt3, pt4);
//now we have the pt3-pt4 line which pt0 is on
//get the corresponding point back on the original line
lineutility.LineRelativeToLine(pt3, pt0, pt1, pt2, pt4);
int quadrant=lineutility.GetQuadrantDouble(pt0, pt4);
pt1=new POINT2(points[1]);
pt2=new POINT2(points[2]);
if(pt1.x<pt2.x && quadrant==1)
sign=-1;
else if(pt1.x > pt2.x && quadrant == 2)
sign=-1;
else if(pt1.x > pt2.x && quadrant == 3)
sign=-1;
else if(pt1.x < pt2.x && quadrant == 4)
sign=-1;
//end section
//System.out.print(Integer.toString(quadrant));
//System.out.print("\n");
if(linetype==TacticalLines.SARA)
t=0;
if(points[1].x<=points[2].x)
goLeftThenRight=true;
//save the points in the correct order
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
savepoints[j].style = 0;
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(ptsJaggyLine);
iLengthPt0Pt1 = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
iLengthPt0Pt2 = Math.sqrt((savepoints[2].x - savepoints[0].x) * (savepoints[2].x - savepoints[0].x) +
(savepoints[2].y - savepoints[0].y) * (savepoints[2].y - savepoints[0].y));
if (iLengthPt0Pt1 > iLengthPt0Pt2) {
iLengthPt0Pt1 = iLengthPt0Pt2;
}
iFontSize = GetTGFontSize(iLengthPt0Pt1);
if (iFontSize > 0) {
iDelta = iLengthPt0Pt1 / 15;//was 15
//M. Deutch 8-18-04
if (iDelta > maxLength) {
iDelta = maxLength;
}
if (iDelta < minLength) {
iDelta = minLength;
}
// left side: draw letter in from the jaggy line
if(goLeftThenRight)
savepoints[0].x-=30*t; //was 20
else
savepoints[0].x+=30*t; //was 20
iLetterOffset = 0;
ptsJaggyLine[0].x = savepoints[0].x - iLetterOffset * 2;//was -
ptsJaggyLine[0].y = savepoints[0].y;
ptsJaggyLine[0].x -= iLetterOffset;
dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[1].y, ptsJaggyLine[0].x - savepoints[1].x);
pts[0].x = (ptsJaggyLine[0].x + savepoints[1].x) / 2;
pts[0].y = (ptsJaggyLine[0].y + savepoints[1].y) / 2;
dDeltaX0 = Math.cos(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
dDeltaY0 = Math.sin(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
ptsJaggyLine[1].x = pts[0].x - dDeltaX0; //was -
ptsJaggyLine[1].y = pts[0].y - dDeltaY0; //was -
ptsJaggyLine[2].x = pts[0].x + dDeltaX0; //was +
ptsJaggyLine[2].y = pts[0].y + dDeltaY0; //was +
ptsJaggyLine[3] = new POINT2(savepoints[1]);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
counter++;
}
points[counter - 1].style = 5;
// draw arrow at end of line
dDeltaX1 = Math.cos(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
dDeltaY1 = Math.sin(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
ptsJaggyLine[0].x = savepoints[1].x + dDeltaX0; //was +
ptsJaggyLine[0].y = savepoints[1].y + dDeltaY0; //was +
ptsJaggyLine[1] = new POINT2(savepoints[1]);
ptsJaggyLine[2].x = savepoints[1].x + dDeltaX1; //was +
ptsJaggyLine[2].y = savepoints[1].y + dDeltaY1; //was +
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
points[counter].style = 0;
if(linetype==TacticalLines.SARA)
{
points[counter].style = 9;
}
counter++;
}
points[counter - 1].style = 5;
if(linetype==TacticalLines.SARA)
{
points[counter-1].style = 9;
points[counter]=new POINT2(points[counter-3]);
points[counter].style=10;
counter++;
}
// right side: draw letter and jaggy line
if(goLeftThenRight)
savepoints[0].x+=60*t; //was 40
else
savepoints[0].x-=60*t; //wass 40
ptsJaggyLine[0].x = savepoints[0].x + iLetterOffset * 2;
ptsJaggyLine[0].y = savepoints[0].y;
ptsJaggyLine[0].x += iLetterOffset;
dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[2].y, ptsJaggyLine[0].x - savepoints[2].x);
pts[0].x = (ptsJaggyLine[0].x + savepoints[2].x) / 2;
pts[0].y = (ptsJaggyLine[0].y + savepoints[2].y) / 2;
dDeltaX0 = Math.cos(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
dDeltaY0 = Math.sin(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
ptsJaggyLine[1].x = pts[0].x - dDeltaX0; //was -
ptsJaggyLine[1].y = pts[0].y - dDeltaY0; //was -
ptsJaggyLine[2].x = pts[0].x + dDeltaX0; //was +
ptsJaggyLine[2].y = pts[0].y + dDeltaY0; //was +
ptsJaggyLine[3] = new POINT2(savepoints[2]);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
counter++;
}
points[counter - 1].style = 5;
// draw arrow at end of line
dDeltaX1 = Math.cos(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
dDeltaY1 = Math.sin(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
ptsJaggyLine[0].x = savepoints[2].x + dDeltaX0;
ptsJaggyLine[0].y = savepoints[2].y + dDeltaY0;
ptsJaggyLine[1] = savepoints[2];
ptsJaggyLine[2].x = savepoints[2].x + dDeltaX1;
ptsJaggyLine[2].y = savepoints[2].y + dDeltaY1;
// DrawLine(destination, mask, color, ptsJaggyLine, 3, iLineThickness);
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
points[counter].style = 0;
if(linetype==TacticalLines.SARA)
points[counter].style = 9;
counter++;
}
points[counter - 1].style = 5;
if(linetype==TacticalLines.SARA)
{
points[counter-1].style = 9;
points[counter]=new POINT2(points[counter-3]);
points[counter].style=10;
counter++;
}
}
else {
points[0] = new POINT2(savepoints[0]);
points[0].style = 0;
points[1] = new POINT2(savepoints[1]);
points[1].style = 5;
points[2] = new POINT2(savepoints[0]);
points[2].style = 0;
points[3] = new POINT2(savepoints[2]);
//for (j = 3; j < vblCounter; j++) {
// points[j].style = 5;
return 4;
}
savepoints = null;
pts = null;
ptsJaggyLine = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMcoverDouble",
new RendererException("Failed inside GetDISMCoverDouble", exc));
}
return counter;
}
/**
* rev C uses 4
* @param points
* @param linetype
* @return
*/
protected static int GetDISMCoverDoubleRevC(POINT2[] points,
int linetype,
int vblSaveCounter)
{
int counter = 0;
try
{
// switch points[1] and points[2] if they are backwards
double dAngle0=0, dDeltaX0=0, dDeltaY0=0, dDeltaX1=0, dDeltaY1=0;
double iLengthPt0Pt1 = 0;
double iLengthPt0Pt2 = 0;
double iDelta = 0;
int j=0;
int t=1;
double iFontSize = 0;
double iLetterOffset = 0;
POINT2[] savepoints = new POINT2[3];
POINT2[] pts = new POINT2[2];
POINT2[] ptsJaggyLine = new POINT2[4];
//float scale = 1;
boolean goLeftThenRight=false;
int sign=1;
//rev C with 4 points
POINT2[]origPoints=null;
if(vblSaveCounter==4)
{
origPoints=new POINT2[4];
for(j=0;j<vblSaveCounter;j++)
origPoints[j]=new POINT2(points[j]);
//reorder points
points[1]=origPoints[0];
points[2]=origPoints[3];
points[0].x=(origPoints[1].x+origPoints[2].x)/2;
points[0].y=(origPoints[1].y+origPoints[2].y)/2;
}
//added section for jaggy line orientation M. Deutch 6-24-11
POINT2 pt0=new POINT2(points[0]);
POINT2 pt1=new POINT2(points[1]);
POINT2 pt2=new POINT2(points[2]);
POINT2 pt3=new POINT2();
POINT2 pt4=new POINT2();
lineutility.LineRelativeToLine(pt1, pt2, pt0, pt3, pt4);
//now we have the pt3-pt4 line which pt0 is on
//get the corresponding point back on the original line
lineutility.LineRelativeToLine(pt3, pt0, pt1, pt2, pt4);
int quadrant=lineutility.GetQuadrantDouble(pt0, pt4);
pt1=new POINT2(points[1]);
pt2=new POINT2(points[2]);
if(pt1.x<pt2.x && quadrant==1)
sign=-1;
else if(pt1.x > pt2.x && quadrant == 2)
sign=-1;
else if(pt1.x > pt2.x && quadrant == 3)
sign=-1;
else if(pt1.x < pt2.x && quadrant == 4)
sign=-1;
//end section
//System.out.print(Integer.toString(quadrant));
//System.out.print("\n");
if(linetype==TacticalLines.SARA)
t=0;
if(points[1].x<=points[2].x)
goLeftThenRight=true;
//save the points in the correct order
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
savepoints[j].style = 0;
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(ptsJaggyLine);
iLengthPt0Pt1 = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
iLengthPt0Pt2 = Math.sqrt((savepoints[2].x - savepoints[0].x) * (savepoints[2].x - savepoints[0].x) +
(savepoints[2].y - savepoints[0].y) * (savepoints[2].y - savepoints[0].y));
if (iLengthPt0Pt1 > iLengthPt0Pt2) {
iLengthPt0Pt1 = iLengthPt0Pt2;
}
iFontSize = GetTGFontSize(iLengthPt0Pt1);
if (iFontSize > 0)
{
iDelta = iLengthPt0Pt1 / 15;//was 15
//M. Deutch 8-18-04
if (iDelta > maxLength) {
iDelta = maxLength;
}
if (iDelta < minLength) {
iDelta = minLength;
}
// left side: draw letter in from the jaggy line
if(vblSaveCounter<4)//rev b
{
if(goLeftThenRight)
savepoints[0].x-=30*t; //was 20
else
savepoints[0].x+=30*t; //was 20
iLetterOffset = 0;
ptsJaggyLine[0].x = savepoints[0].x - iLetterOffset * 2;//was -
ptsJaggyLine[0].y = savepoints[0].y;
ptsJaggyLine[0].x -= iLetterOffset;
dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[1].y, ptsJaggyLine[0].x - savepoints[1].x);
pts[0].x = (ptsJaggyLine[0].x + savepoints[1].x) / 2;
pts[0].y = (ptsJaggyLine[0].y + savepoints[1].y) / 2;
dDeltaX0 = Math.cos(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
dDeltaY0 = Math.sin(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
ptsJaggyLine[1].x = pts[0].x - dDeltaX0; //was -
ptsJaggyLine[1].y = pts[0].y - dDeltaY0; //was -
ptsJaggyLine[2].x = pts[0].x + dDeltaX0; //was +
ptsJaggyLine[2].y = pts[0].y + dDeltaY0; //was +
ptsJaggyLine[3] = new POINT2(savepoints[1]);
for (j = 0; j < 4; j++)
{
points[counter] = new POINT2(ptsJaggyLine[j]);
counter++;
}
points[counter - 1].style = 5;
}//end rev b
else //rev c
{
//iLetterOffset = 0;
//ptsJaggyLine[0].x = savepoints[0].x - iLetterOffset * 2;//was -
//ptsJaggyLine[0].y = savepoints[0].y;
//ptsJaggyLine[0].x -= iLetterOffset;
ptsJaggyLine[0]=new POINT2(origPoints[1]);
//dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[1].y, ptsJaggyLine[0].x - savepoints[1].x);
dAngle0 = Math.atan2(ptsJaggyLine[0].y - origPoints[0].y, ptsJaggyLine[0].x - origPoints[0].x);
//pts[0].x = (ptsJaggyLine[0].x + savepoints[1].x) / 2;
//pts[0].y = (ptsJaggyLine[0].y + savepoints[1].y) / 2;
pts[0].x = (ptsJaggyLine[0].x + origPoints[0].x) / 2;
pts[0].y = (ptsJaggyLine[0].y + origPoints[0].y) / 2;
dDeltaX0 = Math.cos(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
dDeltaY0 = Math.sin(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
ptsJaggyLine[1].x = pts[0].x - dDeltaX0; //was -
ptsJaggyLine[1].y = pts[0].y - dDeltaY0; //was -
ptsJaggyLine[2].x = pts[0].x + dDeltaX0; //was +
ptsJaggyLine[2].y = pts[0].y + dDeltaY0; //was +
//ptsJaggyLine[3] = new POINT2(savepoints[1]);
ptsJaggyLine[3] = new POINT2(origPoints[0]);
for (j = 0; j < 4; j++)
{
points[counter] = new POINT2(ptsJaggyLine[j]);
counter++;
}
points[counter - 1].style = 5;
}//end rev c
// draw arrow at end of line
dDeltaX1 = Math.cos(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
dDeltaY1 = Math.sin(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
//ptsJaggyLine[0].x = savepoints[1].x + dDeltaX0; //was +
//ptsJaggyLine[0].y = savepoints[1].y + dDeltaY0; //was +
if(vblSaveCounter<4)
{
ptsJaggyLine[0].x = savepoints[1].x + dDeltaX0; //was +
ptsJaggyLine[0].y = savepoints[1].y + dDeltaY0; //was +
}
else
{
ptsJaggyLine[0].x = origPoints[0].x + dDeltaX0; //was +
ptsJaggyLine[0].y = origPoints[0].y + dDeltaY0; //was +
}
//ptsJaggyLine[1] = new POINT2(savepoints[1]);
if(vblSaveCounter<4)
ptsJaggyLine[1] = new POINT2(savepoints[1]);
else
ptsJaggyLine[1] = new POINT2(origPoints[0]);
//ptsJaggyLine[2].x = savepoints[1].x + dDeltaX1; //was +
//ptsJaggyLine[2].y = savepoints[1].y + dDeltaY1; //was +
if(vblSaveCounter<4)
{
ptsJaggyLine[2].x = savepoints[1].x + dDeltaX1; //was +
ptsJaggyLine[2].y = savepoints[1].y + dDeltaY1; //was +
}
else
{
ptsJaggyLine[2].x = origPoints[0].x + dDeltaX1; //was +
ptsJaggyLine[2].y = origPoints[0].y + dDeltaY1; //was +
}
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
points[counter].style = 0;
if(linetype==TacticalLines.SARA)
{
points[counter].style = 9;
}
counter++;
}
points[counter - 1].style = 5;
if(linetype==TacticalLines.SARA)
{
points[counter-1].style = 9;
points[counter]=new POINT2(points[counter-3]);
points[counter].style=10;
counter++;
}
// right side: draw letter and jaggy line
if(vblSaveCounter<4) //rev b
{
if(goLeftThenRight)
savepoints[0].x+=60*t; //was 40
else
savepoints[0].x-=60*t; //wass 40
ptsJaggyLine[0].x = savepoints[0].x + iLetterOffset * 2;
ptsJaggyLine[0].y = savepoints[0].y;
ptsJaggyLine[0].x += iLetterOffset;
dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[2].y, ptsJaggyLine[0].x - savepoints[2].x);
pts[0].x = (ptsJaggyLine[0].x + savepoints[2].x) / 2;
pts[0].y = (ptsJaggyLine[0].y + savepoints[2].y) / 2;
dDeltaX0 = Math.cos(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
dDeltaY0 = Math.sin(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
ptsJaggyLine[1].x = pts[0].x - dDeltaX0; //was -
ptsJaggyLine[1].y = pts[0].y - dDeltaY0; //was -
ptsJaggyLine[2].x = pts[0].x + dDeltaX0; //was +
ptsJaggyLine[2].y = pts[0].y + dDeltaY0; //was +
ptsJaggyLine[3] = new POINT2(savepoints[2]);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
counter++;
}
points[counter - 1].style = 5;
// draw arrow at end of line
dDeltaX1 = Math.cos(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
dDeltaY1 = Math.sin(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
ptsJaggyLine[0].x = savepoints[2].x + dDeltaX0;
ptsJaggyLine[0].y = savepoints[2].y + dDeltaY0;
ptsJaggyLine[1] = savepoints[2];
ptsJaggyLine[2].x = savepoints[2].x + dDeltaX1;
ptsJaggyLine[2].y = savepoints[2].y + dDeltaY1;
}//end rev b
else //rev c
{
//if(goLeftThenRight)
// savepoints[0].x+=60*t; //was 40
//else
// savepoints[0].x-=60*t; //wass 40
//ptsJaggyLine[0].x = savepoints[0].x + iLetterOffset * 2;
//ptsJaggyLine[0].y = savepoints[0].y;
//ptsJaggyLine[0].x += iLetterOffset;
ptsJaggyLine[0]=new POINT2(origPoints[2]);
//dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[2].y, ptsJaggyLine[0].x - savepoints[2].x);
dAngle0 = Math.atan2(ptsJaggyLine[0].y - origPoints[3].y, ptsJaggyLine[0].x - origPoints[3].x);
//pts[0].x = (ptsJaggyLine[0].x + savepoints[2].x) / 2;
//pts[0].y = (ptsJaggyLine[0].y + savepoints[2].y) / 2;
pts[0].x = (ptsJaggyLine[0].x + origPoints[3].x) / 2;
pts[0].y = (ptsJaggyLine[0].y + origPoints[3].y) / 2;
dDeltaX0 = Math.cos(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
dDeltaY0 = Math.sin(dAngle0 - sign*CONST_PI / 4) * iDelta; //was -
ptsJaggyLine[1].x = pts[0].x - dDeltaX0; //was -
ptsJaggyLine[1].y = pts[0].y - dDeltaY0; //was -
ptsJaggyLine[2].x = pts[0].x + dDeltaX0; //was +
ptsJaggyLine[2].y = pts[0].y + dDeltaY0; //was +
//ptsJaggyLine[3] = new POINT2(savepoints[2]);
ptsJaggyLine[3] = new POINT2(origPoints[3]);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(ptsJaggyLine[j]);
counter++;
}
points[counter - 1].style = 5;
// draw arrow at end of line
dDeltaX1 = Math.cos(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
dDeltaY1 = Math.sin(dAngle0 + sign*CONST_PI / 4) * iDelta; //was +
//ptsJaggyLine[0].x = savepoints[2].x + dDeltaX0;
//ptsJaggyLine[0].y = savepoints[2].y + dDeltaY0;
//ptsJaggyLine[1] = savepoints[2];
//ptsJaggyLine[2].x = savepoints[2].x + dDeltaX1;
//ptsJaggyLine[2].y = savepoints[2].y + dDeltaY1;
ptsJaggyLine[0].x = origPoints[3].x + dDeltaX0;
ptsJaggyLine[0].y = origPoints[3].y + dDeltaY0;
ptsJaggyLine[1] = new POINT2(origPoints[3]);
ptsJaggyLine[2].x = origPoints[3].x + dDeltaX1;
ptsJaggyLine[2].y = origPoints[3].y + dDeltaY1;
}//end rev c
for (j = 0; j < 3; j++)
{
points[counter] = new POINT2(ptsJaggyLine[j]);
points[counter].style = 0;
if(linetype==TacticalLines.SARA)
points[counter].style = 9;
counter++;
}
points[counter - 1].style = 5;
if(linetype==TacticalLines.SARA)
{
points[counter-1].style = 9;
points[counter]=new POINT2(points[counter-3]);
points[counter].style=10;
counter++;
}
}
else
{
points[0] = new POINT2(savepoints[0]);
points[0].style = 0;
points[1] = new POINT2(savepoints[1]);
points[1].style = 5;
points[2] = new POINT2(savepoints[0]);
points[2].style = 0;
points[3] = new POINT2(savepoints[2]);
return 4;
}
savepoints = null;
pts = null;
ptsJaggyLine = null;
}
catch (Exception exc)
{
ErrorLogger.LogException(_className ,"GetDISMcoverDoubleRevC",
new RendererException("Failed inside GetDISMCoverDoubleRevc", exc));
}
return counter;
}
/**
* Calculates the points for BYPASS
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMBypassDouble(POINT2[] points,
int linetype) {
int counter = 0;
try {
int j = 0;
POINT2[] pointsCorner = new POINT2[2];
POINT2[] rectpts = new POINT2[4];
POINT2[] savepoints = new POINT2[3];
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
ref<double[]> iDeltaX = new ref(), iDeltaY = new ref();
int bPointsRight = 0;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pointsCorner);
lineutility.InitializePOINT2Array(rectpts);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
DrawOpenRectangleDouble(savepoints, pointsCorner, rectpts);
for (j = 0; j < 4; j++) {
points[counter] = rectpts[j];
counter++;
}
bPointsRight = DetermineDirectionDouble(savepoints);
CalcEndpieceDeltasDouble(savepoints, iDeltaX, iDeltaY, CONST_PI / 4);
if ((savepoints[0].y - savepoints[1].y) < 0) {// Point0 is higher than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
}
} else {// Point0 is lower than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
}
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints1[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints2[j]);
counter++;
}
//clean up
pointsCorner = null;
rectpts = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMBypassDouble",
new RendererException("Failed inside GetDISMBypassDouble", exc));
}
return counter;
}
/**
* Calculates the points for BREACH.
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMBreachDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
POINT2[] pointsCorner = new POINT2[2];
POINT2[] rectpts = new POINT2[4];
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
ref<double[]> iDeltaX = new ref(), iDeltaY = new ref();
int bPointsRight = 0, j = 0;
POINT2[] savepoints = new POINT2[3];
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pointsCorner);
lineutility.InitializePOINT2Array(rectpts);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
DrawOpenRectangleDouble(savepoints, pointsCorner, rectpts);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(rectpts[j]);
counter++;
}
bPointsRight = DetermineDirectionDouble(savepoints);
CalcEndpieceDeltasDouble(savepoints, iDeltaX, iDeltaY, CONST_PI / 4);
if ((savepoints[0].y - savepoints[1].y) < 0) {// Point0 is higher than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints2);
}
} else {// Point0 is lower than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints2);
}
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints1[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints2[j]);
counter++;
}
//clean up
pointsCorner = null;
rectpts = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMBreachDouble",
new RendererException("Failed inside GetDISMBreachDouble", exc));
}
return counter;
}
/**
* Calculates the points for CANALIZE
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMCanalizeDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
POINT2[] pointsCorner = new POINT2[2];
POINT2[] rectpts = new POINT2[4];
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
int j = 0;
ref<double[]> iDeltaX = new ref(), iDeltaY = new ref();
int bPointsRight = 0;
POINT2[] savepoints = new POINT2[3];
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pointsCorner);
lineutility.InitializePOINT2Array(rectpts);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
DrawOpenRectangleDouble(savepoints, pointsCorner, rectpts);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(rectpts[j]);
counter++;
}
bPointsRight = DetermineDirectionDouble(savepoints);
CalcEndpieceDeltasDouble(savepoints, iDeltaX, iDeltaY, CONST_PI / 4);
if ((savepoints[0].y - savepoints[1].y) < 0) {// Point0 is higher than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints2);
}
} else {// Point0 is lower than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], -iDeltaY.value[0], iDeltaX.value[0], deltapoints2);
}
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints1[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints2[j]);
counter++;
}
//clean up
pointsCorner = null;
rectpts = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMCanalizeDouble",
new RendererException("Failed inside GetDISMCanalizeDouble", exc));
}
return counter;
}
/**
* Calculates the points for DECEIVE.
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
* @param vblCounter the number of symbol points.
*/
protected static void GetDISMDeceiveDouble(POINT2[] points) {
try {
POINT2[] savepoints = new POINT2[3];// POINT2[3];
int j = 0;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
points[0] = new POINT2(savepoints[0]);
points[0].style = 1;
points[1] = new POINT2(savepoints[1]);
points[1].style = 5;
points[2] = new POINT2(savepoints[2]);
points[2].style = 1;
points[3] = new POINT2(savepoints[0]);
points[3].style = 5;
savepoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMDeceiveDouble",
new RendererException("Failed inside GetDISMDeceiveDouble", exc));
}
return;
}
/**
* Calculates the points for DISRUPT
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMDisruptDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
POINT2[] pts = new POINT2[2];
POINT2[] ptsArrow = new POINT2[3];
POINT2 ptCenter = new POINT2();
int j = 0;
POINT2[] savepoints = new POINT2[3];
double dAngle1 = 0;
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
POINT2[] deltapoints3 = new POINT2[4];
double iDiagEOL_length = 0;
double iDeltaX1 = 0;
double iDeltaY1 = 0;
double iDeltaX2 = 0;
double iDeltaY2 = 0;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(ptsArrow);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
lineutility.InitializePOINT2Array(deltapoints3);
// DrawLine(destination, mask, color, points, 2, 2);
points[counter] = new POINT2(savepoints[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 5;
counter++;
// pts[0] = points[1];
// pts[1] = points[2];
// DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(savepoints[2]);
points[counter].style = 5;
counter++;
ptCenter.x = (savepoints[0].x + savepoints[1].x) / 2;
ptCenter.y = (savepoints[0].y + savepoints[1].y) / 2;
ptsArrow[0] = new POINT2(savepoints[2]);
ptsArrow[1].x = ptCenter.x + (savepoints[2].x - savepoints[1].x) * 4 / 5;
ptsArrow[1].y = ptCenter.y + (savepoints[2].y - savepoints[1].y) * 4 / 5;
ptsArrow[2].x = savepoints[0].x + (savepoints[2].x - savepoints[1].x) * 3 / 5;
ptsArrow[2].y = savepoints[0].y + (savepoints[2].y - savepoints[1].y) * 3 / 5;
pts[0].x = ptCenter.x - (savepoints[2].x - savepoints[1].x) / 5;
pts[0].y = ptCenter.y - (savepoints[2].y - savepoints[1].y) / 5;
pts[1] = new POINT2(ptsArrow[1]);
// DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0] = new POINT2(savepoints[0]);
pts[1] = new POINT2(ptsArrow[2]);
// DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// the following code is very similar to CalcEndpieceDeltas
iDiagEOL_length = ((Math.sqrt // height of graphic
(
(savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y)) +
Math.sqrt // length of graphic
(
(savepoints[2].x - savepoints[1].x) * (savepoints[2].x - savepoints[1].x) +
(savepoints[2].y - savepoints[1].y) * (savepoints[2].y - savepoints[1].y))) / 15);
//M. Deutch 8-18-04
if (iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if (iDiagEOL_length < minLength) {//was minLength
iDiagEOL_length = minLength; //was minLength
}
// dAngle1 = angle used to calculate the end-piece deltas
dAngle1 = Math.atan2(savepoints[1].y - savepoints[2].y, savepoints[1].x - savepoints[2].x);
// dAngle1 = atan2(savepoints[1].y - savepoints[2].y, savepoints[1].x - savepoints[2].x);
iDeltaX1 = (iDiagEOL_length * Math.cos(dAngle1 - CONST_PI / 6));
iDeltaY1 = (iDiagEOL_length * Math.sin(dAngle1 - CONST_PI / 6));
iDeltaX2 = (iDiagEOL_length * Math.cos(dAngle1 + CONST_PI / 6));
iDeltaY2 = (iDiagEOL_length * Math.sin(dAngle1 + CONST_PI / 6));
DrawEndpieceDeltasDouble(ptsArrow[0],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints1);
DrawEndpieceDeltasDouble(ptsArrow[1],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints2);
DrawEndpieceDeltasDouble(ptsArrow[2],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints3);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints1[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints2[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints3[j]);
counter++;
}
//clean up
pts = null;
ptsArrow = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
deltapoints3 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMDisruptDouble",
new RendererException("Failed inside GetDISMDisruptDouble", exc));
}
return counter;
}
// protected int GetDISMSARADouble(POINT2[] points, int linetype, int vblCounter) {
// int counter = 0;
// try {
// int i = 0, j = 0;
// float scale = (float) 0.9;
// float iSymbolSize = scale * (float) 10; // size left for symbol centered within this graphic
// POINT2[] pts = new POINT2[2];
// POINT2[] savepoints = new POINT2[3];
// // locate point near center where jaggy lines should begin
// POINT2[] ptCenter = new POINT2[2];
// // four possible center points
// POINT2[] ptsBegin = new POINT2[4];
// int iLengthTemp = 0;
// int iLengthCntPt1 = 0;
// int iLengthCntPt2 = 0;
// int iDelta = 0;
// double dAngle0 = 0, dDeltaX0 = 0, dDeltaY0 = 0, dDeltaX1 = 0, dDeltaY1 = 0;
// POINT2[] ptsJaggyLine = new POINT2[4];
// for (j = 0; j < 3; j++) {
// savepoints[j] = new POINT2(points[j]);
// lineutility.InitializePOINT2Array(ptsBegin);
// lineutility.InitializePOINT2Array(ptCenter);
// lineutility.InitializePOINT2Array(pts);
// lineutility.InitializePOINT2Array(ptsJaggyLine);
// ptsBegin[0].x = savepoints[0].x - iSymbolSize;
// ptsBegin[0].y = savepoints[0].y - iSymbolSize; // top left
// ptsBegin[1].x = savepoints[0].x + iSymbolSize;
// ptsBegin[1].y = savepoints[0].y - iSymbolSize; // top right
// ptsBegin[2].x = savepoints[0].x + iSymbolSize;
// ptsBegin[2].y = savepoints[0].y + iSymbolSize; // bottom right
// ptsBegin[3].x = savepoints[0].x - iSymbolSize;
// ptsBegin[3].y = savepoints[0].y + iSymbolSize; // bottom left
// ptCenter[0] = ptCenter[1] = ptsBegin[0];
// // locate begin point for Point1
// iLengthCntPt1 = (int) Math.sqrt(
// (savepoints[1].x - ptsBegin[0].x) * (savepoints[1].x - ptsBegin[0].x) +
// (savepoints[1].y - ptsBegin[0].y) * (savepoints[1].y - ptsBegin[0].y));
// for (i = 1; i < 4; i++) {
// iLengthTemp = (int) Math.sqrt(
// (savepoints[1].x - ptsBegin[i].x) * (savepoints[1].x - ptsBegin[i].x) +
// (savepoints[1].y - ptsBegin[i].y) * (savepoints[1].y - ptsBegin[i].y));
// // locate begin point for Point2
// iLengthCntPt2 = (int) Math.sqrt(
// (savepoints[2].x - ptsBegin[0].x) * (savepoints[2].x - ptsBegin[0].x) +
// (savepoints[2].y - ptsBegin[0].y) * (savepoints[2].y - ptsBegin[0].y));
// for (i = 1; i < 4; i++) {
// iLengthTemp = (int) Math.sqrt(
// (savepoints[2].x - ptsBegin[i].x) * (savepoints[2].x - ptsBegin[i].x) +
// (savepoints[2].y - ptsBegin[i].y) * (savepoints[2].y - ptsBegin[i].y));
// // calculate length of jaggy within the line
// if (iLengthCntPt1 < iLengthCntPt2) {
// iDelta = iLengthCntPt1 / 12;
// } else {
// iDelta = iLengthCntPt2 / 12;
// //M. Deutch 8-18-04
// if (iDelta > (int) maxLength) {
// iDelta = (int) maxLength;
// if (iDelta < (int) minLength) {
// iDelta = (int) minLength;
// // draw line from center to Point1
// ptsJaggyLine[0] = ptCenter[0];
// dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[1].y, ptsJaggyLine[0].x - savepoints[1].x);
// pts[0].x = (ptsJaggyLine[0].x + savepoints[1].x) / 2;
// pts[0].y = (ptsJaggyLine[0].y + savepoints[1].y) / 2;
// dDeltaX0 = Math.cos(dAngle0 + CONST_PI / 4) * iDelta;
// dDeltaY0 = Math.sin(dAngle0 + CONST_PI / 4) * iDelta;
// ptsJaggyLine[1].x = pts[0].x - dDeltaX0;
// ptsJaggyLine[1].y = pts[0].y - dDeltaY0;
// ptsJaggyLine[2].x = pts[0].x + dDeltaX0;
// ptsJaggyLine[2].y = pts[0].y + dDeltaY0;
// ptsJaggyLine[3] = new POINT2(savepoints[1]);
// // DrawLine(destination, mask, color, ptsJaggyLine, 4, iLineThickness);
// for (j = 0; j < 4; j++) {
// points[counter] = new POINT2(ptsJaggyLine[j]);
// //points[counter].style=0;
// counter++;
// points[counter - 1].style = 5;
// // draw arrow at end of line
// dDeltaX1 = Math.cos(dAngle0 - CONST_PI / 4) * iDelta;
// dDeltaY1 = Math.sin(dAngle0 - CONST_PI / 4) * iDelta;
// ptsJaggyLine[0].x = savepoints[1].x + dDeltaX0;
// ptsJaggyLine[0].y = savepoints[1].y + dDeltaY0;
// ptsJaggyLine[1] = new POINT2(savepoints[1]);
// ptsJaggyLine[2].x = savepoints[1].x + dDeltaX1;
// ptsJaggyLine[2].y = savepoints[1].y + dDeltaY1;
// // DrawFilledArrowhead(destination, mask, ptsJaggyLine, color);
// for (j = 0; j < 3; j++) {
// points[counter] = new POINT2(ptsJaggyLine[j]);
// points[counter].style = 9;
// counter++;
// points[counter - 1].style = 10;
// // draw line from center to Point2
// ptsJaggyLine[0] = new POINT2(ptCenter[1]);
// dAngle0 = Math.atan2(ptsJaggyLine[0].y - savepoints[2].y, ptsJaggyLine[0].x - savepoints[2].x);
// // dAngle0 = atan2(ptsJaggyLine[0].y - savepoints[2].y, ptsJaggyLine[0].x - savepoints[2].x);
// pts[0].x = (ptsJaggyLine[0].x + savepoints[2].x) / 2;
// pts[0].y = (ptsJaggyLine[0].y + savepoints[2].y) / 2;
// dDeltaX0 = Math.cos(dAngle0 + CONST_PI / 4) * iDelta;
// dDeltaY0 = Math.sin(dAngle0 + CONST_PI / 4) * iDelta;
// ptsJaggyLine[1].x = pts[0].x - dDeltaX0;
// ptsJaggyLine[1].y = pts[0].y - dDeltaY0;
// ptsJaggyLine[2].x = pts[0].x + dDeltaX0;
// ptsJaggyLine[2].y = pts[0].y + dDeltaY0;
// ptsJaggyLine[3] = new POINT2(savepoints[2]);
// // DrawLine(destination, mask, color, ptsJaggyLine, 4, iLineThickness);
// for (j = 0; j < 4; j++) {
// points[counter] = new POINT2(ptsJaggyLine[j]);
// //points[counter].style=0;
// counter++;
// points[counter - 1].style = 5;
// // draw arrow at end of line
// dDeltaX1 = Math.cos(dAngle0 - CONST_PI / 4) * iDelta;
// dDeltaY1 = Math.sin(dAngle0 - CONST_PI / 4) * iDelta;
// ptsJaggyLine[0].x = savepoints[2].x + dDeltaX0;
// ptsJaggyLine[0].y = savepoints[2].y + dDeltaY0;
// ptsJaggyLine[1] = new POINT2(savepoints[2]);
// ptsJaggyLine[2].x = savepoints[2].x + dDeltaX1;
// ptsJaggyLine[2].y = savepoints[2].y + dDeltaY1;
// // DrawFilledArrowhead(destination, mask, ptsJaggyLine, color);
// for (j = 0; j < 3; j++) {
// points[counter] = new POINT2(ptsJaggyLine[j]);
// points[counter].style = 9;
// counter++;
// points[counter - 1].style = 10;
// //clean up
// pts = null;
// savepoints = null;
// ptCenter = null;
// ptsBegin = null;
// ptsJaggyLine = null;
// //return;
// } catch (Exception e) {
// System.out.println(e.getMessage());
// return counter;
/**
* Calculates the points for CONTAIN
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMContainDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
POINT2[] pts = new POINT2[3];
POINT2 ptCenter = new POINT2();
POINT2 ptPerp = new POINT2(); // point used to draw perpendicular line
double iPerpLength = 0;
int j = 0;
double dAngle1 = 0, d = 0;
double dCosAngle1 = 0;
double dSinAngle1 = 0;
double iRadius = 0;
double iDiagEOL_length = 0;
double dAngle2 = 0;
double dDeltaX1, dDeltaY1, dDeltaX2, dDeltaY2;
POINT2[] savepoints = new POINT2[3];
POINT2[] arcpoints = new POINT2[17];
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(arcpoints);
ptCenter.x = (savepoints[0].x + savepoints[1].x) / 2;
ptCenter.y = (savepoints[0].y + savepoints[1].y) / 2;
//added section M. Deutch 8-10-06
//reverse points 0 and 1 if necessary to ensure arc
//has correct orientation
ref<double[]> m = new ref();
POINT2 ptRelative = lineutility.PointRelativeToLine(savepoints[0], savepoints[1], savepoints[2]);
lineutility.CalcTrueSlopeDouble2(savepoints[0], savepoints[1], m);
if (m.value[0] != 0) {
if (savepoints[0].y > savepoints[1].y) {
if (ptRelative.x > ptCenter.x) {
lineutility.Reverse2Points(savepoints[0], savepoints[1]);
}
}
if (savepoints[0].y < savepoints[1].y) {
if (ptRelative.x < ptCenter.x) {
lineutility.Reverse2Points(savepoints[0], savepoints[1]);
}
}
} else {
if (savepoints[0].x < savepoints[1].x) {
if (ptRelative.y > ptCenter.y) {
lineutility.Reverse2Points(savepoints[0], savepoints[1]);
}
}
if (savepoints[0].x > savepoints[1].x) {
if (ptRelative.y < ptCenter.y) {
lineutility.Reverse2Points(savepoints[0], savepoints[1]);
}
}
}
//end section
iPerpLength = Math.sqrt((ptCenter.x - savepoints[2].x) * (ptCenter.x - savepoints[2].x) + (ptCenter.y - savepoints[2].y) * (ptCenter.y - savepoints[2].y));
if (iPerpLength < 1) {
iPerpLength = 1;
}
dAngle1 = Math.atan2(savepoints[0].y - savepoints[1].y, savepoints[0].x - savepoints[1].x);
dCosAngle1 = Math.cos(dAngle1 + CONST_PI / 2);
dSinAngle1 = Math.sin(dAngle1 + CONST_PI / 2);
ptPerp.x = ptCenter.x + dCosAngle1 * iPerpLength;
ptPerp.y = ptCenter.y + dSinAngle1 * iPerpLength;
pts[0] = new POINT2(ptCenter);
//diagnostic for CommandSight
//pts[1] = new POINT2(ptPerp);
pts[1] = new POINT2(savepoints[2]);
// DrawLineWithText(destination, mask, color, pts, 2, "ENY", scale, eraseBackground);
points[counter] = new POINT2(pts[0]);
points[counter].style = 14;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw arrowhead
iRadius = Math.sqrt((ptCenter.x - savepoints[0].x) * (ptCenter.x - savepoints[0].x) + (ptCenter.y - savepoints[0].y) * (ptCenter.y - savepoints[0].y));
iDiagEOL_length = (iPerpLength + iRadius) / 20;
if (iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if (iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
dAngle2 = Math.atan2(ptPerp.y - ptCenter.y, ptPerp.x - ptCenter.x);
dDeltaX1 = Math.cos(dAngle2 + CONST_PI / 4);
dDeltaY1 = Math.sin(dAngle2 + CONST_PI / 4);
dDeltaX2 = Math.cos(dAngle2 - CONST_PI / 4);
dDeltaY2 = Math.sin(dAngle2 - CONST_PI / 4);
pts[0].x = ptCenter.x + dDeltaX1 * iDiagEOL_length;
pts[0].y = ptCenter.y + dDeltaY1 * iDiagEOL_length;
pts[1] = new POINT2(ptCenter);
pts[2].x = ptCenter.x + dDeltaX2 * iDiagEOL_length;
pts[2].y = ptCenter.y + dDeltaY2 * iDiagEOL_length;
//end section
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw arc
ArcApproximationDouble(ptCenter.x - iRadius, ptCenter.y - iRadius,
ptCenter.x + iRadius, ptCenter.y + iRadius,
savepoints[0].x, savepoints[0].y, savepoints[1].x, savepoints[1].y, arcpoints);
for (j = 0; j < 17; j++) {
points[counter] = new POINT2(arcpoints[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw spokes inside arc
pts[0] = new POINT2(savepoints[0]);
pts[1].x = (pts[0].x + ptCenter.x) / 2;
pts[1].y = (pts[0].y + ptCenter.y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0] = new POINT2(savepoints[1]);
pts[1].x = (pts[0].x + ptCenter.x) / 2;
pts[1].y = (pts[0].y + ptCenter.y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
// DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = ptCenter.x - (ptPerp.x - ptCenter.x) * iRadius / iPerpLength;
pts[0].y = ptCenter.y - (ptPerp.y - ptCenter.y) * iRadius / iPerpLength;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = ptCenter.x - dDeltaX1 * iRadius;
pts[0].y = ptCenter.y - dDeltaY1 * iRadius;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = ptCenter.x - dDeltaX2 * iRadius;
pts[0].y = ptCenter.y - dDeltaY2 * iRadius;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
dDeltaX1 = Math.cos(dAngle2 + CONST_PI / 8);
dDeltaY1 = Math.sin(dAngle2 + CONST_PI / 8);
dDeltaX2 = Math.cos(dAngle2 - CONST_PI / 8);
dDeltaY2 = Math.sin(dAngle2 - CONST_PI / 8);
pts[0].x = ptCenter.x - dDeltaX1 * iRadius;
pts[0].y = ptCenter.y - dDeltaY1 * iRadius;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = ptCenter.x - dDeltaX2 * iRadius;
pts[0].y = ptCenter.y - dDeltaY2 * iRadius;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
dDeltaX1 = Math.cos(dAngle2 + 3 * CONST_PI / 8);
dDeltaY1 = Math.sin(dAngle2 + 3 * CONST_PI / 8);
dDeltaX2 = Math.cos(dAngle2 - 3 * CONST_PI / 8);
dDeltaY2 = Math.sin(dAngle2 - 3 * CONST_PI / 8);
pts[0].x = ptCenter.x - dDeltaX1 * iRadius;
pts[0].y = ptCenter.y - dDeltaY1 * iRadius;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = ptCenter.x - dDeltaX2 * iRadius;
pts[0].y = ptCenter.y - dDeltaY2 * iRadius;
pts[1].x = (ptCenter.x + pts[0].x) / 2;
pts[1].y = (ptCenter.y + pts[0].y) / 2;
d = lineutility.CalcDistanceDouble(pts[0], pts[1]);
if (d > maxLength) //shorten the spoke
{
pts[1] = lineutility.ExtendLineDouble(pts[1], pts[0], -maxLength);
}
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
//clean up
pts = null;
savepoints = null;
arcpoints = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMContainDouble",
new RendererException("Failed inside GetDISMContainDouble", exc));
}
return counter;
}
/**
* Calculates the points for FIX, MNFLDFIX
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMFixDouble(POINT2[] points, int linetype,Rectangle2D clipBounds) {
int counter = 0;
try {
POINT2[] pts = new POINT2[3];
POINT2[] savepoints = new POINT2[2];
double dAngle1 = 0;
double dLength = 0;
double dJaggyHalfAmp = 0;
double dJaggyHalfPeriod = 0;
double dDeltaXOut = 0;
double dDeltaYOut = 0;
double dDeltaXAlong = 0;
double dDeltaYAlong = 0;
int iNumJaggies = 0;
int i = 0, j = 0;
for (j = 0; j < 2; j++) {
savepoints[j] = new POINT2(points[j]);
}
Boolean drawJaggies=true;
if(clipBounds != null)
{
POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
savepoints=lineutility.BoundOneSegment(savepoints[0], savepoints[1], ul, lr);
}
if(savepoints==null)
{
savepoints=new POINT2[2];
for (j = 0; j < 2; j++) {
savepoints[j] = new POINT2(points[j]);
}
drawJaggies=false;
}
lineutility.InitializePOINT2Array(pts);
//reverse the points
dAngle1 = Math.atan2(savepoints[0].y - savepoints[1].y, savepoints[0].x - savepoints[1].x);
dLength = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
//arraysupport tries to set jaggylength before the points get bounded
dJaggyHalfAmp = dLength / 15; // half the amplitude of the "jaggy function"
if (dJaggyHalfAmp > maxLength) {
dJaggyHalfAmp = maxLength;
}
if (dJaggyHalfAmp < minLength) {
dJaggyHalfAmp = minLength;
}
dJaggyHalfPeriod = dJaggyHalfAmp / 1.5; // half the period of the "jaggy function"
dDeltaXOut = Math.cos(dAngle1 + CONST_PI / 2) * dJaggyHalfAmp; // X-delta out from the center line
dDeltaYOut = Math.sin(dAngle1 + CONST_PI / 2) * dJaggyHalfAmp; // Y-delta out from the center line
dDeltaXAlong = Math.cos(dAngle1) * dJaggyHalfPeriod; // X-delta along the center line
dDeltaYAlong = Math.sin(dAngle1) * dJaggyHalfPeriod; // Y-delta along the center line
iNumJaggies = (int) (dLength / dJaggyHalfPeriod) - 3;
i = 2;
pts[0] = new POINT2(savepoints[1]);
pts[1].x = savepoints[1].x + dDeltaXAlong * 1.5;
pts[1].y = savepoints[1].y + dDeltaYAlong * 1.5;
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = savepoints[1].x + dDeltaXOut + dDeltaXAlong * i;
pts[0].y = savepoints[1].y + dDeltaYOut + dDeltaYAlong * i;
i++;
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
if(drawJaggies)
while (i <= iNumJaggies) {
pts[1].x = savepoints[1].x - dDeltaXOut + dDeltaXAlong * i;
pts[1].y = savepoints[1].y - dDeltaYOut + dDeltaYAlong * i;
i++;
pts[2].x = savepoints[1].x + dDeltaXOut + dDeltaXAlong * i;
pts[2].y = savepoints[1].y + dDeltaYOut + dDeltaYAlong * i;
i++;
//DrawLine(destination, mask, color, pts, 3, 2);
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
pts[0] = new POINT2(pts[2]);
}
pts[1] = new POINT2(pts[0]);
pts[0].x = savepoints[1].x + dDeltaXAlong * i;
pts[0].y = savepoints[1].y + dDeltaYAlong * i;
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[1] = new POINT2(savepoints[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw arrowhead
pts[0].x = savepoints[0].x + dDeltaXOut / 1.5 - dDeltaXAlong;
pts[0].y = savepoints[0].y + dDeltaYOut / 1.5 - dDeltaYAlong;
pts[2].x = savepoints[0].x - dDeltaXOut / 1.5 - dDeltaXAlong;
pts[2].y = savepoints[0].y - dDeltaYOut / 1.5 - dDeltaYAlong;
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
if (linetype == (long) TacticalLines.MNFLDFIX) {
points[counter].style = 9;
} else {
points[counter].style = 0;
}
counter++;
}
if (linetype == (long) TacticalLines.MNFLDFIX) {
points[counter - 1].style = 10;
} else {
points[counter - 1].style = 5;
}
//clean up
pts = null;
savepoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMFixDouble",
new RendererException("Failed inside GetDISMFixDouble", exc));
}
return counter;
}
/**
* Calculates the points for CLEAR.
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMClearDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
POINT2[] savepoints = new POINT2[3];
int j = 0;
POINT2[] pts = new POINT2[2];
POINT2[] ptsArrow = new POINT2[3];
double ctrX = ((points[0].x + points[1].x) / 2);
double ctrY = ((points[0].y + points[1].y) / 2);
ref<double[]> iDeltaX1 = new ref(), iDeltaY1 = new ref(), iDeltaX2 = new ref(), iDeltaY2 = new ref();
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
POINT2[] deltapoints3 = new POINT2[4];
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(ptsArrow);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
lineutility.InitializePOINT2Array(deltapoints3);
//DrawLine(destination, mask, color, points, 2, 2);
points[counter] = new POINT2(savepoints[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 5;
counter++;
pts[0].x = ctrX;
pts[0].y = ctrY;
pts[1] = new POINT2(savepoints[2]);
ptsArrow[0] = new POINT2(pts[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = (savepoints[0].x + ctrX) / 2;
pts[0].y = (savepoints[0].y + ctrY) / 2;
pts[1].x = savepoints[2].x + savepoints[0].x - pts[0].x;
pts[1].y = savepoints[2].y + savepoints[0].y - pts[0].y;
ptsArrow[1] = new POINT2(pts[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = (savepoints[1].x + ctrX) / 2;
pts[0].y = (savepoints[1].y + ctrY) / 2;
pts[1].x = savepoints[2].x + savepoints[1].x - pts[0].x;
pts[1].y = savepoints[2].y + savepoints[1].y - pts[0].y;
ptsArrow[2] = new POINT2(pts[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
CalcEndpieceDeltasDouble(savepoints, iDeltaX1, iDeltaY1, CONST_PI / 6);
CalcEndpieceDeltasDouble(savepoints, iDeltaX2, iDeltaY2, -CONST_PI / 6);
DrawEndpieceDeltasDouble(ptsArrow[0],
iDeltaX1.value[0], iDeltaY1.value[0], iDeltaX2.value[0], iDeltaY2.value[0], deltapoints1);
DrawEndpieceDeltasDouble(ptsArrow[1],
iDeltaX1.value[0], iDeltaY1.value[0], iDeltaX2.value[0], iDeltaY2.value[0], deltapoints2);
DrawEndpieceDeltasDouble(ptsArrow[2],
iDeltaX1.value[0], iDeltaY1.value[0], iDeltaX2.value[0], iDeltaY2.value[0], deltapoints3);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints1[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints2[j]);
counter++;
}
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints3[j]);
counter++;
}
//clean up
pts = null;
savepoints = null;
ptsArrow = null;
deltapoints1 = null;
deltapoints2 = null;
deltapoints3 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMClearDouble",
new RendererException("Failed inside GetDISMClearDouble", exc));
}
return counter;
}
private static boolean IsSeizeArcReversed(POINT2[] pPoints){
try {
double dAngle1 = Math.atan2(pPoints[0].y - pPoints[1].y, pPoints[0].x - pPoints[1].x);
double dDeltaX1 = Math.cos(dAngle1 + CONST_PI / 4);
double dDeltaY1 = Math.sin(dAngle1 + CONST_PI / 4);
double dDeltaX2 = Math.cos(dAngle1 - CONST_PI / 4);
double dDeltaY2 = Math.sin(dAngle1 - CONST_PI / 4);
double dChordLength = Math.sqrt((pPoints[1].x - pPoints[0].x) * (pPoints[1].x - pPoints[0].x) +
(pPoints[1].y - pPoints[0].y) * (pPoints[1].y - pPoints[0].y));
double dArcRadius = dChordLength / 1.414213562373; // sqrt(2) == 1.414213562373
POINT2 ptArcCenter = new POINT2();
//get the default center
ptArcCenter.x = pPoints[0].x - dDeltaX1 * dArcRadius;
ptArcCenter.y = pPoints[0].y - dDeltaY1 * dArcRadius;
double d = lineutility.CalcDistanceDouble(ptArcCenter, pPoints[2]);
//get the alternate center if the arc is reversed
POINT2 ptArcCenterReversed = new POINT2();
ptArcCenterReversed.x = pPoints[0].x - dDeltaX2 * dArcRadius;
ptArcCenterReversed.y = pPoints[0].y - dDeltaY2 * dArcRadius;
double dReversed = lineutility.CalcDistanceDouble(ptArcCenterReversed, pPoints[2]);
if (dReversed > d) {
return true;
} else {
return false;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"IsSeizeArcReversed",
new RendererException("Failed inside IsSeizeArcReversed", exc));
}
return false;
}
/**
* Calculates the points for SEIZE
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMSeizeDouble(POINT2[] points,
int linetype,
double radius)
{
int counter = 0;
try {
POINT2 ptArcCenter = new POINT2();
POINT2 ptArcStart = new POINT2();
POINT2[] savepoints = new POINT2[3];
float scale = (float) 0.9;
double iCircleRadius = (25 * scale);
POINT2[] arcpoints = new POINT2[17];
POINT2[] pts = new POINT2[3];
double dAngle1 = 0;
double dDeltaX1 = 0;
double dDeltaY1 = 0;
double dDeltaX2 = 0;
double dDeltaY2 = 0;
double dChordLength = 0;
double dArcRadius = 0;
int j = 0;
double dDeltaX3 = 0;
double dDeltaY3 = 0;
double iDiagEOL_length = 0;
double factor = 1;
if(radius>0)
iCircleRadius=radius;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
//if(points.Length>2)
// savepoints[2]=points[j];
}
//if radius is 0 then it is rev B
String client=CELineArray.getClient();
if(!client.startsWith("cpof") && radius==0)
{
dArcRadius=lineutility.CalcDistanceDouble(savepoints[0], savepoints[1]);
if(iCircleRadius>dArcRadius/2)
iCircleRadius=dArcRadius/2;
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(arcpoints);
// draw circle
ArcApproximationDouble(savepoints[0].x - iCircleRadius, savepoints[0].y - iCircleRadius,
savepoints[0].x + iCircleRadius, savepoints[0].y + iCircleRadius,
savepoints[0].x, savepoints[0].y, savepoints[0].x, savepoints[0].y, arcpoints);
for (j = 0; j < 17; j++) {
points[counter] = new POINT2(arcpoints[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw arc
dAngle1 = Math.atan2(savepoints[0].y - savepoints[1].y, savepoints[0].x - savepoints[1].x);
dDeltaX1 = Math.cos(dAngle1 + CONST_PI / 4);
dDeltaY1 = Math.sin(dAngle1 + CONST_PI / 4);
dDeltaX2 = Math.cos(dAngle1 - CONST_PI / 4);
dDeltaY2 = Math.sin(dAngle1 - CONST_PI / 4);
boolean isArcReversed = IsSeizeArcReversed(savepoints);
//bool isArcReversed = false;
if (isArcReversed == false) {
ptArcStart.x = savepoints[0].x - dDeltaX2 * iCircleRadius;
ptArcStart.y = savepoints[0].y - dDeltaY2 * iCircleRadius;
dChordLength = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
dArcRadius = dChordLength / 1.414213562373; // sqrt(2) == 1.414213562373
ptArcCenter.x = savepoints[0].x - dDeltaX1 * dArcRadius;
ptArcCenter.y = savepoints[0].y - dDeltaY1 * dArcRadius;
ArcApproximationDouble((ptArcCenter.x - dArcRadius), (ptArcCenter.y - dArcRadius),
(ptArcCenter.x + dArcRadius), (ptArcCenter.y + dArcRadius),
savepoints[1].x, savepoints[1].y, ptArcStart.x, ptArcStart.y, arcpoints);
} else //arc is reversed
{
ptArcStart.x = savepoints[0].x - dDeltaX1 * iCircleRadius;
ptArcStart.y = savepoints[0].y - dDeltaY1 * iCircleRadius;
dChordLength = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
dArcRadius = dChordLength / 1.414213562373; // sqrt(2) == 1.414213562373
ptArcCenter.x = savepoints[0].x - dDeltaX2 * dArcRadius;
ptArcCenter.y = savepoints[0].y - dDeltaY2 * dArcRadius;
ArcApproximationDouble((ptArcCenter.x - dArcRadius), (ptArcCenter.y - dArcRadius),
(ptArcCenter.x + dArcRadius), (ptArcCenter.y + dArcRadius),
ptArcStart.x, ptArcStart.y, savepoints[1].x, savepoints[1].y, arcpoints);
}
//end diagnostic
for (j = 0; j < 17; j++) {
points[counter] = new POINT2(arcpoints[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw arrow
if (dChordLength / 8 > maxLength) {
factor = dChordLength / (8 * maxLength);
}
if (factor == 0) {
factor = 1;
}
if (isArcReversed == false) {
pts[0].x = savepoints[1].x - (savepoints[1].x - savepoints[0].x) / (8 * factor);
pts[0].y = savepoints[1].y - (savepoints[1].y - savepoints[0].y) / (8 * factor);
pts[1] = new POINT2(savepoints[1]);
dDeltaX3 = Math.cos(dAngle1 + CONST_PI / 2);
dDeltaY3 = Math.sin(dAngle1 + CONST_PI / 2);
iDiagEOL_length = (dChordLength / 8);
pts[2].x = savepoints[1].x + dDeltaX3 * iDiagEOL_length / factor;
pts[2].y = savepoints[1].y + dDeltaY3 * iDiagEOL_length / factor;
} //DrawLine(destination, mask, color, pts, 3, 2);
//diagnostic arc reversed
else {
pts[0].x = savepoints[1].x - (savepoints[1].x - savepoints[0].x) / (8 * factor);
pts[0].y = savepoints[1].y - (savepoints[1].y - savepoints[0].y) / (8 * factor);
pts[1] = new POINT2(savepoints[1]);
dDeltaX3 = Math.cos(dAngle1 - CONST_PI / 2);
dDeltaY3 = Math.sin(dAngle1 - CONST_PI / 2);
iDiagEOL_length = (dChordLength / 8);
pts[2].x = savepoints[1].x + dDeltaX3 * iDiagEOL_length / factor;
pts[2].y = savepoints[1].y + dDeltaY3 * iDiagEOL_length / factor;
}
//end diagnostic
//diagnostic
//end diagnostic
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
//clean up
savepoints = null;
arcpoints = null;
pts = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMSeizeDouble",
new RendererException("Failed inside GetDISMSeizeDouble", exc));
}
return counter;
}
/**
* Used twice for RIP to determine if the points are clockwise.
* @param x1
* @param y1
* @param x2
* @param y2
* @param px
* @param py
* @return RIGHT_SIDE if 3 points are clockwise
*/
private static int side(double x1, double y1, double x2, double y2, double px, double py) {
double dx1, dx2, dy1, dy2;
try {
double o;
dx1 = x2 - x1;
dy1 = y2 - y1;
dx2 = px - x1;
dy2 = py - y1;
o = (dx1 * dy2) - (dy1 * dx2);
if (o > 0.0) {
return (LEFT_SIDE);
}
if (o < 0.0) {
return (RIGHT_SIDE);
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "side",
new RendererException("Failed inside side", exc));
}
return (COLINEAR);
}
/**
* Calculates the points for RIP
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type
*/
protected static int GetDISMRIPDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
// draw the straight lines
POINT2[] pts = new POINT2[2];
POINT2[] savepoints = new POINT2[4];
int j = 0;
double iLengthPt0Pt1 = 0;
double iDiagEOL_length = 0;
double dAngle1 = 0;
double iDeltaX1 = 0;
double iDeltaY1 = 0;
double iDeltaX2 = 0;
double iDeltaY2 = 0;
double iLengthPt2Pt3 = 0;
double iRadius = 0;
POINT2[] deltapoints = new POINT2[4];
POINT2[] arcpoints = new POINT2[17];
POINT2 ptArcCenter = new POINT2();
boolean clockwise=false;
int side01=side(points[0].x,points[0].y,points[1].x,points[1].y,points[2].x,points[2].y);
int side12=side(points[1].x,points[1].y,points[2].x,points[2].y,points[3].x,points[3].y);
if(side01==RIGHT_SIDE && side12==RIGHT_SIDE)
clockwise=true;
else if(side01==RIGHT_SIDE && side12==COLINEAR)
clockwise=true;
else if(side01==COLINEAR && side12==RIGHT_SIDE)
clockwise=true;
for (j = 0; j < 4; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(deltapoints);
lineutility.InitializePOINT2Array(arcpoints);
//DrawLine(destination, mask, color, points, 2, 2);
points[counter] = new POINT2(savepoints[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 5;
counter++;
pts[0] = new POINT2(savepoints[2]);
pts[1] = new POINT2(savepoints[3]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw the arrowhead on line between savepoints 0 and 1
pts[0] = new POINT2(savepoints[0]);
pts[1] = new POINT2(savepoints[1]);
iLengthPt0Pt1 = Math.sqrt((pts[1].x - pts[0].x) * (pts[1].x - pts[0].x) +
(pts[1].y - pts[0].y) * (pts[1].y - pts[0].y));
iDiagEOL_length = iLengthPt0Pt1 / 8;
//M. Deutch 8-19-04
if (iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if (iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
dAngle1 = Math.atan2(pts[1].y - pts[0].y, pts[1].x - pts[0].x);
iDeltaX1 = (iDiagEOL_length * Math.cos(dAngle1 - CONST_PI / 4));
iDeltaY1 = (iDiagEOL_length * Math.sin(dAngle1 - CONST_PI / 4));
iDeltaX2 = (iDiagEOL_length * Math.cos(dAngle1 + CONST_PI / 4));
iDeltaY2 = (iDiagEOL_length * Math.sin(dAngle1 + CONST_PI / 4));
DrawEndpieceDeltasDouble(pts[0],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints[j]);
points[counter].style = 0;
counter++;
}
points[counter - 3].style = 5;
points[counter - 1].style = 5;
// draw the arrowhead on line between savepoints 2 and 3
pts[0] = new POINT2(savepoints[2]);
pts[1] = new POINT2(savepoints[3]);
iLengthPt2Pt3 = Math.sqrt((pts[1].x - pts[0].x) * (pts[1].x - pts[0].x) +
(pts[1].y - pts[0].y) * (pts[1].y - pts[0].y));
iDiagEOL_length = iLengthPt2Pt3 / 8;
//M. Deutch 8-19-04
if (iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if (iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
dAngle1 = Math.atan2(pts[1].y - pts[0].y, pts[1].x - pts[0].x);
iDeltaX1 = (iDiagEOL_length * Math.cos(dAngle1 - CONST_PI / 4));
iDeltaY1 = (iDiagEOL_length * Math.sin(dAngle1 - CONST_PI / 4));
iDeltaX2 = (iDiagEOL_length * Math.cos(dAngle1 + CONST_PI / 4));
iDeltaY2 = (iDiagEOL_length * Math.sin(dAngle1 + CONST_PI / 4));
DrawEndpieceDeltasDouble(pts[0],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(deltapoints[j]);
points[counter].style = 0;
counter++;
}
points[counter - 3].style = 5;
points[counter - 1].style = 5;
// draw the semicircle
iRadius = (Math.sqrt((savepoints[2].x - savepoints[1].x) * (savepoints[2].x - savepoints[1].x) +
(savepoints[2].y - savepoints[1].y) * (savepoints[2].y - savepoints[1].y)) / 2);
ptArcCenter.x = (savepoints[1].x + savepoints[2].x) / 2;
ptArcCenter.y = (savepoints[1].y + savepoints[2].y) / 2;
//diagnostic
if(clockwise==false)
{
ArcApproximationDouble((ptArcCenter.x - iRadius), (ptArcCenter.y - iRadius),
(ptArcCenter.x + iRadius), (ptArcCenter.y + iRadius),
savepoints[2].x, savepoints[2].y, savepoints[1].x, savepoints[1].y, arcpoints);
}
else
{
ArcApproximationDouble((ptArcCenter.x - iRadius), (ptArcCenter.y - iRadius),
(ptArcCenter.x + iRadius), (ptArcCenter.y + iRadius),
savepoints[1].x, savepoints[1].y, savepoints[2].x, savepoints[2].y, arcpoints);
}
for (j = 0; j < 17; j++) {
points[counter] = new POINT2(arcpoints[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
//clean up
pts = null;
savepoints = null;
deltapoints = null;
arcpoints = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMRIPDouble",
new RendererException("Failed inside GetDISMRIPDouble", exc));
}
return counter;
}
/**
* Calculates the points for BYDIF
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMByDifDouble(POINT2[] points,
int linetype,
Rectangle2D clipBounds) {
int counter = 0;
try {
POINT2[] pointsCorner = new POINT2[2];
POINT2[] rectpts = new POINT2[4];
POINT2[] savepoints = new POINT2[3], savepoints2 = new POINT2[2];
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
POINT2[] pts = new POINT2[3];
//POINT2 pt0 = new POINT2();
//POINT2 pt1 = new POINT2();
ref<double[]> iDeltaX = new ref(), iDeltaY = new ref();
int bPointsRight = 0;
double dAngle1 = 0;
double dLength = 0;
double dJaggyHalfAmp = 0;
double dJaggyHalfPeriod = 0;
double dDeltaXOut = 0;
double dDeltaYOut = 0;
double dDeltaXAlong = 0;
double dDeltaYAlong = 0;
int iNumJaggies = 0;
int i = 0, j = 0;
//int pointcounter = 0;
//int[] segments = null;
//end declarations
//lineutility.WriteFile("made it this far");
//ok to here
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pointsCorner);
lineutility.InitializePOINT2Array(rectpts);
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
DrawOpenRectangleDouble(savepoints, pointsCorner, rectpts);
//save the back side for use by the jagged line
savepoints2[0] = new POINT2(rectpts[1]);
savepoints2[1] = new POINT2(rectpts[2]);
//diagnostic these hard coded because JavalineArray does not know the bounds
if(clipBounds != null)
{
POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
savepoints2=lineutility.BoundOneSegment(savepoints2[0], savepoints2[1], ul, lr);
}
Boolean drawJaggies=true;
if(savepoints2==null)
{
savepoints2 = new POINT2[2];
savepoints2[0] = new POINT2(rectpts[1]);
savepoints2[1] = new POINT2(rectpts[2]);
drawJaggies=false;
}
//lineutility.WriteFile("made it this far");
//ok to here
//M. Deutch 10-27-10
//pointcounter = lineutility.BoundPointsCount(savepoints2, 2);
//pointcounter=countsupport.GetDISMFixCountDouble(savepoints2[0],savepoints2[1]);
//removed section 10-27-10
// segments = new int[pointcounter];
// savepoints2 = new POINT2[pointcounter];
// //reload savepoints2
// savepoints2[0] = rectpts[1];
// savepoints2[1] = rectpts[2];
// pt0 = rectpts[1];
// pt1 = rectpts[2];
// boolean bolFound = false;
// lineutility.BoundPoints(savepoints2, 2, segments);
// for (j = 0; j < pointcounter - 1; j++) {
// if (segments[j] == 1) {
// pt0 = new POINT2(savepoints2[j]);
// pt1 = new POINT2(savepoints2[j + 1]);
// bolFound = true;
// break;
// savepoints2 = null;
// savepoints2 = new POINT2[2];
// savepoints2[0] = new POINT2(pt0);
// savepoints2[1] = new POINT2(pt1);
// //end section
// if (bolFound == false) {
// counter = GetDISMEasyDouble(points, linetype);
// for (j = 12; j < points.length; j++) {
// points[j].style = 5;
// //cleanup
// pointsCorner = null;
// rectpts = null;
// savepoints = null;
// savepoints2 = null;
// deltapoints1 = null;
// deltapoints2 = null;
// pts = null;
// segments = null;
// return counter;
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(rectpts[j]);
points[counter].style = 0;
counter++;
}
points[1].style = 5;
points[counter - 1].style = 5;
dAngle1 = Math.atan2(savepoints2[0].y - savepoints2[1].y, savepoints2[0].x - savepoints2[1].x);
dLength = Math.sqrt((savepoints2[1].x - savepoints2[0].x) * (savepoints2[1].x - savepoints2[0].x) +
(savepoints2[1].y - savepoints2[0].y) * (savepoints2[1].y - savepoints2[0].y));
dJaggyHalfAmp = dLength / 15; // half the amplitude of the "jaggy function"
//M. Deutch 8-18-04
if (dJaggyHalfAmp > maxLength) {
dJaggyHalfAmp = maxLength;
}
if (dJaggyHalfAmp < minLength) {
dJaggyHalfAmp = minLength;
}
dJaggyHalfPeriod = dJaggyHalfAmp / 1.5; // half the period of the "jaggy function"
dDeltaXOut = Math.cos(dAngle1 + CONST_PI / 2) * dJaggyHalfAmp; // X-delta out from the center line
dDeltaYOut = Math.sin(dAngle1 + CONST_PI / 2) * dJaggyHalfAmp; // Y-delta out from the center line
dDeltaXAlong = Math.cos(dAngle1) * dJaggyHalfPeriod; // X-delta along the center line
dDeltaYAlong = Math.sin(dAngle1) * dJaggyHalfPeriod; // Y-delta along the center line
iNumJaggies = (int) (dLength / dJaggyHalfPeriod) - 3;
i = 2;
pts[0] = new POINT2(savepoints2[1]);
pts[1].x = savepoints2[1].x + dDeltaXAlong * 1.5;
pts[1].y = savepoints2[1].y + dDeltaYAlong * 1.5;
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = savepoints2[1].x + dDeltaXOut + dDeltaXAlong * i;
pts[0].y = savepoints2[1].y + dDeltaYOut + dDeltaYAlong * i;
i++;
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
//lineutility.WriteFile("made it this far");
//ok to here
//lineutility.WriteFile("length = " + Double.toString(dLength) + "numJaggies = " +
//Integer.toString(iNumJaggies) + "points size = " + Integer.toString(points.length));
if(drawJaggies)//diagnostic
while (i <= iNumJaggies) {
pts[1].x = savepoints2[1].x - dDeltaXOut + dDeltaXAlong * i;
pts[1].y = savepoints2[1].y - dDeltaYOut + dDeltaYAlong * i;
i++;
pts[2].x = savepoints2[1].x + dDeltaXOut + dDeltaXAlong * i;
pts[2].y = savepoints2[1].y + dDeltaYOut + dDeltaYAlong * i;
i++;
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
pts[0] = new POINT2(pts[2]);
}
//lineutility.WriteFile("made it this far " + Double.toString(dLength));
pts[1] = new POINT2(pts[0]);
pts[0].x = savepoints2[1].x + dDeltaXAlong * i;
pts[0].y = savepoints2[1].y + dDeltaYAlong * i;
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[1] = new POINT2(savepoints2[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
//lineutility.WriteFile("made it this far");
//did not get this far
bPointsRight = DetermineDirectionDouble(savepoints);
CalcEndpieceDeltasDouble(savepoints, iDeltaX, iDeltaY, CONST_PI / 4);
if ((savepoints[0].y - savepoints[1].y) < 0) {// Point0 is higher than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
}
} else {// Point0 is lower than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
}
}
//lineutility.WriteFile("made it this far");
points[counter] = new POINT2(deltapoints1[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 10;
counter++;
points[counter] = new POINT2(deltapoints2[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 10;
counter++;
//clean up
pointsCorner = null;
rectpts = null;
savepoints = null;
savepoints2 = null;
deltapoints1 = null;
deltapoints2 = null;
pts = null;
//segments = null;
//return;
} catch (Exception exc) {
//lineutility.WriteFile(exc.getMessage());
ErrorLogger.LogException(_className ,"GetDISMByDifDouble",
new RendererException("Failed inside GetDISMByDifDouble", exc));
}
return counter;
}
/**
* Calculates the points for PENETRATE
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static void GetDISMPenetrateDouble(POINT2[] points, int linetype) {
try {
POINT2[] arrowpts = new POINT2[3];
POINT2 midpt = new POINT2();
POINT2[] savepoints = new POINT2[3];
//int nQuadrant=0,j=0;
int j = 0;
double d = 0;
//end declarations
for (j = 0; j < 3; j++) {
//savepoints[j].x=points[j].x;
//savepoints[j].y=points[j].y;
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(arrowpts);
points[0].x = savepoints[0].x;
points[0].y = savepoints[0].y;
points[0].style = 0;
points[1].x = savepoints[1].x;
points[1].y = savepoints[1].y;
points[1].style = 5;
midpt = lineutility.MidPointDouble(savepoints[0], savepoints[1], 0);
//comment one line for CommandSight
//points[2] = lineutility.PointRelativeToLine(savepoints[0], savepoints[1], savepoints[2]);
//uncomment one line for CommandSight
points[2] = new POINT2(savepoints[2]);
points[3] = new POINT2(midpt);
points[3].style = 5;
d = lineutility.MBRDistance(savepoints, 3);
//M. Deutch 8-19-04
if (d / 5 > maxLength) {
d = 5 * maxLength;
}
if (d / 5 < minLength) {
d = 5 * minLength;
}
// if(d<400)
// d=400;
String client=CELineArray.getClient();
if(client.matches("cpof3d") || client.matches("cpof2d"))
{
if(d<400)
d=400;
}
else
{
if(d<150)
d=150;
}
if(d>600)
d=600;
lineutility.GetArrowHead4Double(points[2], points[3], (int)d / 20,(int)d / 20, arrowpts, 0);
for (j = 0; j < 3; j++) {
points[4 + j] = new POINT2(arrowpts[j]);
}
//clean up
arrowpts = null;
savepoints = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMPenetrateDouble",
new RendererException("Failed inside GetDISMPenetrateDouble", exc));
}
return;
}
/**
* Calculates the points for BYIMP
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMByImpDouble(POINT2[] points,
int linetype) {
int counter = 0;
try {
int j = 0;
POINT2[] pointsCorner = new POINT2[2];
POINT2[] rectpts = new POINT2[4];
POINT2[] savepoints = new POINT2[3];
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
POINT2 midpt = new POINT2();
POINT2[] pts = new POINT2[6];
POINT2 ptRelative = new POINT2();
ref<double[]> iDeltaX = new ref(), iDeltaY = new ref();
int bPointsRight = 0;
double dMBR = lineutility.MBRDistance(points, 3);
//end declarations
//M. Deutch 8-18-04
if (dMBR > 40 * maxLength) {
dMBR = 40 * maxLength;
}
if (dMBR < 5 * minLength) {
dMBR = 5 * minLength;
}
if(dMBR>250)
dMBR=250;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(rectpts);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
lineutility.InitializePOINT2Array(pts);
lineutility.InitializePOINT2Array(pointsCorner);
DrawOpenRectangleDouble(savepoints, pointsCorner, rectpts);
points[counter] = new POINT2(rectpts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(rectpts[1]);
points[counter].style = 0;
counter++;
midpt = lineutility.MidPointDouble(rectpts[1], rectpts[2], 0);
pts[0] = lineutility.ExtendLine2Double(rectpts[1], midpt, -5, 5);
pts[1] = lineutility.ExtendLine2Double(rectpts[1], midpt, 5, 5);
points[counter] = new POINT2(pts[0]);
points[counter].style = 5;
counter++;
ptRelative = lineutility.PointRelativeToLine(rectpts[0], rectpts[1], pts[0]);
pts[2] = lineutility.ExtendLineDouble(ptRelative, pts[0], -dMBR / 40);
pts[3] = lineutility.ExtendLineDouble(ptRelative, pts[0], dMBR / 40);
points[counter] = new POINT2(pts[2]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[3]);
points[counter].style = 5;
counter++;
ptRelative = lineutility.PointRelativeToLine(rectpts[2], rectpts[3], pts[1]);
pts[4] = lineutility.ExtendLineDouble(ptRelative, pts[1], -dMBR / 40);
pts[5] = lineutility.ExtendLineDouble(ptRelative, pts[1], dMBR / 40);
points[counter] = new POINT2(pts[4]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[5]);
points[counter].style = 5;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(rectpts[2]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(rectpts[3]);
points[counter].style = 5;
counter++;
bPointsRight = DetermineDirectionDouble(savepoints);
CalcEndpieceDeltasDouble(savepoints, iDeltaX, iDeltaY, CONST_PI / 4);
if ((savepoints[0].y - savepoints[1].y) < 0) {// Point0 is higher than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
}
} else {// Point0 is lower than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
}
}
points[counter] = new POINT2(deltapoints1[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 10;
counter++;
points[counter] = new POINT2(deltapoints2[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 10;
counter++;
//clean up
pointsCorner = null;
rectpts = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
pts = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMByImpDouble",
new RendererException("Failed inside GetDISMByImpDouble", exc));
}
return counter;
}
/**
* Calculates the points for SPTBYFIRE
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMSupportByFireDouble(POINT2[] points,
int linetype) {
int counter = 0;
try {
POINT2[] pts = new POINT2[3];
POINT2[] savepoints = new POINT2[4];
int j = 0;
double iDiagEOL_length = 0;
double dAngle1 = 0;
double iDeltaX1 = 0;
double iDeltaY1 = 0;
double iDeltaX2 = 0;
double iDeltaY2 = 0;
for (j = 0; j < 4; j++) {
savepoints[j] = new POINT2(points[j]);
}
ReorderSptByFirePoints(savepoints);
lineutility.InitializePOINT2Array(pts);
// draw line connecting points 1 & 2
//DrawLine(destination, mask, color, savepoints, 2, 2);
points[counter] = new POINT2(savepoints[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 5;
counter++;
// draw line connecting savepoints 1 & 3
pts[0] = new POINT2(savepoints[0]);
pts[1] = new POINT2(savepoints[2]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw arrow at end of line
iDiagEOL_length = (Math.sqrt(
(savepoints[0].x - savepoints[1].x) * (savepoints[0].x - savepoints[1].x) +
(savepoints[0].y - savepoints[1].y) * (savepoints[0].y - savepoints[1].y)) / 10);
//M. Deutch 8-19-04
if (iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if (iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
dAngle1 = Math.atan2(savepoints[0].y - savepoints[2].y, savepoints[0].x - savepoints[2].x);
iDeltaX1 = (Math.cos(dAngle1 + CONST_PI / 6) * iDiagEOL_length);
iDeltaY1 = (Math.sin(dAngle1 + CONST_PI / 6) * iDiagEOL_length);
iDeltaX2 = (Math.cos(dAngle1 - CONST_PI / 6) * iDiagEOL_length);
iDeltaY2 = (Math.sin(dAngle1 - CONST_PI / 6) * iDiagEOL_length);
pts[0].x = savepoints[2].x + iDeltaX1;
pts[0].y = savepoints[2].y + iDeltaY1;
pts[1] = new POINT2(savepoints[2]);
pts[2].x = savepoints[2].x + iDeltaX2;
pts[2].y = savepoints[2].y + iDeltaY2;
//DrawLine(destination, mask, color, pts, 3, 2);
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw line connecting savepoints 2 & 4
pts[0] = new POINT2(savepoints[1]);
pts[1] = new POINT2(savepoints[3]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw arrow at end of line
dAngle1 = Math.atan2(savepoints[1].y - savepoints[3].y, savepoints[1].x - savepoints[3].x);
iDeltaX1 = (Math.cos(dAngle1 + CONST_PI / 6) * iDiagEOL_length);
iDeltaY1 = (Math.sin(dAngle1 + CONST_PI / 6) * iDiagEOL_length);
iDeltaX2 = (Math.cos(dAngle1 - CONST_PI / 6) * iDiagEOL_length);
iDeltaY2 = (Math.sin(dAngle1 - CONST_PI / 6) * iDiagEOL_length);
pts[0].x = savepoints[3].x + iDeltaX1;
pts[0].y = savepoints[3].y + iDeltaY1;
pts[1] = new POINT2(savepoints[3]);
pts[2].x = savepoints[3].x + iDeltaX2;
pts[2].y = savepoints[3].y + iDeltaY2;
//DrawLine(destination, mask, color, pts, 3, 2);
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw lines on the back of the graphic
dAngle1 = Math.atan2(savepoints[1].y - savepoints[0].y, savepoints[1].x - savepoints[0].x);
iDiagEOL_length *= 2;
iDeltaX1 = (Math.cos(dAngle1 - CONST_PI / 4) * iDiagEOL_length);
iDeltaY1 = (Math.sin(dAngle1 - CONST_PI / 4) * iDiagEOL_length);
iDeltaX2 = (Math.cos(dAngle1 + CONST_PI / 4) * iDiagEOL_length);
iDeltaY2 = (Math.sin(dAngle1 + CONST_PI / 4) * iDiagEOL_length);
pts[0].x = savepoints[0].x - iDeltaX1;
pts[0].y = savepoints[0].y - iDeltaY1;
pts[1] = new POINT2(savepoints[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = savepoints[1].x + iDeltaX2;
pts[0].y = savepoints[1].y + iDeltaY2;
pts[1] = new POINT2(savepoints[1]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
//clean up
pts = null;
savepoints = null;
//return;
}
catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMSupportbyFireDouble",
new RendererException("Failed inside GetDISMSupportByFireDouble", exc));
}
return counter;
}
private static void ReorderAtkByFirePoints(POINT2[] points) {
try {
//assume the points were ordered correctly. then pt0 is above the line from pt1 to pt2
POINT2[] savepoints = new POINT2[3];
POINT2 ptAboveLine = new POINT2(), ptBelowLine = new POINT2(), ptLeftOfLine = new POINT2(), ptRightOfLine = new POINT2();
double distToLine = 0, distanceToPointAboveLine = 0, distanceToPointBelowLine = 0;
double distanceToPointLeftOfLine = 0, distanceToPointRightOfLine = 0;
for (int j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
if (Math.abs(savepoints[1].x - savepoints[2].x) > 2) {
distToLine = lineutility.CalcDistanceToLineDouble(savepoints[1], savepoints[2], savepoints[0]);
ptAboveLine = lineutility.ExtendDirectedLine(savepoints[1], savepoints[2], savepoints[2], 2, distToLine);
ptBelowLine = lineutility.ExtendDirectedLine(savepoints[1], savepoints[2], savepoints[2], 3, distToLine);
distanceToPointAboveLine = lineutility.CalcDistanceDouble(savepoints[0], ptAboveLine);
distanceToPointBelowLine = lineutility.CalcDistanceDouble(savepoints[0], ptBelowLine);
if (distanceToPointAboveLine < distanceToPointBelowLine) {
//then pt2 - pt3 should be left to right
if (savepoints[2].x < savepoints[1].x) {
lineutility.Reverse2Points(savepoints[1], savepoints[2]);
//if(linetype==TacticalLines.SPTBYFIRE)
// lineutility.Reverse2Points(points[0],points[1]);
}
} else {
if (savepoints[2].x > savepoints[1].x) {
lineutility.Reverse2Points(savepoints[1], savepoints[2]);
//if(linetype==TacticalLines.SPTBYFIRE)
// lineutility.Reverse2Points(points[0],points[1]);
}
}
} else //the last 2 points form a vertical line
{
distToLine = lineutility.CalcDistanceToLineDouble(savepoints[1], savepoints[2], savepoints[0]);
ptLeftOfLine = lineutility.ExtendDirectedLine(savepoints[1], savepoints[2], savepoints[2], 0, distToLine);
ptRightOfLine = lineutility.ExtendDirectedLine(savepoints[1], savepoints[2], savepoints[2], 1, distToLine);
distanceToPointLeftOfLine = lineutility.CalcDistanceDouble(savepoints[0], ptLeftOfLine);
distanceToPointRightOfLine = lineutility.CalcDistanceDouble(savepoints[0], ptRightOfLine);
if (distanceToPointRightOfLine < distanceToPointLeftOfLine) {
if (savepoints[2].y < savepoints[1].y) {
lineutility.Reverse2Points(savepoints[1], savepoints[2]);
}
} else {
if (savepoints[2].y > savepoints[1].y) {
lineutility.Reverse2Points(savepoints[1], savepoints[2]);
}
}
}
points[1].x = savepoints[1].x;
points[1].y = savepoints[1].y;
points[2].x = savepoints[2].x;
points[2].y = savepoints[2].y;
} catch (Exception exc) {
ErrorLogger.LogException(_className, "ReorderAtkByFirePoints",
new RendererException("Failed inside GetDISMSupportByFireDouble", exc));
}
}
private static void ReorderSptByFirePoints(POINT2[] points) {
try {
//assume the points were ordered correctly. then pt0 is above the line from pt1 to pt2
POINT2 ptAboveLine = new POINT2(), ptBelowLine = new POINT2(), ptLeftOfLine = new POINT2(), ptRightOfLine = new POINT2();
double distToLine = 0, distanceToPointAboveLine = 0, distanceToPointBelowLine = 0;
double distanceToPointLeftOfLine = 0, distanceToPointRightOfLine = 0;
POINT2 midpt = lineutility.MidPointDouble(points[0], points[1], 0);
if (Math.abs(points[2].x - points[3].x) > 2) {
distToLine = lineutility.CalcDistanceToLineDouble(points[1], points[2], midpt);
ptAboveLine = lineutility.ExtendDirectedLine(points[1], points[2], points[2], 2, distToLine);
ptBelowLine = lineutility.ExtendDirectedLine(points[1], points[2], points[2], 3, distToLine);
distanceToPointAboveLine = lineutility.CalcDistanceDouble(points[0], ptAboveLine);
distanceToPointBelowLine = lineutility.CalcDistanceDouble(points[0], ptBelowLine);
if (distanceToPointAboveLine < distanceToPointBelowLine) {
//then pt2 - pt3 should be left to right
if (points[2].x < points[1].x) {
lineutility.Reverse2Points(points[0], points[1]);
lineutility.Reverse2Points(points[2], points[3]);
}
} else {
if (points[2].x > points[1].x) {
lineutility.Reverse2Points(points[0], points[1]);
lineutility.Reverse2Points(points[2], points[3]);
}
}
} else //the last 2 points form a vertical line
{
distToLine = lineutility.CalcDistanceToLineDouble(points[1], points[2], midpt);
ptLeftOfLine = lineutility.ExtendDirectedLine(points[1], points[2], points[2], 0, distToLine);
ptRightOfLine = lineutility.ExtendDirectedLine(points[1], points[2], points[2], 1, distToLine);
distanceToPointLeftOfLine = lineutility.CalcDistanceDouble(points[0], ptLeftOfLine);
distanceToPointRightOfLine = lineutility.CalcDistanceDouble(points[0], ptRightOfLine);
if (distanceToPointLeftOfLine < distanceToPointRightOfLine) {
//then pt2 - pt3 should be left to right
if (points[2].y > points[1].y) {
lineutility.Reverse2Points(points[0], points[1]);
lineutility.Reverse2Points(points[2], points[3]);
}
} else {
if (points[2].y < points[1].y) {
lineutility.Reverse2Points(points[0], points[1]);
lineutility.Reverse2Points(points[2], points[3]);
}
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "ReorderSptByFire",
new RendererException("Failed inside ReorderSptByFirePoints", exc));
}
}
/**
* Calculates the points for ATKBYFIRE
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMATKBYFIREDouble(POINT2[] points, int linetype) {
int counter = 0;
try {
POINT2[] pts = new POINT2[3];
POINT2 ptMid = new POINT2();
POINT2[] savepoints = new POINT2[3];
int j = 0;
double iDiagEOL_length = 0;
double dAngle1 = 0;
double iDeltaX1 = 0;
double iDeltaY1 = 0;
double iDeltaX2 = 0;
double iDeltaY2 = 0;
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
ReorderAtkByFirePoints(savepoints);
lineutility.InitializePOINT2Array(pts);
// draw line across back
pts[0] = new POINT2(savepoints[1]);
pts[1] = new POINT2(savepoints[2]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw perpendicular line
ptMid.x = (savepoints[1].x + savepoints[2].x) / 2;
ptMid.y = (savepoints[1].y + savepoints[2].y) / 2;
pts[0] = new POINT2(ptMid);
pts[1] = new POINT2(savepoints[0]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// draw arrowhead
iDiagEOL_length = ((Math.sqrt // height of graphic
(
(savepoints[1].x - savepoints[2].x) * (savepoints[1].x - savepoints[2].x) +
(savepoints[1].y - savepoints[2].y) * (savepoints[1].y - savepoints[2].y)) +
Math.sqrt // length of graphic
(
(savepoints[0].x - ptMid.x) * (savepoints[0].x - ptMid.x) +
(savepoints[0].y - ptMid.y) * (savepoints[0].y - ptMid.y))) / 20);
//if(iDiagEOL_length<10)
// iDiagEOL_length=10;
if ((double) iDiagEOL_length > maxLength/5) {
iDiagEOL_length = maxLength/5;
}
if ((double) iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
dAngle1 = Math.atan2(ptMid.y - savepoints[0].y, ptMid.x - savepoints[0].x);
iDeltaX1 = (Math.cos(dAngle1 + CONST_PI / 6) * iDiagEOL_length);
iDeltaY1 = (Math.sin(dAngle1 + CONST_PI / 6) * iDiagEOL_length);
iDeltaX2 = (Math.cos(dAngle1 - CONST_PI / 6) * iDiagEOL_length);
iDeltaY2 = (Math.sin(dAngle1 - CONST_PI / 6) * iDiagEOL_length);
pts[0].x = savepoints[0].x + iDeltaX1;
pts[0].y = savepoints[0].y + iDeltaY1;
pts[1] = new POINT2(savepoints[0]);
pts[2].x = savepoints[0].x + iDeltaX2;
pts[2].y = savepoints[0].y + iDeltaY2;
//DrawLine(destination, mask, color, pts, 3, 2);
for (j = 0; j < 3; j++) {
points[counter] = new POINT2(pts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
// draw lines on the back of the graphic
dAngle1 = Math.atan2(savepoints[1].y - savepoints[2].y, savepoints[1].x - savepoints[2].x);
iDeltaX1 = (Math.cos(dAngle1 - CONST_PI / 4) * iDiagEOL_length * 2);
iDeltaY1 = (Math.sin(dAngle1 - CONST_PI / 4) * iDiagEOL_length * 2);
iDeltaX2 = (Math.cos(dAngle1 + CONST_PI / 4) * iDiagEOL_length * 2);
iDeltaY2 = (Math.sin(dAngle1 + CONST_PI / 4) * iDiagEOL_length * 2);
pts[0].x = savepoints[1].x + iDeltaX1;
pts[0].y = savepoints[1].y + iDeltaY1;
pts[1] = new POINT2(savepoints[1]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
pts[0].x = savepoints[2].x - iDeltaX2;
pts[0].y = savepoints[2].y - iDeltaY2;
pts[1] = new POINT2(savepoints[2]);
//DrawLine(destination, mask, color, pts, 2, 2);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
//clean up
pts = null;
savepoints = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMAtkByFireDouble",
new RendererException("Failed inside GetDISMAtkByFireDouble", exc));
}
return counter;
}
/**
* Calculates the points for GAP
*
* @param points OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMGapDouble(POINT2[] points, int linetype) {
try {
POINT2[] savepoints = new POINT2[4];
POINT2[] pts = new POINT2[2];
int j = 0;
double dMBR = lineutility.MBRDistance(points, 4);
//end declarations
for (j = 0; j < 4; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(pts);
//M. Deutch 8-19-04
if (dMBR / 10 > maxLength) {
dMBR = 10 * maxLength;
}
if (dMBR / 10 < minLength) {
dMBR = 10 * minLength;
}
points[0] = new POINT2(savepoints[0]);
points[0].style = 0;
points[1] = new POINT2(savepoints[1]);
points[1].style = 5;
points[2] = new POINT2(savepoints[2]);
points[2].style = 0;
points[3] = new POINT2(savepoints[3]);
points[3].style = 5;
double dist = dMBR / 10;
if(dist>20)
dist=20;
double dist2 = dist;
switch (linetype) //change 1
{
case TacticalLines.BRIDGE:
dist = 1.5 * dist;
dist2 = dist / 2;
break;
default:
dist2 = dist;
break;
}
//get the extension point
pts[0] = lineutility.ExtendLineDouble(savepoints[1], savepoints[0], dist);
pts[1] = lineutility.ExtendLineDouble(savepoints[2], savepoints[0], dist2);
points[4] = new POINT2(points[0]);
points[4].style = 0;
points[5] = lineutility.MidPointDouble(pts[0], pts[1], 5);
//get the extension point
pts[0] = lineutility.ExtendLineDouble(savepoints[0], savepoints[1], dist);
pts[1] = lineutility.ExtendLineDouble(savepoints[3], savepoints[1], dist2);
points[6] = new POINT2(points[1]);
points[6].style = 0;
points[7] = lineutility.MidPointDouble(pts[0], pts[1], 5);
//get the extension point
pts[0] = lineutility.ExtendLineDouble(savepoints[0], savepoints[2], dist2);
pts[1] = lineutility.ExtendLineDouble(savepoints[3], savepoints[2], dist);
points[8] = new POINT2(points[2]);
points[8].style = 0;
points[9] = lineutility.MidPointDouble(pts[0], pts[1], 5);
//get the extension point
pts[0] = lineutility.ExtendLineDouble(savepoints[1], savepoints[3], dist2);
pts[1] = lineutility.ExtendLineDouble(savepoints[2], savepoints[3], dist);
points[10] = new POINT2(points[3]);
points[10].style = 0;
points[11] = lineutility.MidPointDouble(pts[0], pts[1], 5);
//clean up
pts = null;
savepoints = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMGapDouble",
new RendererException("Failed inside GetDISMGapDouble", exc));
}
return 12;
}
/**
* Calculates the points for DECEIVE.
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
// protected static void GetDISMDeceiveDouble(POINT2[] points,
// int linetype) {
// try {
// POINT2[] savepoints = new POINT2[3];
// int j = 0;
// for (j = 0; j < 3; j++) {
// savepoints[j] = new POINT2(points[j]);
// points[0] = new POINT2(savepoints[0]);
// points[0].style = 17;
// points[1] = new POINT2(savepoints[1]);
// points[1].style = 5;
// points[2] = new POINT2(savepoints[2]);
// points[2].style = 17;
// points[3] = new POINT2(savepoints[0]);
// points[3].style = 5;
// savepoints = null;
// //return;
// } catch (Exception e) {
// System.out.println(e.getMessage());
// return;
/**
* Calculates the points for MNFLDDIS
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMMinefieldDisruptDouble(POINT2[] points, int linetype) {
int counter=0;
try {
POINT2[] pts = new POINT2[2];
POINT2[] ptsArrow = new POINT2[3];
POINT2 ptCenter = new POINT2();
int j = 0;
POINT2[] savepoints = new POINT2[3];
double dAngle1 = 0, d = 0, dist = 0;
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
POINT2[] deltapoints3 = new POINT2[4];
double iDiagEOL_length = 0;
double iDeltaX1 = 0;
double iDeltaY1 = 0;
double iDeltaX2 = 0;
double iDeltaY2 = 0;
POINT2 ptTail = new POINT2();
//end declarations
for (j = 0; j < 3; j++) {
savepoints[j] = new POINT2(points[j]);
}
lineutility.InitializePOINT2Array(ptsArrow);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
lineutility.InitializePOINT2Array(deltapoints3);
lineutility.InitializePOINT2Array(pts);
points[counter] = new POINT2(savepoints[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 5;
counter++;
ptCenter.x = (savepoints[0].x + savepoints[1].x) / 2;
ptCenter.y = (savepoints[0].y + savepoints[1].y) / 2;
ptsArrow[0] = new POINT2(savepoints[2]);
ptsArrow[1].x = ptCenter.x + (savepoints[2].x - savepoints[0].x) * 4 / 5;
ptsArrow[1].y = ptCenter.y + (savepoints[2].y - savepoints[0].y) * 4 / 5;
ptsArrow[2].x = savepoints[1].x + (savepoints[2].x - savepoints[0].x) * 3 / 5;
ptsArrow[2].y = savepoints[1].y + (savepoints[2].y - savepoints[0].y) * 3 / 5;
points[counter] = new POINT2(savepoints[1]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(ptsArrow[2]);
points[counter].style = 5;
counter++;
pts[1] = new POINT2(ptsArrow[1]);
//draw middle line
points[counter] = new POINT2(ptCenter);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
//draw tail
//M. Deutch 8-19-04
dist = lineutility.CalcDistanceDouble(savepoints[2], savepoints[0]);
d = dist;
if (d > 5 * maxLength) {
d = 5 * maxLength;
}
if (d < 5 * minLength) {
d = 5 * minLength;
}
ptTail.x = (savepoints[0].x + ptCenter.x) / 2;
ptTail.y = (savepoints[0].y + ptCenter.y) / 2;
pts[0].x = ptTail.x - (savepoints[2].x - savepoints[0].x) / 5;
pts[0].y = ptTail.y - (savepoints[2].y - savepoints[0].y) / 5;
pts[0] = lineutility.ExtendLineDouble(pts[0], ptTail, -d / 5);
points[counter] = new POINT2(ptTail);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[0]);
points[counter].style = 5;
counter++;
pts[0] = new POINT2(savepoints[0]);
pts[1] = new POINT2(ptsArrow[0]);
points[counter] = new POINT2(pts[0]);
points[counter].style = 0;
counter++;
points[counter] = new POINT2(pts[1]);
points[counter].style = 5;
counter++;
// the following code is very similar to CalcEndpieceDeltas
iDiagEOL_length = ((Math.sqrt // height of graphic
(
(savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
(savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y)) +
Math.sqrt // length of graphic
(
(savepoints[2].x - savepoints[1].x) * (savepoints[2].x - savepoints[1].x) +
(savepoints[2].y - savepoints[1].y) * (savepoints[2].y - savepoints[1].y))) / 15);
// dAngle1 = angle used to calculate the end-piece deltas
//M. Deutch 8-19-04
if (iDiagEOL_length > maxLength) {
iDiagEOL_length = maxLength;
}
if (iDiagEOL_length < minLength) {
iDiagEOL_length = minLength;
}
dAngle1 = Math.atan2(savepoints[0].y - savepoints[2].y, savepoints[0].x - savepoints[2].x);
iDeltaX1 = (iDiagEOL_length * Math.cos(dAngle1 - CONST_PI / 6));
iDeltaY1 = (iDiagEOL_length * Math.sin(dAngle1 - CONST_PI / 6));
iDeltaX2 = (iDiagEOL_length * Math.cos(dAngle1 + CONST_PI / 6));
iDeltaY2 = (iDiagEOL_length * Math.sin(dAngle1 + CONST_PI / 6));
DrawEndpieceDeltasDouble(ptsArrow[0],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints1);
DrawEndpieceDeltasDouble(ptsArrow[1],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints2);
DrawEndpieceDeltasDouble(ptsArrow[2],
iDeltaX1, iDeltaY1, iDeltaX2, iDeltaY2, deltapoints3);
points[counter] = new POINT2(deltapoints1[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 10;
counter++;
points[counter] = new POINT2(deltapoints2[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 10;
counter++;
points[counter] = new POINT2(deltapoints3[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints3[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints3[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints3[3]);
points[counter].style = 10;
counter++;
//clean up
pts = null;
ptsArrow = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
deltapoints3 = null;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMMinefieldDisruptDouble",
new RendererException("Failed inside GetDISMMinefieldDisruptDouble", exc));
}
return counter;
}
/**
* Calculates the points for LINTGT
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
* @param vblCounter the number of points required to display the symbol
*/
protected static int GetDISMLinearTargetDouble(POINT2[] points, int linetype, int vblCounter) {
int counter = 0;
try {
int j = 0;
double dMBR = lineutility.MBRDistance(points, vblCounter-4);
//end declarations
//M. Deutch 8-19-04
if (dMBR / 20 > maxLength) {
dMBR = 20 * maxLength;
}
if (dMBR / 20 < minLength) {
dMBR = 20 * minLength;
}
if (dMBR < 150) {
dMBR = 150;
}
if(dMBR>250)
dMBR=250;
for (j = 0; j < vblCounter - 4; j++) {
points[counter].style = 0;
counter++;
}
//for(j=vblCounter-4;j<vblCounter;j++)
// points[j]=new POINT2();
points[counter - 1].style = 5;
points[counter] = lineutility.ExtendTrueLinePerpDouble(points[0], points[1], points[0], dMBR / 20, 0);
counter++;
points[counter] = lineutility.ExtendTrueLinePerpDouble(points[0], points[1], points[0], -dMBR / 20, 5);
counter++;
points[counter] = lineutility.ExtendTrueLinePerpDouble(points[vblCounter - 5], points[vblCounter - 6], points[vblCounter - 5], dMBR / 20, 0);
counter++;
points[counter] = lineutility.ExtendTrueLinePerpDouble(points[vblCounter - 5], points[vblCounter - 6], points[vblCounter - 5], -dMBR / 20, 5);
counter++;
if (linetype == (long) TacticalLines.FPF) {
points[0].style = 6;
}
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMLinearTargetDouble",
new RendererException("Failed inside GetDISMLinearTargetDouble", exc));
}
return counter;
}
/**
* Calculates the points for BLOCK, MNFLDBLK
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static void GetDISMBlockDouble2(POINT2[] points,
int linetype) {
try {
//diagnostic for CommandSight
//POINT2 ptRelative = lineutility.PointRelativeToLine(points[0], points[1], points[2]);
POINT2 ptRelative = new POINT2(points[2]);
POINT2 midpt = lineutility.MidPointDouble(points[0], points[1], 0);
int j = 0;
points[0].style = 0;
points[1].style = 5;
points[2] = new POINT2(midpt);
points[3] = new POINT2(ptRelative);
if (linetype == (long) TacticalLines.BLOCK) {
points[2].style = 14;
}
if (linetype == (long) TacticalLines.FPF) {
points[2].style = 6;
}
//for (j = 3; j < vblCounter; j++) {
// points[j].style = 5;
//return;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMBlockDouble2",
new RendererException("Failed inside GetDISMBlockDouble2", exc));
}
return;
}
/**
* Calculates the points for PAA_RECTANGULAR.
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static void GetDISMPAADouble(POINT2[] points, int linetype) {
try {
POINT2 pt0 = new POINT2(points[0]);
POINT2 pt1 = new POINT2(points[1]);
POINT2 pt2 = new POINT2();
POINT2 pt3 = new POINT2();
POINT2 midpt = new POINT2();
double d = lineutility.CalcDistanceDouble(pt0, pt1);
//end declarations
midpt = lineutility.MidPointDouble(pt0, pt1, 0);
pt2 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, d / 2, 0);
pt3 = lineutility.ExtendTrueLinePerpDouble(pt0, pt1, midpt, -d / 2, 0);
d = lineutility.CalcDistanceDouble(pt0, pt2);
points[0] = new POINT2(pt0);
points[0].style = 14;
points[1] = new POINT2(pt2);
points[1].style = 14;
points[2] = new POINT2(pt1);
points[2].style = 14;
points[3] = new POINT2(pt3);
points[3].style = 14;
points[4] = new POINT2(pt0);
points[4].style = 5;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMPAADouble",
new RendererException("Failed inside GetDISMPAADouble", exc));
}
return;
}
private static boolean ReverseDelayArc(POINT2[] points) {
try {
POINT2 pt1 = points[0];
POINT2 pt2 = points[1];
POINT2 pt3 = points[2];
float lineAngle = getAngleBetweenPoints(pt1.x, pt1.y, pt2.x, pt2.y);
float curveAngle = getAngleBetweenPoints(pt2.x, pt2.y, pt3.x, pt3.y);
float upperBound = curveAngle + 180;
return !isInRange(curveAngle, upperBound, lineAngle);
}
catch (Exception exc) {
ErrorLogger.LogException(_className ,"ReverseDelayArc",
new RendererException("Failed inside GetDelayArc", exc));
}
return false;
}
private static boolean isInRange(float min, float max, float targetAngle) {
targetAngle = normalizeAngle(targetAngle);
min = normalizeAngle(min);
max = normalizeAngle(max);
if (min < max) {
return min <= targetAngle && targetAngle <= max;
}
return min <= targetAngle || targetAngle <= max;
}
private static float getAngleBetweenPoints(double x1, double y1, double x2, double y2) {
return (float) Math.toDegrees(Math.atan2(y2 - y1, x2 - x1));
}
/**
* Returns an angle from 0 to 360
*
* @param angle the angle to normalize
* @return an angle in range from 0 to 360
*/
public static float normalizeAngle(float angle) {
return (3600000 + angle) % 360;
}
private static void DrawEndpieceDeltasDouble(POINT2 point,
double iDelta1,
double iDelta2,
double iDelta3,
double iDelta4,
POINT2[] deltapoints)
{
try
{
deltapoints[0] = new POINT2(point);
deltapoints[0].style = 0;
deltapoints[1].x = point.x + iDelta1;
deltapoints[1].y = point.y + iDelta2;
deltapoints[1].style = 5;
deltapoints[2] = new POINT2(point);
deltapoints[2].style = 0;
deltapoints[3].x = point.x + iDelta3;
deltapoints[3].y = point.y + iDelta4;
deltapoints[3].style = 5;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"DrawEndpieceDeltasDouble",
new RendererException("Failed inside DrawEndpieceDeltasDouble", exc));
}
}
/**
* Calculates the points for EASY
*
* @param points - OUT - the client points, also used for the returned points.
* @param linetype the line type.
*/
protected static int GetDISMEasyDouble(POINT2[] points,
int linetype) {
int counter = 0;
try {
int j = 0;
POINT2[] pointsCorner = new POINT2[2];
POINT2[] rectpts = new POINT2[4];
POINT2[] savepoints = new POINT2[3];
POINT2[] deltapoints1 = new POINT2[4];
POINT2[] deltapoints2 = new POINT2[4];
ref<double[]> iDeltaX = new ref(), iDeltaY = new ref();
int bPointsRight = 0;
//end declarations
for (j = 0; j < 3; j++) {
savepoints[j] = points[j];
}
lineutility.InitializePOINT2Array(pointsCorner);
lineutility.InitializePOINT2Array(rectpts);
lineutility.InitializePOINT2Array(deltapoints1);
lineutility.InitializePOINT2Array(deltapoints2);
DrawOpenRectangleDouble(savepoints, pointsCorner, rectpts);
for (j = 0; j < 4; j++) {
points[counter] = new POINT2(rectpts[j]);
points[counter].style = 0;
counter++;
}
points[counter - 1].style = 5;
bPointsRight = DetermineDirectionDouble(savepoints);
CalcEndpieceDeltasDouble(savepoints, iDeltaX, iDeltaY, CONST_PI / 4);
if ((savepoints[0].y - savepoints[1].y) < 0) {// Point0 is higher than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
}
} else {// Point0 is lower than Point1
if (bPointsRight != 0) {// figure opens to the right
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaY.value[0], -iDeltaX.value[0], iDeltaX.value[0], iDeltaY.value[0], deltapoints2);
} else {// figure opens to the left
DrawEndpieceDeltasDouble(savepoints[0],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints1);
DrawEndpieceDeltasDouble(savepoints[1],
iDeltaX.value[0], iDeltaY.value[0], iDeltaY.value[0], -iDeltaX.value[0], deltapoints2);
}
}
points[counter] = new POINT2(deltapoints1[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints1[3]);
points[counter].style = 10;
counter++;
points[counter] = new POINT2(deltapoints2[1]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[0]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 9;
counter++;
points[counter] = new POINT2(deltapoints2[3]);
points[counter].style = 10;
counter++;
//clean up
pointsCorner = null;
rectpts = null;
savepoints = null;
deltapoints1 = null;
deltapoints2 = null;
} catch (Exception exc) {
ErrorLogger.LogException(_className ,"GetDISMEasyDouble",
new RendererException("Failed inside GetDISMEasyDouble", exc));
}
return counter;
}
/**
* Calculates the points for AMBUSH
*
* @param pLinePoints - OUT - the client points, also used for the returned points.
*/
protected static int AmbushPointsDouble(POINT2[] pLinePoints)
{
int counter=0;
try
{
POINT2[] pts=new POINT2[3];
POINT2[] savepoints=new POINT2[3];
// calculate midpoint
POINT2 ptMid=new POINT2();
double dRadius=0,d=0;
double dAngle1=0;
double dAngle1c=0;
double dAngle2c=0;
double dAngle12c=0;
double dAngle0=0;
POINT2[] arcpoints=new POINT2[17];
double dAngleTic = 0;
double dDeltaX1=0, dDeltaY1=0;
double dDeltaX2 = 0;
double dDeltaY2 = 0;
POINT2 ptCenter=new POINT2();
int j=0,i=0;
double iArrowLength=0;
for(j=0;j<3;j++)
{
savepoints[j]=new POINT2(pLinePoints[j]);
}
//initialize the pOINT2 arrays
lineutility.InitializePOINT2Array(arcpoints);
lineutility.InitializePOINT2Array(pts);
ptMid.x = (savepoints[1].x + savepoints[2].x) / 2;
ptMid.y = (savepoints[1].y + savepoints[2].y) / 2;
// calculate arc center
dRadius = Math.sqrt( (ptMid.x-savepoints[2].x) * (ptMid.x-savepoints[2].x) +
(ptMid.y-savepoints[2].y) * (ptMid.y-savepoints[2].y) );
// add section M. Deutch 8-25-05
//consider the other possiblity for a center
double dRadius2 = Math.sqrt( (ptMid.x-savepoints[1].x) * (ptMid.x-savepoints[1].x) +
(ptMid.y-savepoints[1].y) * (ptMid.y-savepoints[1].y) );
dAngle1 = Math.atan2(savepoints[1].y - savepoints[2].y, savepoints[1].x - savepoints[2].x);
ptCenter.x = ptMid.x + Math.cos(dAngle1 - CONST_PI / 2) * dRadius;
ptCenter.y = ptMid.y + Math.sin(dAngle1 - CONST_PI / 2) * dRadius;
//added section M. Deutch 8-25-05
//consider the other possibility for a center if the points were reversed
double dAngle2 = Math.atan2(savepoints[2].y - savepoints[1].y, savepoints[2].x - savepoints[1].x);
POINT2 ptCenter2=new POINT2();
ptCenter2.x = ptMid.x + Math.cos(dAngle2 - CONST_PI / 2) * dRadius;
ptCenter2.y = ptMid.y + Math.sin(dAngle2 - CONST_PI / 2) * dRadius;
double dist=lineutility.CalcDistanceDouble(savepoints[0],ptCenter);
double dist2=lineutility.CalcDistanceDouble(savepoints[0],ptCenter2);
//if the distance to the new center is closer
//then reverse the arc endpoints
if(dist2>dist)
{
//POINT2 ptTemp=new POINT2();
POINT2 ptTemp=new POINT2(savepoints[1]);
savepoints[1]=new POINT2(savepoints[2]);
savepoints[2]=new POINT2(ptTemp);
ptCenter=new POINT2(ptCenter2);
dAngle1=dAngle2;
}
//end section
dRadius = Math.sqrt ( (savepoints[1].x-ptCenter.x) * (savepoints[1].x-ptCenter.x) +
(savepoints[1].y-ptCenter.y) * (savepoints[1].y-ptCenter.y) );
// draw arc
ArcApproximationDouble ((ptCenter.x - dRadius),(ptCenter.y - dRadius),
(ptCenter.x + dRadius),( ptCenter.y + dRadius),
savepoints[2].x, savepoints[2].y, savepoints[1].x, savepoints[1].y, arcpoints);
for(j=0;j<17;j++)
{
pLinePoints[counter]=new POINT2(arcpoints[j]);
pLinePoints[counter].style=0;
counter++;
}
pLinePoints[counter-1].style=5;
// draw line out from arc to point 1
pts[0] = new POINT2(savepoints[0]);
dAngle1c = Math.atan2(ptCenter.y - savepoints[1].y, ptCenter.x - savepoints[1].x);
dAngle2c = Math.atan2(ptCenter.y - savepoints[2].y, ptCenter.x - savepoints[2].x);
// dAngle1c = atan2(ptCenter.y - savepoints[1].y, ptCenter.x - savepoints[1].x);
// dAngle2c = atan2(ptCenter.y - savepoints[2].y, ptCenter.x - savepoints[2].x);
dAngle12c = (dAngle1c + dAngle2c) / 2;
if ( (dAngle1c > 0) && (dAngle2c < 0) )
{
pts[1].x = ptCenter.x + Math.cos(dAngle12c) * dRadius;
pts[1].y = ptCenter.y + Math.sin(dAngle12c) * dRadius;
}
else
{
pts[1].x = ptCenter.x - Math.cos(dAngle12c) * dRadius;
pts[1].y = ptCenter.y - Math.sin(dAngle12c) * dRadius;
}
//DrawLine(destination, mask, color, pts, 2, 2);
pLinePoints[counter]=new POINT2(pts[0]);
pLinePoints[counter].style=0;counter++;
pLinePoints[counter]=new POINT2(pts[1]);
pLinePoints[counter].style=5;counter++;
// draw arrowhead on end of line
dAngle0 = Math.atan2(pts[1].y - savepoints[0].y, pts[1].x - savepoints[0].x);
// dAngle0 = atan2(pts[1].y - savepoints[0].y, pts[1].x - savepoints[0].x);
iArrowLength =(
(
Math.sqrt // height of graphic
(
(savepoints[1].x-savepoints[2].x) * (savepoints[1].x-savepoints[2].x) +
(savepoints[1].y-savepoints[2].y) * (savepoints[1].y-savepoints[2].y)
) +
Math.sqrt // length of graphic
(
(savepoints[0].x-ptMid.x) * (savepoints[0].x-ptMid.x) +
(savepoints[0].y-ptMid.y) * (savepoints[0].y-ptMid.y)
)
) / 20);
if((double)iArrowLength>maxLength)
iArrowLength=(int)maxLength;
if((double)iArrowLength<minLength)
iArrowLength=(int)minLength;
pts[0].x = savepoints[0].x + Math.cos(dAngle0 + CONST_PI / 6) * iArrowLength;
pts[0].y = savepoints[0].y + Math.sin(dAngle0 + CONST_PI / 6) * iArrowLength;
pts[1] = savepoints[0];
pts[2].x = savepoints[0].x + Math.cos(dAngle0 - CONST_PI / 6) * iArrowLength;
pts[2].y = savepoints[0].y + Math.sin(dAngle0 - CONST_PI / 6) * iArrowLength;
for(j=0;j<3;j++)
{
pLinePoints[counter]=new POINT2(pts[j]);
pLinePoints[counter].style=0;
counter++;
}
pLinePoints[counter-1].style=5;
// DrawLine(destination, mask, color, pts, 3, 2);
// draw lines out from arc toward back of graphic
//M. Deutch 8-19-04
d=dRadius/3;
if(d>maxLength)
d=maxLength;
if(d<minLength)
d=minLength;
dAngleTic = CONST_PI / 18; // angle in radians between tic-marks
//dDeltaX2 = Math.Cos(dAngle1 + CONST_PI / 2) * dRadius / 3;
//dDeltaY2 = Math.Sin(dAngle1 + CONST_PI / 2) * dRadius / 3;
dDeltaX2 = Math.cos(dAngle1 + CONST_PI / 2) * d;
dDeltaY2 = Math.sin(dAngle1 + CONST_PI / 2) * d;
for (i=0; i<8; i++)
{
dAngle1c += dAngleTic;
dDeltaX1 = Math.cos(dAngle1c) * dRadius;
dDeltaY1 = Math.sin(dAngle1c) * dRadius;
pts[0].x = ptCenter.x - dDeltaX1;
pts[0].y = ptCenter.y - dDeltaY1;
pLinePoints[counter]=new POINT2(pts[0]);
pLinePoints[counter].style=0;
counter++;
pts[1].x = pts[0].x - dDeltaX2;
pts[1].y = pts[0].y - dDeltaY2;
pLinePoints[counter]=new POINT2(pts[1]);
pLinePoints[counter].style=5;
counter++;
//DrawLine(destination, mask, color, pts, 2, 2);
}
//FillPoints(pLinePoints,counter);
//clean up
pts=null;
savepoints=null;
arcpoints=null;
}
catch(Exception exc)
{
ErrorLogger.LogException(_className ,"AmbushPointsDouble",
new RendererException("Failed inside AmbushPointsDouble", exc));
}
return counter;
}
}
|
package org.jboss.planet.util;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StringToolsTest {
@Test
public void testIsEmpty() {
}
@Test
public void testSafeToString() {
}
@Test
public void testConvertTitleToLink() {
}
@Test
public void testStripHtml() {
assertEquals("Some text.", StringTools.stripHtml("<p>Some text.</p>"));
assertEquals("This: < shouldn't get removed.", StringTools.stripHtml("This: < shouldn't get removed."));
assertEquals("Non-terminated tags. And now this!. >",
StringTools.stripHtml("<p>Non-terminated tags. <a> And now this!. >"));
assertEquals("Tags with spaces, and some not terminated .",
StringTools.stripHtml("<p > Tags with spaces, and some <a > not terminated </a>."));
assertEquals(
"Escaped characters within PRE",
StringTools
.stripHtml("<pre><pool> Escaped characters within PRE <allow-multiple-users/></pool></pre>"));
}
@Test
public void testIsValidXml() {
}
@Test
public void testCheckAndFixHtml() {
assertEquals("<div><p></p></div>", StringTools.checkAndFixHtml("<div><p></div></p>", true));
assertEquals("<p>Some text.</p>\n", StringTools.checkAndFixHtml("<p>Some text.</p>\n", true));
assertEquals("<p><i>Some text.</i>\n</p>\n", StringTools.checkAndFixHtml("<p><i>Some text.</i>\n</p>\n", true));
assertEquals("Some text.", StringTools.checkAndFixHtml("Some text.", true));
final String scriptTagTest = "<script src=\"https://gist.github.com/2343383.js?file=nQueensScoreRules\"></script>";
assertEquals(scriptTagTest, StringTools.checkAndFixHtml(scriptTagTest, true));
// TODO: Check why this test fails on Openshift Jenkins instance
// assertEquals("Special characters: \u03C0", StringTools.checkAndFixHtml("Special characters: \u03C0", true));
}
@Test
public void testCreateSummary() {
}
@Test
public void testEscape() {
}
@Test
public void testUnescapeDoubleEscapedString() {
}
}
|
// LeicaReader.java
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.AxisGuesser;
import loci.formats.CoreMetadata;
import loci.formats.FilePattern;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.TiffConstants;
import loci.formats.tiff.TiffParser;
import ome.xml.model.enums.Correction;
import ome.xml.model.enums.Immersion;
import ome.xml.model.primitives.PositiveInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LeicaReader extends FormatReader {
// -- Constants -
private static final Logger LOGGER =
LoggerFactory.getLogger(LeicaReader.class);
public static final String[] LEI_SUFFIX = {"lei"};
/** All Leica TIFFs have this tag. */
private static final int LEICA_MAGIC_TAG = 33923;
/** Format for dates. */
private static final String DATE_FORMAT = "yyyy:MM:dd,HH:mm:ss:SSS";
/** IFD tags. */
private static final Integer SERIES = new Integer(10);
private static final Integer IMAGES = new Integer(15);
private static final Integer DIMDESCR = new Integer(20);
private static final Integer FILTERSET = new Integer(30);
private static final Integer TIMEINFO = new Integer(40);
private static final Integer SCANNERSET = new Integer(50);
private static final Integer EXPERIMENT = new Integer(60);
private static final Integer LUTDESC = new Integer(70);
private static final Integer CHANDESC = new Integer(80);
private static final Integer SEQUENTIALSET = new Integer(90);
private static final Integer SEQ_SCANNERSET = new Integer(200);
private static final Integer SEQ_FILTERSET = new Integer(700);
private static final int SEQ_SCANNERSET_END = 300;
private static final int SEQ_FILTERSET_END = 800;
private static final Hashtable<String, Integer> CHANNEL_PRIORITIES =
createChannelPriorities();
private static Hashtable<String, Integer> createChannelPriorities() {
Hashtable<String, Integer> h = new Hashtable<String, Integer>();
h.put("red", new Integer(0));
h.put("green", new Integer(1));
h.put("blue", new Integer(2));
h.put("cyan", new Integer(3));
h.put("magenta", new Integer(4));
h.put("yellow", new Integer(5));
h.put("black", new Integer(6));
h.put("gray", new Integer(7));
h.put("", new Integer(8));
return h;
}
private static final Hashtable<Integer, String> DIMENSION_NAMES =
makeDimensionTable();
// -- Fields --
protected IFDList ifds;
/** Array of IFD-like structures containing metadata. */
protected IFDList headerIFDs;
/** Helper readers. */
protected MinimalTiffReader tiff;
/** Array of image file names. */
protected Vector[] files;
/** Number of series in the file. */
private int numSeries;
/** Name of current LEI file */
private String leiFilename;
/** Length of each file name. */
private int fileLength;
private boolean[] valid;
private String[][] timestamps;
private Vector<String> seriesNames;
private Vector<String> seriesDescriptions;
private int lastPlane = 0, nameLength = 0;
private double[][] physicalSizes;
private double[] pinhole, exposureTime;
private int nextDetector = 0, nextChannel = 0;
private Vector<Integer> activeChannelIndices = new Vector<Integer>();
private boolean sequential = false;
private Vector[] channelNames;
private Vector[] emWaves;
private Vector[] exWaves;
private boolean[][] cutInPopulated;
private boolean[][] cutOutPopulated;
private boolean[][] filterRefPopulated;
private Double detectorOffset, detectorVoltage;
private int[] tileWidth, tileHeight;
// -- Constructor --
/** Constructs a new Leica reader. */
public LeicaReader() {
super("Leica", new String[] {"lei", "tif", "tiff", "raw"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, LEI_SUFFIX)) return true;
if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES) &&
!checkSuffix(name, "raw"))
{
return false;
}
if (!open) return false; // not allowed to touch the file system
// check for that there is an .lei file in the same directory
String prefix = name;
if (prefix.indexOf(".") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
Location lei = new Location(prefix + ".lei");
if (!lei.exists()) {
lei = new Location(prefix + ".LEI");
while (!lei.exists() && prefix.indexOf("_") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
lei = new Location(prefix + ".lei");
if (!lei.exists()) lei = new Location(prefix + ".LEI");
}
}
return lei.exists();
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
return ifd.containsKey(new Integer(LEICA_MAGIC_TAG));
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
try {
int index = (int) Math.min(lastPlane, files[series].size() - 1);
tiff.setId((String) files[series].get(index));
return tiff.get8BitLookupTable();
}
catch (FormatException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
catch (IOException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
return null;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
try {
int index = (int) Math.min(lastPlane, files[series].size() - 1);
tiff.setId((String) files[series].get(index));
return tiff.get16BitLookupTable();
}
catch (FormatException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
catch (IOException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
return null;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
lastPlane = no;
int fileIndex = no < files[series].size() ? no : 0;
int planeIndex = no < files[series].size() ? 0 : no;
String filename = (String) files[series].get(fileIndex);
if (new Location(filename).exists()) {
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
tiff.setId(filename);
return tiff.openBytes(planeIndex, buf, x, y, w, h);
}
else {
RandomAccessInputStream s = new RandomAccessInputStream(filename);
s.seek(planeIndex * FormatTools.getPlaneSize(this));
readPlane(s, x, y, w, h, buf);
s.close();
}
}
// imitate Leica's software and return a blank plane if the
// appropriate TIFF file is missing
return buf;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> v = new Vector<String>();
if (leiFilename != null) v.add(leiFilename);
if (!noPixels && files != null) {
for (Object file : files[getSeries()]) {
if (file != null && new Location((String) file).exists()) {
v.add((String) file);
}
}
}
return v.toArray(new String[v.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (tiff != null) tiff.close(fileOnly);
if (!fileOnly) {
leiFilename = null;
files = null;
ifds = headerIFDs = null;
tiff = null;
seriesNames = null;
numSeries = 0;
lastPlane = 0;
physicalSizes = null;
seriesDescriptions = null;
pinhole = exposureTime = null;
nextDetector = 0;
nextChannel = 0;
sequential = false;
activeChannelIndices.clear();
channelNames = null;
emWaves = null;
exWaves = null;
cutInPopulated = null;
cutOutPopulated = null;
filterRefPopulated = null;
}
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
if (tileWidth[getSeries()] != 0) {
return tileWidth[getSeries()];
}
return super.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
if (tileHeight[getSeries()] != 0) {
return tileHeight[getSeries()];
}
return super.getOptimalTileHeight();
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
close();
String leiFile = findLEIFile(id);
if (leiFile == null || leiFile.trim().length() == 0 ||
new Location(leiFile).isDirectory())
{
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
super.initFile(id);
TiffReader r = new TiffReader();
r.setMetadataStore(getMetadataStore());
r.setId(id);
core = r.getCoreMetadata();
metadataStore = r.getMetadataStore();
Hashtable globalMetadata = r.getGlobalMetadata();
for (Object key : globalMetadata.keySet()) {
addGlobalMeta(key.toString(), globalMetadata.get(key));
}
r.close();
files = new Vector[] {new Vector()};
files[0].add(id);
tiff = new MinimalTiffReader();
return;
}
else {
throw new FormatException("LEI file not found.");
}
}
// parse the LEI file
super.initFile(leiFile);
leiFilename =
new File(leiFile).exists()? new Location(leiFile).getAbsolutePath() : id;
in = new RandomAccessInputStream(leiFile);
MetadataLevel metadataLevel = metadataOptions.getMetadataLevel();
seriesNames = new Vector<String>();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core[0].littleEndian = (fourBytes[0] == TiffConstants.LITTLE &&
fourBytes[1] == TiffConstants.LITTLE &&
fourBytes[2] == TiffConstants.LITTLE &&
fourBytes[3] == TiffConstants.LITTLE);
boolean realLittleEndian = isLittleEndian();
in.order(isLittleEndian());
LOGGER.info("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
headerIFDs = new IFDList();
while (addr != 0) {
IFD ifd = new IFD();
headerIFDs.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
ifd.putIFDValue(tag, in.getFilePointer());
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = headerIFDs.size();
tileWidth = new int[numSeries];
tileHeight = new int[numSeries];
core = new CoreMetadata[numSeries];
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
}
files = new Vector[numSeries];
channelNames = new Vector[getSeriesCount()];
emWaves = new Vector[getSeriesCount()];
exWaves = new Vector[getSeriesCount()];
cutInPopulated = new boolean[getSeriesCount()][];
cutOutPopulated = new boolean[getSeriesCount()][];
filterRefPopulated = new boolean[getSeriesCount()][];
for (int i=0; i<getSeriesCount(); i++) {
channelNames[i] = new Vector();
emWaves[i] = new Vector();
exWaves[i] = new Vector();
}
// determine the length of a filename
LOGGER.info("Parsing metadata blocks");
core[0].littleEndian = !isLittleEndian();
int seriesIndex = 0;
int invalidCount = 0;
valid = new boolean[numSeries];
timestamps = new String[headerIFDs.size()][];
for (int i=0; i<headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
valid[i] = true;
if (ifd.get(SERIES) != null) {
long offset = ((Long) ifd.get(SERIES)).longValue();
in.seek(offset + 8);
nameLength = in.readInt() * 2;
}
in.seek(((Long) ifd.get(IMAGES)).longValue());
parseFilenames(i);
if (!valid[i]) invalidCount++;
}
numSeries -= invalidCount;
int[] count = new int[getSeriesCount()];
for (int i=0; i<getSeriesCount(); i++) {
count[i] = core[i].imageCount;
}
Vector[] tempFiles = files;
IFDList tempIFDs = headerIFDs;
core = new CoreMetadata[numSeries];
files = new Vector[numSeries];
headerIFDs = new IFDList();
int index = 0;
for (int i=0; i<numSeries; i++) {
core[i] = new CoreMetadata();
while (!valid[index]) index++;
core[i].imageCount = count[index];
files[i] = tempFiles[index];
Object[] sorted = files[i].toArray();
Arrays.sort(sorted);
files[i].clear();
files[i].addAll(Arrays.asList(sorted));
headerIFDs.add(tempIFDs.get(index));
index++;
}
tiff = new MinimalTiffReader();
LOGGER.info("Populating metadata");
if (headerIFDs == null) headerIFDs = ifds;
seriesDescriptions = new Vector<String>();
physicalSizes = new double[headerIFDs.size()][5];
pinhole = new double[headerIFDs.size()];
exposureTime = new double[headerIFDs.size()];
for (int i=0; i<headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
core[i].littleEndian = isLittleEndian();
setSeries(i);
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
for (Integer key : keys) {
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
if (key.equals(SERIES)) {
parseSeriesTag();
}
else if (key.equals(IMAGES)) {
parseImageTag(i);
}
else if (key.equals(DIMDESCR)) {
parseDimensionTag(i);
}
else if (key.equals(TIMEINFO) && metadataLevel != MetadataLevel.MINIMUM)
{
parseTimeTag(i);
}
else if (key.equals(EXPERIMENT) &&
metadataLevel != MetadataLevel.MINIMUM)
{
parseExperimentTag();
}
else if (key.equals(LUTDESC)) {
parseLUT(i);
}
else if (key.equals(CHANDESC) && metadataLevel != MetadataLevel.MINIMUM)
{
parseChannelTag();
}
}
core[i].orderCertain = true;
core[i].littleEndian = isLittleEndian();
core[i].falseColor = true;
core[i].metadataComplete = true;
core[i].interleaved = false;
String filename = (String) files[i].get(0);
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
tiff.setId(filename);
core[i].sizeX = tiff.getSizeX();
core[i].sizeY = tiff.getSizeY();
tileWidth[i] = tiff.getOptimalTileWidth();
tileHeight[i] = tiff.getOptimalTileHeight();
}
}
for (int i=0; i<numSeries; i++) {
setSeries(i);
if (getSizeZ() == 0) core[i].sizeZ = 1;
if (getSizeT() == 0) core[i].sizeT = 1;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getImageCount() == 0) core[i].imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
core[i].sizeZ = 1;
core[i].sizeT = 1;
}
if (getSizeY() == 1 || getSizeY() == getSizeZ() ||
getSizeY() == getSizeT())
{
// XZ or XT scan
if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) {
core[i].sizeY = getSizeZ();
core[i].sizeZ = 1;
}
else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) {
core[i].sizeY = getSizeT();
core[i].sizeT = 1;
}
}
if (isRGB()) core[i].indexed = false;
core[i].dimensionOrder =
MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
core[i].littleEndian = realLittleEndian;
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// Ensure we populate Image names before returning due to a possible
// minimum metadata level.
for (int i=0; i<numSeries;i ++) {
store.setImageName(seriesNames.get(i), i);
}
if (metadataLevel == MetadataLevel.MINIMUM) return;
for (int i=0; i<numSeries; i++) {
IFD ifd = headerIFDs.get(i);
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null &&
timestamps[i].length > 0)
{
firstPlane = DateTools.getTime(timestamps[i][0], DATE_FORMAT);
store.setImageAcquiredDate(
DateTools.formatDate(timestamps[i][0], DATE_FORMAT), i);
}
else {
MetadataTools.setDefaultCreationDate(store, id, i);
}
store.setImageDescription(seriesDescriptions.get(i), i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
// parse instrument data
nextDetector = 0;
nextChannel = 0;
cutInPopulated[i] = new boolean[core[i].sizeC];
cutOutPopulated[i] = new boolean[core[i].sizeC];
filterRefPopulated[i] = new boolean[core[i].sizeC];
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
int nextInstrumentBlock = 1;
sequential = DataTools.indexOf(keys, SEQ_SCANNERSET) != -1;
for (Integer key : keys) {
if (key.equals(FILTERSET) || key.equals(SCANNERSET) ||
key.equals(SEQ_SCANNERSET) || key.equals(SEQ_FILTERSET) ||
(key > SEQ_SCANNERSET && key < SEQ_SCANNERSET_END) ||
(key > SEQ_FILTERSET && key < SEQ_FILTERSET_END))
{
if (sequential && (key.equals(FILTERSET) || key.equals(SCANNERSET))) {
continue;
}
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
setSeries(i);
parseInstrumentData(store, nextInstrumentBlock++);
}
}
activeChannelIndices.clear();
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
store.setPixelsPhysicalSizeX(physicalSizes[i][0], i);
store.setPixelsPhysicalSizeY(physicalSizes[i][1], i);
store.setPixelsPhysicalSizeZ(physicalSizes[i][2], i);
if ((int) physicalSizes[i][4] > 0) {
store.setPixelsTimeIncrement(physicalSizes[i][4], i);
}
for (int j=0; j<core[i].imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
long time = DateTools.getTime(timestamps[i][j], DATE_FORMAT);
double elapsedTime = (double) (time - firstPlane) / 1000;
store.setPlaneDeltaT(elapsedTime, i, j);
store.setPlaneExposureTime(exposureTime[i], i, j);
}
}
}
setSeries(0);
}
// -- Helper methods --
/** Find the .lei file that belongs to the same dataset as the given file. */
private String findLEIFile(String baseFile)
throws FormatException, IOException
{
if (checkSuffix(baseFile, LEI_SUFFIX)) {
return baseFile;
}
else if (checkSuffix(baseFile, TiffReader.TIFF_SUFFIXES) && isGroupFiles())
{
// need to find the associated .lei file
if (ifds == null) super.initFile(baseFile);
in = new RandomAccessInputStream(baseFile);
TiffParser tp = new TiffParser(in);
in.order(tp.checkHeader().booleanValue());
in.seek(0);
LOGGER.info("Finding companion file name");
// open the TIFF file and look for the "Image Description" field
ifds = tp.getIFDs();
if (ifds == null) throw new FormatException("No IFDs found");
String descr = ifds.get(0).getComment();
// remove anything of the form "[blah]"
descr = descr.replaceAll("\\[.*.\\]\n", "");
// each remaining line in descr is a (key, value) pair,
// where '=' separates the key from the value
String lei =
baseFile.substring(0, baseFile.lastIndexOf(File.separator) + 1);
StringTokenizer lines = new StringTokenizer(descr, "\n");
String line = null, key = null, value = null;
while (lines.hasMoreTokens()) {
line = lines.nextToken();
if (line.indexOf("=") == -1) continue;
key = line.substring(0, line.indexOf("=")).trim();
value = line.substring(line.indexOf("=") + 1).trim();
addGlobalMeta(key, value);
if (key.startsWith("Series Name")) lei += value;
}
// now open the LEI file
Location l = new Location(lei).getAbsoluteFile();
if (l.exists()) {
return lei;
}
else {
if (!lei.endsWith("lei") && !lei.endsWith("LEI")) {
lei = lei.substring(0, lei.lastIndexOf(".") + 1);
String test = lei + "lei";
if (new Location(test).exists()) {
return test;
}
test = lei + "LEI";
if (new Location(test).exists()) {
return test;
}
}
l = l.getParentFile();
String[] list = l.list();
for (int i=0; i<list.length; i++) {
if (checkSuffix(list[i], LEI_SUFFIX)) {
return new Location(l.getAbsolutePath(), list[i]).getAbsolutePath();
}
}
}
}
else if (checkSuffix(baseFile, "raw") && isGroupFiles()) {
// check for that there is an .lei file in the same directory
String prefix = baseFile;
if (prefix.indexOf(".") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
Location lei = new Location(prefix + ".lei");
if (!lei.exists()) {
lei = new Location(prefix + ".LEI");
while (!lei.exists() && prefix.indexOf("_") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
lei = new Location(prefix + ".lei");
if (!lei.exists()) lei = new Location(prefix + ".LEI");
}
}
if (lei.exists()) return lei.getAbsolutePath();
}
return null;
}
private void parseFilenames(int seriesIndex) throws IOException {
int maxPlanes = 0;
Vector<String> f = new Vector<String>();
int tempImages = in.readInt();
if (((long) tempImages * nameLength) > in.length()) {
in.order(!isLittleEndian());
tempImages = in.readInt();
in.order(isLittleEndian());
}
core[seriesIndex].sizeX = in.readInt();
core[seriesIndex].sizeY = in.readInt();
in.skipBytes(4);
int samplesPerPixel = in.readInt();
core[seriesIndex].rgb = samplesPerPixel > 1;
core[seriesIndex].sizeC = samplesPerPixel;
File dirFile = new File(currentId).getAbsoluteFile();
String[] listing = null;
String dirPrefix = "";
if (dirFile.exists()) {
listing = dirFile.getParentFile().list();
dirPrefix = dirFile.getParent();
if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator;
}
else {
listing = Location.getIdMap().keySet().toArray(new String[0]);
}
Vector<String> list = new Vector<String>();
for (int k=0; k<listing.length; k++) {
if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) {
list.add(listing[k]);
}
}
boolean tiffsExist = false;
String prefix = "";
for (int j=0; j<tempImages; j++) {
// read in each filename
prefix = getString(nameLength);
f.add(dirPrefix + prefix);
// test to make sure the path is valid
Location test = new Location(f.get(f.size() - 1)).getAbsoluteFile();
LOGGER.debug("Expected to find TIFF file {}", test.getAbsolutePath());
if (!test.exists()) {
LOGGER.debug(" file does not exist");
}
if (test.exists()) list.remove(prefix);
if (!tiffsExist) tiffsExist = test.exists();
}
// all of the TIFF files were renamed
if (!tiffsExist) {
// Strategy for handling renamed files:
// 1) Assume that files for each series follow a pattern.
// 2) Assign each file group to the first series with the correct count.
LOGGER.info("Handling renamed TIFF files");
listing = list.toArray(new String[list.size()]);
// grab the file patterns
Vector<String> filePatterns = new Vector<String>();
for (String q : listing) {
Location l = new Location(dirPrefix, q).getAbsoluteFile();
FilePattern pattern = new FilePattern(l);
if (!pattern.isValid()) continue;
AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
String fp = pattern.getPattern();
if (guess.getAxisCountS() >= 1) {
String pre = pattern.getPrefix(guess.getAxisCountS());
Vector<String> fileList = new Vector<String>();
for (int n=0; n<listing.length; n++) {
Location p = new Location(dirPrefix, listing[n]);
if (p.getAbsolutePath().startsWith(pre)) {
fileList.add(listing[n]);
}
}
fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix,
fileList.toArray(new String[fileList.size()]));
}
if (fp != null && !filePatterns.contains(fp)) {
filePatterns.add(fp);
}
}
for (String q : filePatterns) {
String[] pattern = new FilePattern(q).getFiles();
if (pattern.length == tempImages) {
// make sure that this pattern hasn't already been used
boolean validPattern = true;
for (int n=0; n<seriesIndex; n++) {
if (files[n] == null) continue;
if (files[n].contains(pattern[0])) {
validPattern = false;
break;
}
}
if (validPattern) {
files[seriesIndex] = new Vector<String>();
files[seriesIndex].addAll(Arrays.asList(pattern));
}
}
}
}
else files[seriesIndex] = f;
if (files[seriesIndex] == null) valid[seriesIndex] = false;
else {
core[seriesIndex].imageCount = files[seriesIndex].size();
maxPlanes = (int) Math.max(maxPlanes, core[seriesIndex].imageCount);
}
}
private void parseSeriesTag() throws IOException {
addSeriesMeta("Version", in.readInt());
addSeriesMeta("Number of Series", in.readInt());
fileLength = in.readInt();
addSeriesMeta("Length of filename", fileLength);
int extLen = in.readInt();
if (extLen > fileLength) {
in.seek(8);
core[0].littleEndian = !isLittleEndian();
in.order(isLittleEndian());
fileLength = in.readInt();
extLen = in.readInt();
}
addSeriesMeta("Length of file extension", extLen);
addSeriesMeta("Image file extension", getString(extLen));
}
private void parseImageTag(int seriesIndex) throws IOException {
core[seriesIndex].imageCount = in.readInt();
core[seriesIndex].sizeX = in.readInt();
core[seriesIndex].sizeY = in.readInt();
addSeriesMeta("Number of images", getImageCount());
addSeriesMeta("Image width", getSizeX());
addSeriesMeta("Image height", getSizeY());
addSeriesMeta("Bits per Sample", in.readInt());
addSeriesMeta("Samples per pixel", in.readInt());
String name = getString(fileLength * 2);
if (name.indexOf(".") != -1) {
name = name.substring(0, name.lastIndexOf("."));
}
String[] tokens = name.split("_");
StringBuffer buf = new StringBuffer();
for (int p=1; p<tokens.length; p++) {
String lcase = tokens[p].toLowerCase();
if (!lcase.startsWith("ch0") && !lcase.startsWith("c0") &&
!lcase.startsWith("z0") && !lcase.startsWith("t0"))
{
if (buf.length() > 0) buf.append("_");
buf.append(tokens[p]);
}
}
seriesNames.add(buf.toString());
}
private void parseDimensionTag(int seriesIndex)
throws FormatException, IOException
{
addSeriesMeta("Voxel Version", in.readInt());
core[seriesIndex].rgb = in.readInt() == 20;
addSeriesMeta("VoxelType", isRGB() ? "RGB" : "gray");
int bpp = in.readInt();
addSeriesMeta("Bytes per pixel", bpp);
if (bpp % 3 == 0) {
core[seriesIndex].sizeC = 3;
core[seriesIndex].rgb = true;
bpp /= 3;
}
core[seriesIndex].pixelType =
FormatTools.pixelTypeFromBytes(bpp, false, false);
core[seriesIndex].dimensionOrder = "XY";
int resolution = in.readInt();
core[seriesIndex].bitsPerPixel = resolution;
addSeriesMeta("Real world resolution", resolution);
addSeriesMeta("Maximum voxel intensity", getString(true));
addSeriesMeta("Minimum voxel intensity", getString(true));
int len = in.readInt();
in.skipBytes(len * 2 + 4);
len = in.readInt();
for (int j=0; j<len; j++) {
int dimId = in.readInt();
String dimType = DIMENSION_NAMES.get(new Integer(dimId));
if (dimType == null) dimType = "";
int size = in.readInt();
int distance = in.readInt();
int strlen = in.readInt() * 2;
String[] sizeData = getString(strlen).split(" ");
String physicalSize = sizeData[0];
String unit = "";
if (sizeData.length > 1) unit = sizeData[1];
double physical = Double.parseDouble(physicalSize) / size;
if (unit.equals("m")) {
physical *= 1000000;
}
if (dimType.equals("x")) {
core[seriesIndex].sizeX = size;
physicalSizes[seriesIndex][0] = physical;
}
else if (dimType.equals("y")) {
core[seriesIndex].sizeY = size;
physicalSizes[seriesIndex][1] = physical;
}
else if (dimType.equals("channel")) {
if (getSizeC() == 0) core[seriesIndex].sizeC = 1;
core[seriesIndex].sizeC *= size;
if (getDimensionOrder().indexOf("C") == -1) {
core[seriesIndex].dimensionOrder += "C";
}
physicalSizes[seriesIndex][3] = physical;
}
else if (dimType.equals("z")) {
core[seriesIndex].sizeZ = size;
if (getDimensionOrder().indexOf("Z") == -1) {
core[seriesIndex].dimensionOrder += "Z";
}
physicalSizes[seriesIndex][2] = physical;
}
else {
core[seriesIndex].sizeT = size;
if (getDimensionOrder().indexOf("T") == -1) {
core[seriesIndex].dimensionOrder += "T";
}
physicalSizes[seriesIndex][4] = physical;
}
String dimPrefix = "Dim" + j;
addSeriesMeta(dimPrefix + " type", dimType);
addSeriesMeta(dimPrefix + " size", size);
addSeriesMeta(dimPrefix + " distance between sub-dimensions",
distance);
addSeriesMeta(dimPrefix + " physical length",
physicalSize + " " + unit);
addSeriesMeta(dimPrefix + " physical origin", getString(true));
}
addSeriesMeta("Series name", getString(false));
String description = getString(false);
seriesDescriptions.add(description);
addSeriesMeta("Series description", description);
}
private void parseTimeTag(int seriesIndex) throws IOException {
int nDims = in.readInt();
addSeriesMeta("Number of time-stamped dimensions", nDims);
addSeriesMeta("Time-stamped dimension", in.readInt());
for (int j=0; j<nDims; j++) {
String dimPrefix = "Dimension " + j;
addSeriesMeta(dimPrefix + " ID", in.readInt());
addSeriesMeta(dimPrefix + " size", in.readInt());
addSeriesMeta(dimPrefix + " distance", in.readInt());
}
int numStamps = in.readInt();
addSeriesMeta("Number of time-stamps", numStamps);
timestamps[seriesIndex] = new String[numStamps];
for (int j=0; j<numStamps; j++) {
timestamps[seriesIndex][j] = getString(64);
addSeriesMeta("Timestamp " + j, timestamps[seriesIndex][j]);
}
if (in.getFilePointer() < in.length()) {
int numTMs = in.readInt();
addSeriesMeta("Number of time-markers", numTMs);
for (int j=0; j<numTMs; j++) {
if (in.getFilePointer() + 4 >= in.length()) break;
int numDims = in.readInt();
String time = "Time-marker " + j + " Dimension ";
for (int k=0; k<numDims; k++) {
if (in.getFilePointer() + 4 < in.length()) {
addSeriesMeta(time + k + " coordinate", in.readInt());
}
else break;
}
if (in.getFilePointer() >= in.length()) break;
addSeriesMeta("Time-marker " + j, getString(64));
}
}
}
private void parseExperimentTag() throws IOException {
in.skipBytes(8);
String description = getString(true);
addSeriesMeta("Image Description", description);
addSeriesMeta("Main file extension", getString(true));
addSeriesMeta("Image format identifier", getString(true));
addSeriesMeta("Single image extension", getString(true));
}
private void parseLUT(int seriesIndex) throws IOException {
int nChannels = in.readInt();
if (nChannels > 0) core[seriesIndex].indexed = true;
addSeriesMeta("Number of LUT channels", nChannels);
addSeriesMeta("ID of colored dimension", in.readInt());
for (int j=0; j<nChannels; j++) {
String p = "LUT Channel " + j;
addSeriesMeta(p + " version", in.readInt());
addSeriesMeta(p + " inverted?", in.read() == 1);
addSeriesMeta(p + " description", getString(false));
addSeriesMeta(p + " filename", getString(false));
String lut = getString(false);
addSeriesMeta(p + " name", lut);
in.skipBytes(8);
}
}
private void parseChannelTag() throws IOException {
int nBands = in.readInt();
for (int band=0; band<nBands; band++) {
String p = "Band #" + (band + 1) + " ";
addSeriesMeta(p + "Lower wavelength", in.readDouble());
in.skipBytes(4);
addSeriesMeta(p + "Higher wavelength", in.readDouble());
in.skipBytes(4);
addSeriesMeta(p + "Gain", in.readDouble());
addSeriesMeta(p + "Offset", in.readDouble());
}
}
private void parseInstrumentData(MetadataStore store, int blockNum)
throws FormatException, IOException
{
int series = getSeries();
// read 24 byte SAFEARRAY
in.skipBytes(4);
int cbElements = in.readInt();
in.skipBytes(8);
int nElements = in.readInt();
in.skipBytes(4);
long initialOffset = in.getFilePointer();
long elementOffset = 0;
LOGGER.trace("Element LOOP; series {} at offset", series, initialOffset);
for (int j=0; j<nElements; j++) {
elementOffset = initialOffset + j * cbElements;
LOGGER.trace("Seeking to: {}", elementOffset);
in.seek(elementOffset);
String contentID = getString(128);
LOGGER.trace("contentID: {}", contentID);
String description = getString(64);
LOGGER.trace("description: {}", description);
String data = getString(64);
int dataType = in.readShort();
LOGGER.trace("dataType: {}", dataType);
in.skipBytes(6);
// read data
switch (dataType) {
case 2:
data = String.valueOf(in.readShort());
break;
case 3:
data = String.valueOf(in.readInt());
break;
case 4:
data = String.valueOf(in.readFloat());
break;
case 5:
data = String.valueOf(in.readDouble());
break;
case 7:
case 11:
data = in.read() == 0 ? "false" : "true";
break;
case 17:
data = in.readString(1);
break;
}
LOGGER.trace("data: {}", data);
if (data.trim().length() == 0) {
LOGGER.trace("Zero length dat string, continuing...");
continue;
}
String[] tokens = contentID.split("\\|");
LOGGER.trace("Parsing tokens: {}", tokens);
if (tokens[0].startsWith("CDetectionUnit")) {
// detector information
if (tokens[1].startsWith("PMT")) {
try {
if (tokens[2].equals("VideoOffset")) {
detectorOffset = new Double(data);
}
else if (tokens[2].equals("HighVoltage")) {
detectorVoltage = new Double(data);
nextDetector++;
}
else if (tokens[2].equals("State")) {
// link Detector to Image, if the detector was actually used
if (data.equals("Active")) {
store.setDetectorOffset(detectorOffset, series, nextDetector);
store.setDetectorVoltage(detectorVoltage, series, nextDetector);
store.setDetectorType(
getDetectorType("PMT"), series, nextDetector);
String index = tokens[1].substring(tokens[1].indexOf(" ") + 1);
int channelIndex = -1;
try {
channelIndex = Integer.parseInt(index) - 1;
}
catch (NumberFormatException e) { }
if (channelIndex >= 0) {
activeChannelIndices.add(new Integer(channelIndex));
}
String detectorID =
MetadataTools.createLSID("Detector", series, nextDetector);
store.setDetectorID(detectorID, series, nextDetector);
if (nextDetector == 0) {
// link every channel to the first detector in the beginning
// if additional detectors are found, the links will be
// overwritten
for (int c=0; c<getEffectiveSizeC(); c++) {
store.setDetectorSettingsID(detectorID, series, c);
}
}
if (nextChannel < getEffectiveSizeC()) {
store.setDetectorSettingsID(
detectorID, series, nextChannel++);
}
}
}
}
catch (NumberFormatException e) {
LOGGER.debug("Failed to parse detector metadata", e);
}
}
}
else if (tokens[0].startsWith("CTurret")) {
// objective information
int objective = Integer.parseInt(tokens[3]);
if (tokens[2].equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(data), series, objective);
}
else if (tokens[2].equals("Objective")) {
String[] objectiveData = data.split(" ");
StringBuffer model = new StringBuffer();
String mag = null, na = null;
String immersion = null, correction = null;
for (int i=0; i<objectiveData.length; i++) {
if (objectiveData[i].indexOf("x") != -1 && mag == null &&
na == null)
{
int xIndex = objectiveData[i].indexOf("x");
mag = objectiveData[i].substring(0, xIndex).trim();
na = objectiveData[i].substring(xIndex + 1).trim();
}
else if (mag == null && na == null) {
model.append(objectiveData[i]);
model.append(" ");
}
else if (correction == null) {
correction = objectiveData[i];
}
else if (immersion == null) {
immersion = objectiveData[i];
}
}
if (immersion != null) immersion = immersion.trim();
if (correction != null) correction = correction.trim();
Correction realCorrection = getCorrection(correction);
Correction testCorrection = getCorrection(immersion);
Immersion realImmersion = getImmersion(immersion);
Immersion testImmersion = getImmersion(correction);
// Correction and Immersion are reversed
if ((testCorrection != Correction.OTHER &&
realCorrection == Correction.OTHER) ||
(testImmersion != Immersion.OTHER &&
realImmersion == Immersion.OTHER))
{
String tmp = correction;
correction = immersion;
immersion = tmp;
}
store.setObjectiveImmersion(
getImmersion(immersion), series, objective);
store.setObjectiveCorrection(
getCorrection(correction), series, objective);
store.setObjectiveModel(model.toString().trim(), series, objective);
store.setObjectiveLensNA(new Double(na), series, objective);
store.setObjectiveNominalMagnification(new PositiveInteger((int)
Double.parseDouble(mag)), series, objective);
}
else if (tokens[2].equals("OrderNumber")) {
store.setObjectiveSerialNumber(data, series, objective);
}
else if (tokens[2].equals("RefractionIndex")) {
store.setImageObjectiveSettingsRefractiveIndex(
new Double(data), series);
}
// link Objective to Image
String objectiveID =
MetadataTools.createLSID("Objective", series, objective);
store.setObjectiveID(objectiveID, series, objective);
if (objective == 0) {
store.setImageObjectiveSettingsID(objectiveID, series);
}
}
else if (tokens[0].startsWith("CSpectrophotometerUnit")) {
int ndx = tokens[1].lastIndexOf(" ");
int channel = Integer.parseInt(tokens[1].substring(ndx + 1)) - 1;
if (tokens[2].equals("Wavelength")) {
Integer wavelength = new Integer((int) Double.parseDouble(data));
store.setFilterModel(tokens[1], series, channel);
String filterID = MetadataTools.createLSID("Filter", series, channel);
store.setFilterID(filterID, series, channel);
int index = activeChannelIndices.indexOf(new Integer(channel));
if (index >= 0 && index < core[series].sizeC) {
if (!filterRefPopulated[series][index]) {
store.setLightPathEmissionFilterRef(filterID, series, index, 0);
filterRefPopulated[series][index] = true;
}
if (tokens[3].equals("0") && !cutInPopulated[series][index]) {
store.setTransmittanceRangeCutIn(
new PositiveInteger(wavelength), series, channel);
cutInPopulated[series][index] = true;
}
else if (tokens[3].equals("1") && !cutOutPopulated[series][index]) {
store.setTransmittanceRangeCutOut(
new PositiveInteger(wavelength), series, channel);
cutOutPopulated[series][index] = true;
}
}
}
else if (tokens[2].equals("Stain")) {
if (activeChannelIndices.contains(new Integer(channel))) {
int nNames = channelNames[series].size();
String prevValue = nNames == 0 ? "" :
(String) channelNames[series].get(nNames - 1);
if (!prevValue.equals(data)) {
channelNames[series].add(data);
}
}
}
}
else if (tokens[0].startsWith("CXYZStage")) {
// NB: there is only one stage position specified for each series
if (tokens[2].equals("XPos")) {
for (int q=0; q<core[series].imageCount; q++) {
store.setPlanePositionX(new Double(data), series, q);
if (q == 0) {
addGlobalMeta("X position for position #" + (series + 1), data);
}
}
}
else if (tokens[2].equals("YPos")) {
for (int q=0; q<core[series].imageCount; q++) {
store.setPlanePositionY(new Double(data), series, q);
if (q == 0) {
addGlobalMeta("Y position for position #" + (series + 1), data);
}
}
}
else if (tokens[2].equals("ZPos")) {
for (int q=0; q<core[series].imageCount; q++) {
store.setPlanePositionZ(new Double(data), series, q);
if (q == 0) {
addGlobalMeta("Z position for position #" + (series + 1), data);
}
}
}
}
else if (tokens[0].equals("CScanActuator") &&
tokens[1].equals("Z Scan Actuator") && tokens[2].equals("Position"))
{
double pos = Double.parseDouble(data) * 1000000;
for (int q=0; q<core[series].imageCount; q++) {
store.setPlanePositionZ(pos, series, q);
}
}
if (contentID.equals("dblVoxelX")) {
physicalSizes[series][0] = Double.parseDouble(data);
}
else if (contentID.equals("dblVoxelY")) {
physicalSizes[series][1] = Double.parseDouble(data);
}
else if (contentID.equals("dblStepSize")) {
double size = Double.parseDouble(data);
if (size > 0) {
physicalSizes[series][2] = size;
}
}
else if (contentID.equals("dblPinhole")) {
// pinhole is stored in meters
pinhole[series] = Double.parseDouble(data) * 1000000;
}
else if (contentID.startsWith("nDelayTime")) {
exposureTime[series] = Double.parseDouble(data);
if (contentID.endsWith("_ms")) {
exposureTime[series] /= 1000;
}
}
addSeriesMeta("Block " + blockNum + " " + contentID, data);
}
// populate saved LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int channel=0; channel<getEffectiveSizeC(); channel++) {
if (channel < channelNames[i].size()) {
String name = (String) channelNames[i].get(channel);
if (name != null && !name.trim().equals("") && !name.equals("None")) {
store.setChannelName(name, i, channel);
}
}
if (channel < emWaves[i].size()) {
Integer wave = new Integer(emWaves[i].get(channel).toString());
store.setChannelEmissionWavelength(
new PositiveInteger(wave), i, channel);
}
if (channel < exWaves[i].size()) {
Integer wave = new Integer(exWaves[i].get(channel).toString());
store.setChannelExcitationWavelength(
new PositiveInteger(wave), i, channel);
}
if (i < pinhole.length) {
store.setChannelPinholeSize(new Double(pinhole[i]), i, channel);
}
}
}
setSeries(0);
}
private boolean usedFile(String s) {
if (files == null) return false;
for (int i=0; i<files.length; i++) {
if (files[i] == null) continue;
for (int j=0; j<files[i].size(); j++) {
if (((String) files[i].get(j)).endsWith(s)) return true;
}
}
return false;
}
private String getString(int len) throws IOException {
return DataTools.stripString(in.readString(len));
}
private String getString(boolean doubleLength) throws IOException {
int len = in.readInt();
if (doubleLength) len *= 2;
return getString(len);
}
private static Hashtable<Integer, String> makeDimensionTable() {
Hashtable<Integer, String> table = new Hashtable<Integer, String>();
table.put(new Integer(0), "undefined");
table.put(new Integer(120), "x");
table.put(new Integer(121), "y");
table.put(new Integer(122), "z");
table.put(new Integer(116), "t");
table.put(new Integer(6815843), "channel");
table.put(new Integer(6357100), "wave length");
table.put(new Integer(7602290), "rotation");
table.put(new Integer(7798904), "x-wide for the motorized xy-stage");
table.put(new Integer(7798905), "y-wide for the motorized xy-stage");
table.put(new Integer(7798906), "z-wide for the z-stage-drive");
table.put(new Integer(4259957), "user1 - unspecified");
table.put(new Integer(4325493), "user2 - unspecified");
table.put(new Integer(4391029), "user3 - unspecified");
table.put(new Integer(6357095), "graylevel");
table.put(new Integer(6422631), "graylevel1");
table.put(new Integer(6488167), "graylevel2");
table.put(new Integer(6553703), "graylevel3");
table.put(new Integer(7864398), "logical x");
table.put(new Integer(7929934), "logical y");
table.put(new Integer(7995470), "logical z");
table.put(new Integer(7602254), "logical t");
table.put(new Integer(7077966), "logical lambda");
table.put(new Integer(7471182), "logical rotation");
table.put(new Integer(5767246), "logical x-wide");
table.put(new Integer(5832782), "logical y-wide");
table.put(new Integer(5898318), "logical z-wide");
return table;
}
}
|
package com.deuteriumlabs.dendrite.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Projection;
import com.google.appengine.api.datastore.PropertyProjection;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Text;
/**
* Represents a page of a story. <code>StoryPage</code> instances act as nodes
* in a tree to form a complete story. The unordered nature of the page IDs of
* the pages in a story causes the branches of different stories to be
* interwoven.
*/
public class StoryPage extends Model {
private static final String ELLIPSIS = "…";
private static final int MAX_SUMMARY_LEN = 30;
private static final char ANCESTRY_DELIMITER = '>';
private static final String ANCESTRY_PROPERTY = "ancestry";
private static final String AUTHOR_ID_PROPERTY = "authorId";
private static final String AUTHOR_NAME_PROPERTY = "authorName";
private static final String BEGINNING_NUMBER_PROPERTY = "beginningNumber";
private static final String BEGINNING_VERSION_PROPERTY = "beginningVersion";
private static final String FORMERLY_LOVING_USERS_PROPERTY = "formerlyLovingUsers";
private static final String ID_NUMBER_PROPERTY = "idNumber";
private static final String ID_VERSION_PROPERTY = "idVersion";
private static final String KIND_NAME = "StoryPage";
private static final int LEN_ALPHABET = 26;
private static final char[] LETTERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z' };
private static final String LOVING_USERS_PROPERTY = "lovingUsers";
private static final String TAGS_PROPERTY = "tags";
private static final String TEXT_PROPERTY = "text";
private static final int SIZE_INFLUENCE = 1;
private static final int LOVE_INFLUENCE = 1;
private static final String IS_FIRST_PG_PROPERTY = "isFirstPg";
public static String convertNumberToVersion(final int num) {
final int lowNum = ((num - 1) % LEN_ALPHABET) + 1;
final char lowLetter = convertNumToLetter(lowNum);
final int highNums = (num - 1) / LEN_ALPHABET;
String versionStr = Character.toString(lowLetter);
if (highNums > 0) {
final String highLetters = convertNumberToVersion(highNums);
versionStr = highLetters + versionStr;
}
return versionStr;
}
public static int countAllPagesWrittenBy(final String authorId) {
final Query query = new Query(KIND_NAME);
final Filter filter = getAuthorIdFilter(authorId);
query.setFilter(filter);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
return preparedQuery.countEntities(fetchOptions);
}
public static int countAllPgs() {
final Query query = new Query(KIND_NAME);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
return preparedQuery.countEntities(fetchOptions);
}
public static int countFirstPgsMatchingTag(final String tag) {
final PreparedQuery preparedQuery =
getPreparedQueryForFirstPgsMatchingTag(tag);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
return preparedQuery.countEntities(fetchOptions);
}
// TODO(Matt Heard): Clarify names of 'greater' and 'less' variables.
public static int countLoversBetween(final String greater, final String less) {
final Query query = new Query(KIND_NAME);
Class<String> type = String.class;
String projectionProperty = LOVING_USERS_PROPERTY;
final PropertyProjection projection;
projection = new PropertyProjection(projectionProperty, type);
query.addProjection(projection);
final String propertyName = ANCESTRY_PROPERTY;
FilterOperator operator = FilterOperator.GREATER_THAN;
String value = greater;
final Filter greaterFilter;
greaterFilter = new FilterPredicate(propertyName, operator, value);
operator = FilterOperator.LESS_THAN;
value = less;
final Filter lessFilter;
lessFilter = new FilterPredicate(propertyName, operator, value);
final Filter filter;
filter = CompositeFilterOperator.and(greaterFilter, lessFilter);
query.setFilter(filter);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
final List<Entity> entities = preparedQuery.asList(fetchOptions);
int count = 0;
for (final Entity entity : entities) {
final String loverId;
loverId = (String) entity.getProperty(projectionProperty);
if (loverId != null && loverId.equals("") == false) {
count++;
}
}
return count;
}
public static int countVersions(final int num) {
final Query query = new Query(KIND_NAME);
final Filter filter = getIdNumFilter(num);
query.setFilter(filter);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
return preparedQuery.countEntities(fetchOptions);
}
public static List<StoryPage> getAllVersions(final PageId pageId) {
final Query query = new Query(KIND_NAME);
final int num = pageId.getNumber();
final Filter filter = StoryPage.getIdNumFilter(num);
query.setFilter(filter);
DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
final List<Entity> entities = preparedQuery.asList(fetchOptions);
final List<StoryPage> pages = getPgsFromEntities(entities);
return pages;
}
public static List<StoryPage> getFirstPgsMatchingTag(final String tag) {
final PreparedQuery preparedQuery =
getPreparedQueryForFirstPgsMatchingTag(tag);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
final List<Entity> entities = preparedQuery.asList(fetchOptions);
final List<StoryPage> pgs = new ArrayList<StoryPage>();
for (final Entity entity : entities) {
final StoryPage pg = new StoryPage(entity);
pgs.add(pg);
}
return pgs;
}
public static List<StoryPage> getPagesWrittenBy(String authorId, int start,
int end) {
final Query query = new Query(KIND_NAME);
query.addSort(BEGINNING_NUMBER_PROPERTY);
query.addSort(ID_NUMBER_PROPERTY);
query.addSort(ID_VERSION_PROPERTY);
final Filter filter = getAuthorIdFilter(authorId);
query.setFilter(filter);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final int limit = end - start;
final FetchOptions fetchOptions = FetchOptions.Builder.withLimit(limit);
final int offset = start;
fetchOptions.offset(offset);
List<Entity> entities = preparedQuery.asList(fetchOptions);
List<StoryPage> pgs = getPgsFromEntities(entities);
return pgs;
}
/**
* @param pageId
* @return
*/
public static StoryPage getParentOf(final PageId childId) {
childId.setVersion("a");
final StoryPage child = new StoryPage();
child.setId(childId);
child.read();
return child.getParent();
}
public static String getRandomVersion(final PageId id) {
id.setVersion("a");
final StoryPage pg = new StoryPage();
pg.setId(id);
pg.read();
if (pg.isInStore() == true) {
final long denominator = pg.calculateChanceDenominator();
Random generator = new Random();
int randomNum = generator.nextInt((int) denominator) + 1;
while (randomNum >= 0) {
final long numerator = pg.calculateChanceNumerator();
randomNum -= numerator;
if (randomNum >= 0) {
pg.incrementVersion();
}
}
final String version = pg.getId().getVersion();
return version;
} else {
return "a";
}
}
private static char convertNumToLetter(int num) {
Map<Integer, Character> map = new HashMap<Integer, Character>();
for (int i = 0; i < LETTERS.length; i++)
map.put(i + 1, LETTERS[i]);
return map.get(num);
}
private static int countLoversOfAllVersions(final int pgNum) {
final Query query = new Query(KIND_NAME);
Projection loversProjection;
String propertyName = LOVING_USERS_PROPERTY;
loversProjection = new PropertyProjection(propertyName, String.class);
query.addProjection(loversProjection);
FilterPredicate filter;
filter = Query.FilterOperator.EQUAL.of(ID_NUMBER_PROPERTY, pgNum);
query.setFilter(filter);
final DatastoreService store = getStore();
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
final List<Entity> entities = store.prepare(query).asList(fetchOptions);
int count = 0;
for (final Entity entity : entities) {
if (entity.getProperty(LOVING_USERS_PROPERTY) != null) {
count++;
}
}
return count;
}
private static Filter getAuthorIdFilter(String authorId) {
final String propertyName = AUTHOR_ID_PROPERTY;
final FilterOperator operator = FilterOperator.EQUAL;
final String value = authorId;
return new FilterPredicate(propertyName, operator, value);
}
/**
* Builds a filter to restrict a query to a particular ID.
*
* @param id
* The page ID to filter for
* @return The filter to apply to the query
*/
private static Filter getIdFilter(final PageId id) {
final int num = id.getNumber();
final Filter numFilter = getIdNumFilter(num);
final String version = id.getVersion();
final Filter versionFilter = getIdVersionFilter(version);
return CompositeFilterOperator.and(numFilter, versionFilter);
}
/**
* Builds a filter to restrict a query to a particular ID number. Without
* also applying a filter to restrict to a particular ID version, this will
* provide a collection of versions of one page in a story.
*
* @param num
* The page number to filter for
* @return The filter to apply to the query
*/
private static Filter getIdNumFilter(final int num) {
final String propertyName = ID_NUMBER_PROPERTY;
final FilterOperator operator = FilterOperator.EQUAL;
final int value = num;
return new FilterPredicate(propertyName, operator, value);
}
/**
* Returns the number component of the story page ID from the given entity.
*
* @param entity
* The entity containing the ID
* @return The number component of the story page ID
*/
private static int getIdNumFromEntity(final Entity entity) {
final Long num = (Long) entity.getProperty(ID_NUMBER_PROPERTY);
return num.intValue();
}
/**
* Builds a filter to restrict a query to a particular ID version. This will
* probably not be very useful without other query filters.
*
* @param version
* The page version to filter for
* @return The filter to apply to the query
*/
private static Filter getIdVersionFilter(final String version) {
final String propertyName = ID_VERSION_PROPERTY;
final FilterOperator operator = FilterOperator.EQUAL;
final String value = version;
return new FilterPredicate(propertyName, operator, value);
}
/**
* Returns the version component of the story page ID from the given entity.
*
* @param entity
* The entity containing the ID
* @return The version component of the story page ID
*/
private static String getIdVersionFromEntity(final Entity entity) {
return (String) entity.getProperty(ID_VERSION_PROPERTY);
}
private static List<StoryPage> getPgsFromEntities(
final List<Entity> entities) {
final List<StoryPage> pgs = new ArrayList<StoryPage>();
for (final Entity entity : entities) {
StoryPage pg = new StoryPage(entity);
pgs.add(pg);
}
return pgs;
}
private static PreparedQuery getPreparedQueryForFirstPgsMatchingTag(
final String tag) {
final Query query = new Query(KIND_NAME);
String propertyName = IS_FIRST_PG_PROPERTY;
FilterOperator operator = FilterOperator.EQUAL;
final Filter isFirstPgFilter;
isFirstPgFilter = new FilterPredicate(propertyName, operator, true);
propertyName = TAGS_PROPERTY;
final String propertyVal = tag;
final Filter tagFilter;
tagFilter = new FilterPredicate(propertyName, operator, propertyVal);
final Filter filter;
filter = CompositeFilterOperator.and(isFirstPgFilter, tagFilter);
query.setFilter(filter);
query.addSort(ID_NUMBER_PROPERTY);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
return preparedQuery;
}
/**
* @param greater
* @param less
* @return
*/
static int countSubtreeBetween(final String greater, final String less) {
final Query query = new Query(KIND_NAME);
final String propertyName = ANCESTRY_PROPERTY;
FilterOperator operator = FilterOperator.GREATER_THAN;
// TODO(Matt Heard) Clarify names of 'greater' and 'less' variables.
String value = greater;
final Filter greaterFilter;
greaterFilter = new FilterPredicate(propertyName, operator, value);
operator = FilterOperator.LESS_THAN;
value = less;
final Filter lessFilter;
lessFilter = new FilterPredicate(propertyName, operator, value);
final Filter filter;
filter = CompositeFilterOperator.and(greaterFilter, lessFilter);
query.setFilter(filter);
final DatastoreService store = getStore();
final PreparedQuery preparedQuery = store.prepare(query);
final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
return preparedQuery.countEntities(fetchOptions);
}
private List<PageId> ancestry;
private String authorId;
private String authorName;
private PageId beginning;
private String chance;
private List<String> formerlyLovingUsers;
private PageId id;
private List<String> lovingUsers;
private StoryPage parent;
private List<String> tags;
private Text text;
private boolean isFirstPg;
public StoryPage() {
this.setBeginning(null);
}
public StoryPage(final Entity entity) {
this.readPropertiesFromEntity(entity);
}
public boolean addTag(final String tag) {
final List<String> tags = this.getTags();
final boolean isDuplicate = tags.contains(tag);
if (isDuplicate == false) {
tags.add(tag);
this.setTags(tags);
return true;
} else {
return false;
}
}
@Override
public void create() {
this.generateAncestry();
this.determineWhetherFirstPg();
super.create();
}
public void determineWhetherFirstPg() {
final PageId beginningId = this.getBeginning();
final int beginningNum = beginningId.getNumber();
final PageId pgId = this.getId();
final int pgNum = pgId.getNumber();
final boolean isFirstPg = (beginningNum == pgNum);
this.setFirstPg(isFirstPg);
}
public void generateAncestry() {
final StoryPage parent = this.getParent();
final List<PageId> ancestry;
if (parent != null) {
parent.read();
ancestry = parent.getAncestry();
} else {
ancestry = new ArrayList<PageId>();
}
final PageId id = this.getId();
ancestry.add(id);
this.setAncestry(ancestry);
}
/**
* @return ancestry The list of pages that lead to this page.
*/
public List<PageId> getAncestry() {
return this.ancestry;
}
public String getAuthorId() {
return this.authorId;
}
public String getAuthorName() {
return this.authorName;
}
public PageId getBeginning() {
return this.beginning;
}
/**
* @return
*/
public String getChance() {
if (this.chance == null) {
this.calculateChance();
}
return this.chance;
}
/**
* @return
*/
public List<String> getFormerlyLovingUsers() {
return this.formerlyLovingUsers;
}
/**
* Returns the ID of this story page.
*
* @return The ID of this story page
*/
public PageId getId() {
return id;
}
public String getLongSummary() {
final Text text = this.getText();
if (text != null) {
final String full = text.getValue();
return summarise(full, 100);
} else {
return "This page has not been written yet.";
}
}
/**
* @return
*/
public List<String> getLovingUsers() {
return this.lovingUsers;
}
/**
* @return
*/
public int getNumLovingUsers() {
final List<String> lovingUsers = this.getLovingUsers();
return lovingUsers.size();
}
/**
* @return
*/
public StoryPage getParent() {
return this.parent;
}
public String getSummary() {
final Text text = this.getText();
final String full = text.getValue();
return summarise(full, MAX_SUMMARY_LEN);
}
public List<String> getTags() {
if (this.tags == null) {
this.initTags();
}
return this.tags;
}
/**
* Returns the text of this story page.
*
* @return The text of this story page
*/
public Text getText() {
return this.text;
}
public boolean isFirstPg() {
return this.isFirstPg;
}
/**
* @param userId
* @return
*/
public boolean isLovedBy(final String userId) {
final List<String> lovingUsers = this.getLovingUsers();
return lovingUsers.contains(userId);
}
public boolean removeTag(final String tag) {
final List<String> tags = this.getTags();
boolean isUpdateNeeded = false;
while (tags.contains(tag)) {
tags.remove(tag);
isUpdateNeeded = true;
}
if (isUpdateNeeded) {
this.setTags(tags);
return true;
} else {
return false;
}
}
public void setAuthorId(final String authorId) {
this.authorId = authorId;
}
public void setAuthorName(final String authorName) {
this.authorName = authorName;
}
public void setBeginning(PageId beginning) {
this.beginning = beginning;
}
/**
* @param users
*/
public void setFormerlyLovingUsers(final List<String> users) {
this.formerlyLovingUsers = users;
}
/**
* Sets the ID of this story page.
*
* @param id
* The new ID for this story page
*/
public void setId(final PageId id) {
this.id = id;
final PageId beginning = this.getBeginning();
if (beginning == null) {
this.setBeginning(id);
}
}
/**
* @param lovingUsers
*/
public void setLovingUsers(final List<String> lovingUsers) {
this.lovingUsers = lovingUsers;
}
public void setParent(final StoryPage parent) {
this.parent = parent;
}
/**
* Sets the text of this story page.
*
* @param string
* The new text for this story page
*/
public void setText(final String string) {
final Text text = new Text(string);
this.setText(text);
}
public void setText(final Text text) {
this.text = text;
}
@Override
public String toString() {
final PageId id = this.getId();
final String summary = this.getText().toString();
return "{ " + id + ": " + summary + " }";
}
/**
* The chance of a page being displayed is determined by two factors:
*
* (1) the size of its subtree, which is measured by counting all of its
* descendants, and
*
* (2) its number of lovers.
*
* Each factor is calculated as a fraction of two integers and are each
* multiplied by a constant representing how influential each factor is upon
* the total weight.
*
* For example, a page has 3 children while all alternatives have 8
* children. This produces a chance of 3/8 from the size of its subtree. The
* page also has 10 lovers while all alternatives have 15 lovers. This
* produces a chance of 10/15 from the lovers. In this example, the subtree
* size accounts for 6/10 of the total weight, while the lovers accounts for
* 4/10 of the total weight. The total weight can then be calculated by
* summing the product of each factor by how influential it is:
*
* (3/8 * 600/1000) + (10/15 * 400/1000)
*
* = ((3 * 600 * 15) + (10 * 400 * 8) ) / (8 * 15 * 1000)
*
* = 0.49166666666
*
* This example page would have a 49% chance of being displayed.
*/
private void calculateChance() {
final long numerator = this.calculateChanceNumerator();
final long denominator = this.calculateChanceDenominator();
this.setChance(numerator + "/" + denominator);
}
/**
* @return
*/
private long calculateChanceDenominator() {
final int sizeDenominator = this.getSizeDenominator();
final int sizeInfluence = this.getSizeInfluence();
final int loveDenominator = this.getLoveDenominator();
final int loveInfluence = this.getLoveInfluence();
return (sizeDenominator * sizeInfluence)
+ (loveDenominator * loveInfluence);
}
/**
* @return
*/
private int calculateChanceNumerator() {
final int sizeNumerator = this.getSizeNumerator();
final int sizeInfluence = this.getSizeInfluence();
final int loveNumerator = this.getLoveNumerator();
final int loveInfluence = this.getLoveInfluence();
return (sizeNumerator * sizeInfluence)
+ (loveNumerator + loveInfluence);
}
/**
* @param entity
* @return
*/
private List<PageId> getAncestryFromEntity(final Entity entity) {
final String str = (String) entity.getProperty(ANCESTRY_PROPERTY);
return parseAncestry(str);
}
private String getAuthorIdFromEntity(final Entity entity) {
return (String) entity.getProperty(AUTHOR_ID_PROPERTY);
}
private String getAuthorNameFromEntity(final Entity entity) {
return (String) entity.getProperty(AUTHOR_NAME_PROPERTY);
}
private int getBeginningNumFromEntity(final Entity entity) {
final String property = BEGINNING_NUMBER_PROPERTY;
final Long num = (Long) entity.getProperty(property);
if (num != null) {
return num.intValue();
} else {
return 0;
}
}
private String getBeginningVersionFromEntity(final Entity entity) {
return (String) entity.getProperty(BEGINNING_VERSION_PROPERTY);
}
/**
* @param entity
* @return
*/
@SuppressWarnings("unchecked")
private List<String> getFormerlyLovingUsersFromEntity(final Entity entity) {
final String property = FORMERLY_LOVING_USERS_PROPERTY;
return (List<String>) entity.getProperty(property);
}
private boolean getIsFirstPgFromEntity(final Entity entity) {
final String propertyName = IS_FIRST_PG_PROPERTY;
final Boolean property = (Boolean) entity.getProperty(propertyName);
if (property != null) {
return property.booleanValue();
} else {
return false;
}
}
private int getLoveDenominator() {
final int numLoversOfAllVersions = this.getNumLoversOfAllVersions();
return numLoversOfAllVersions;
}
private int getLoveInfluence() {
return LOVE_INFLUENCE;
}
private int getLoveNumerator() {
final int numLoversOfThisPg = this.getNumLovingUsers();
return numLoversOfThisPg;
}
/**
* @param entity
* @return
*/
@SuppressWarnings("unchecked")
private List<String> getLovingUsersFromEntity(final Entity entity) {
return (List<String>) entity.getProperty(LOVING_USERS_PROPERTY);
}
private int getNumLoversOfAllVersions() {
final PageId id = this.getId();
final int pgNum = id.getNumber();
final int numLovers = StoryPage.countLoversOfAllVersions(pgNum);
return numLovers;
}
private int getSizeDenominator() {
if (this.isTheFirstPage()) {
/*
* For example, the first page of the story is 1a. Find the number
* of nodes in all subtrees of all versions of 1a. So, if there are
* two versions, 1a and 1b, I need to find the size of both subtrees
* and add 1 to each size and then add them together. This is O(n)
* where n is the number of versions. Is there an O(1) solution?
* We're looking for all nodes with subtrees which match the
* following regex: "1[a-z]+.*". From this, we know that the string
* must be greater than "1\`" and less than "1\{".
*/
return this.getSizeOfBeginningSubtree();
} else {
return this.getSizeOfSiblingSubtrees();
}
}
private int getSizeInfluence() {
return SIZE_INFLUENCE;
}
private int getSizeNumerator() {
return this.getSizeOfSubtree() + 1;
}
/**
* @return
*/
private int getSizeOfBeginningSubtree() {
final int num = this.getId().getNumber();
final String greaterThanOrEqual = num + "`";
final String lessThan = num + "{";
return StoryPage.countSubtreeBetween(greaterThanOrEqual, lessThan);
}
/**
* @return
*/
private int getSizeOfSiblingSubtrees() {
final List<PageId> ancestry = this.getAncestry();
String subtreeAncestry = "";
for (int i = 0; i < ancestry.size() - 1; i++) {
subtreeAncestry += ancestry.get(i);
subtreeAncestry += String.valueOf(ANCESTRY_DELIMITER);
}
final int num = this.getId().getNumber();
subtreeAncestry += num;
final String greaterThanOrEqual = subtreeAncestry + "`";
final String lessThan = subtreeAncestry + "{";
return StoryPage.countSubtreeBetween(greaterThanOrEqual, lessThan);
}
/**
* @return
*/
private int getSizeOfSubtree() {
final List<PageId> ancestry = this.getAncestry();
String subtreeAncestry = "";
for (int i = 0; i < ancestry.size(); i++) {
subtreeAncestry += ancestry.get(i);
if (i < ancestry.size() - 1) {
subtreeAncestry += String.valueOf(ANCESTRY_DELIMITER);
}
}
final String greater = subtreeAncestry + ANCESTRY_DELIMITER;
final char nextChar = ANCESTRY_DELIMITER + 1;
final String less = subtreeAncestry + nextChar;
return StoryPage.countSubtreeBetween(greater, less);
}
@SuppressWarnings("unchecked")
private List<String> getTagsFromEntity(final Entity entity) {
return (List<String>) entity.getProperty(TAGS_PROPERTY);
}
/**
* Returns the text of the story page from the given entity.
*
* @param entity
* The entity containing the text
* @return The text of the story page
*/
private Text getTextFromEntity(final Entity entity) {
return (Text) entity.getProperty(TEXT_PROPERTY);
}
/**
* @return
*/
private void incrementVersion() {
this.getId().incrementVersion();
this.read();
}
private void initTags() {
final List<String> tags = new ArrayList<String>();
this.setTags(tags);
}
/**
* @return
*/
private boolean isTheFirstPage() {
return this.getId().getNumber() == this.getBeginning().getNumber();
}
/**
* @param str
* @return
*/
private List<PageId> parseAncestry(final String str) {
final List<PageId> ancestry = new ArrayList<PageId>();
if (str != null && str.equals("") == false) {
final String regex = String.valueOf(ANCESTRY_DELIMITER);
final String[] words = str.split(regex);
for (final String word : words) {
ancestry.add(new PageId(word));
}
}
return ancestry;
}
/**
* @param entity
*/
private void readAncestryFromEntity(final Entity entity) {
final List<PageId> ancestry = getAncestryFromEntity(entity);
this.setAncestry(ancestry);
this.setParentFromAncestry(ancestry);
}
private void readAuthorIdFromEntity(final Entity entity) {
final String authorId = getAuthorIdFromEntity(entity);
this.setAuthorId(authorId);
}
private void readAuthorNameFromEntity(final Entity entity) {
final String authorName = getAuthorNameFromEntity(entity);
this.setAuthorName(authorName);
}
private void readBeginningFromEntity(final Entity entity) {
final PageId beginning = new PageId();
final int num = getBeginningNumFromEntity(entity);
beginning.setNumber(num);
final String version = getBeginningVersionFromEntity(entity);
beginning.setVersion(version);
final boolean isValid = beginning.isValid();
if (isValid)
this.setBeginning(beginning);
else
this.setBeginning(null);
}
/**
* @param entity
*/
private void readFormerlyLovingUsersFromEntity(final Entity entity) {
List<String> users = getFormerlyLovingUsersFromEntity(entity);
if (users == null) {
users = new ArrayList<String>();
}
this.setFormerlyLovingUsers(users);
}
/**
* Reads the values from the entity corresponding to the ID of this story
* page.
*
* @param entity
* The entity storing the ID
*/
private void readIdFromEntity(final Entity entity) {
final PageId id = new PageId();
final int num = getIdNumFromEntity(entity);
id.setNumber(num);
final String version = getIdVersionFromEntity(entity);
id.setVersion(version);
this.setId(id);
}
private void readIsFirstPgFromEntity(final Entity entity) {
final boolean isFirstPg = getIsFirstPgFromEntity(entity);
this.setFirstPg(isFirstPg);
}
/**
* @param entity
*/
private void readLovingUsersFromEntity(final Entity entity) {
List<String> users = getLovingUsersFromEntity(entity);
if (users == null) {
users = new ArrayList<String>();
}
this.setLovingUsers(users);
}
private void readTagsFromEntity(final Entity entity) {
List<String> tags = getTagsFromEntity(entity);
if (tags == null) {
tags = new ArrayList<String>();
}
this.setTags(tags);
}
/**
* Reads the value from the entity corresponding to the text of this story
* page.
*
* @param entity
* The entity storing the text
*/
private void readTextFromEntity(final Entity entity) {
final Text text = getTextFromEntity(entity);
this.setText(text);
}
/**
* @param ancestry
*/
private void setAncestry(final List<PageId> ancestry) {
this.ancestry = ancestry;
}
/**
* @param entity
*/
private void setAncestryInEntity(final Entity entity) {
final List<PageId> ancestry = this.getAncestry();
String entityVal = "";
for (int i = 0; i < ancestry.size(); i++) {
entityVal += ancestry.get(i);
if (i < ancestry.size() - 1) {
entityVal += ANCESTRY_DELIMITER;
}
}
entity.setProperty(ANCESTRY_PROPERTY, entityVal);
}
private void setAuthorIdInEntity(final Entity entity) {
final String authorId = this.getAuthorId();
if (authorId != null) {
entity.setProperty(AUTHOR_ID_PROPERTY, authorId);
}
}
private void setAuthorNameInEntity(final Entity entity) {
final String authorName = this.getAuthorName();
if (authorName != null) {
entity.setProperty(AUTHOR_NAME_PROPERTY, authorName);
}
}
private void setBeginningInEntity(final Entity entity) {
final PageId beginning = this.getBeginning();
final int num = beginning.getNumber();
entity.setProperty(BEGINNING_NUMBER_PROPERTY, num);
final String version = beginning.getVersion();
entity.setProperty(BEGINNING_VERSION_PROPERTY, version);
}
/**
* @param chance
*/
private void setChance(final String chance) {
this.chance = chance;
}
private void setFirstPg(final boolean isFirstPg) {
this.isFirstPg = isFirstPg;
}
/**
* @param entity
*/
private void setFormerlyLovingUsersInEntity(final Entity entity) {
final List<String> users = this.getFormerlyLovingUsers();
entity.setProperty(FORMERLY_LOVING_USERS_PROPERTY, users);
}
/**
* Sets the values in the entity corresponding to the ID for this story
* page.
*
* @param entity
* The entity in which the values are to be stored
*/
private void setIdInEntity(final Entity entity) {
final PageId id = this.getId();
final int num = id.getNumber();
entity.setProperty(ID_NUMBER_PROPERTY, num);
final String version = id.getVersion();
entity.setProperty(ID_VERSION_PROPERTY, version);
}
private void setIsFirstPgInEntity(final Entity entity) {
final boolean isFirstPg = this.isFirstPg();
entity.setProperty(IS_FIRST_PG_PROPERTY, isFirstPg);
}
/**
* @param entity
*/
private void setLovingUsersInEntity(final Entity entity) {
final List<String> lovingUsers = this.getLovingUsers();
entity.setProperty(LOVING_USERS_PROPERTY, lovingUsers);
}
/**
* @param ancestry
*/
private void setParentFromAncestry(final List<PageId> ancestry) {
if (ancestry.size() > 1) {
final int parentIndex = ancestry.size() - 2;
final PageId parentId = ancestry.get(parentIndex);
final StoryPage parent = new StoryPage();
parent.setId(parentId);
parent.read();
this.setParent(parent);
} else {
this.setParent(null);
}
}
private void setTags(final List<String> tags) {
this.tags = tags;
}
private void setTagsInEntity(final Entity entity) {
final List<String> tags = this.getTags();
entity.setProperty(TAGS_PROPERTY, tags);
}
/**
* Sets the value in the entity corresponding to the text of this story
* page.
*
* @param entity
* The entity in which the value is to be stored
*/
private void setTextInEntity(Entity entity) {
final Text text = this.getText();
entity.setProperty(TEXT_PROPERTY, text);
}
private String summarise(final String full, final int len) {
final int fullSize = full.length();
if (fullSize < (len - 1))
return full;
else {
final String cropped = full.substring(0, (len - 1));
return cropped + ELLIPSIS;
}
}
/*
* (non-Javadoc)
*
* @see com.deuteriumlabs.dendrite.model.Model#getKindName()
*/
@Override
String getKindName() {
return KIND_NAME;
}
/*
* (non-Javadoc)
*
* @see com.deuteriumlabs.dendrite.model.Model#getMatchingQuery()
*/
@Override
Query getMatchingQuery() {
final Query query = new Query(KIND_NAME);
final PageId id = this.getId();
final Filter filter = getIdFilter(id);
return query.setFilter(filter);
}
/*
* (non-Javadoc)
*
* @see
* com.deuteriumlabs.dendrite.model.Model#readPropertiesFromEntity(com.google
* .appengine.api.datastore.Entity)
*/
@Override
void readPropertiesFromEntity(final Entity entity) {
this.readAncestryFromEntity(entity);
this.readIdFromEntity(entity);
this.readTextFromEntity(entity);
this.readBeginningFromEntity(entity);
this.readAuthorNameFromEntity(entity);
this.readAuthorIdFromEntity(entity);
this.readLovingUsersFromEntity(entity);
this.readFormerlyLovingUsersFromEntity(entity);
this.readTagsFromEntity(entity);
this.readIsFirstPgFromEntity(entity);
}
/*
* (non-Javadoc)
*
* @see
* com.deuteriumlabs.dendrite.model.Model#setPropertiesInEntity(com.google
* .appengine.api.datastore.Entity)
*/
@Override
void setPropertiesInEntity(final Entity entity) {
this.setAncestryInEntity(entity);
this.setIdInEntity(entity);
this.setTextInEntity(entity);
this.setBeginningInEntity(entity);
this.setAuthorNameInEntity(entity);
this.setAuthorIdInEntity(entity);
this.setLovingUsersInEntity(entity);
this.setFormerlyLovingUsersInEntity(entity);
this.setTagsInEntity(entity);
this.setIsFirstPgInEntity(entity);
}
@Override
protected Entity createNewEntity(String kindName) {
final String key = this.getId().toString();
return new Entity(KIND_NAME, key);
}
@Override
protected Entity getMatchingEntity() throws EntityNotFoundException {
final Key key = getKey();
return getStore().get(key);
}
private Key getKey() {
return KeyFactory.createKey(KIND_NAME, id.toString());
}
}
|
package de.hbt.hackathon.rtb.agent;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.hbt.hackathon.rtb.base.message.input.DeadMessage;
import de.hbt.hackathon.rtb.base.message.input.EnergyMessage;
import de.hbt.hackathon.rtb.base.message.input.ExitRobotMessage;
import de.hbt.hackathon.rtb.base.message.input.GameFinishesMessage;
import de.hbt.hackathon.rtb.base.message.input.GameStartsMessage;
import de.hbt.hackathon.rtb.base.message.input.InitializeMessage;
import de.hbt.hackathon.rtb.base.message.input.InputMessage;
import de.hbt.hackathon.rtb.base.message.output.ColourMessage;
import de.hbt.hackathon.rtb.base.message.output.NameMessage;
import de.hbt.hackathon.rtb.base.message.output.OutputMessage;
import de.hbt.hackathon.rtb.base.strategy.AbstractStrategy;
import de.hbt.hackathon.rtb.strategy.HealingStrategy;
import de.hbt.hackathon.rtb.strategy.SimpleStrategy;
import de.hbt.hackathon.rtb.world.World;
public class Agent implements CommunicationListener {
private static final Logger LOGGER = LoggerFactory.getLogger(Agent.class);
// technical configuration
private static final int UPDATES_PER_SECOND = 10;
// game configuration
private static final String NAME = "Brainbug";
private static final String HOME_COLOUR = "FFFFFF";
private static final String AWAY_COLOUR = "FF7777";
private final Communicator communicator;
private final AbstractStrategy strategy;
private final Timer gameTimer;
public Agent(Communicator communicator, AbstractStrategy strategy) {
this.communicator = communicator;
this.strategy = strategy;
this.gameTimer = new Timer();
}
public static void main(String[] args) throws IOException {
Communicator communicator = new Communicator();
World world = new World();
AbstractStrategy strategy;
;
AbstractStrategy simpleStrategy = new SimpleStrategy(world);
AbstractStrategy healingStrategy = new HealingStrategy(world);
if (args[0].equals(simpleStrategy.getName())) {
strategy = simpleStrategy;
} else if (args[0].equals(healingStrategy.getName())) {
strategy = healingStrategy;
} else {
LOGGER.error("No bot name is given!");
strategy = simpleStrategy;
}
WorldUpdater worldUpdater = new WorldUpdater(world);
CapabilitiesBuilder capabilitiesBuilder = new CapabilitiesBuilder();
strategy.setCapabilities(capabilitiesBuilder.getCapabilities());
Agent agent = new Agent(communicator, strategy);
Thread communicatorThread = new Thread(communicator);
communicator.addListener(agent);
communicator.addListener(worldUpdater);
communicator.addListener(capabilitiesBuilder);
communicatorThread.start();
}
public void onTimer() {
List<OutputMessage> commands = strategy.process();
for (OutputMessage message : commands) {
communicator.sendOutputMessage(message);
}
}
private void startGameTimer() {
gameTimer.schedule(new TimerTask() {
@Override
public void run() {
Agent.this.onTimer();
}
}, 0L, 1000L / UPDATES_PER_SECOND);
}
private void stopGameTimer() {
gameTimer.cancel();
}
@Override
public void onMessage(InputMessage message) {
if (message instanceof InitializeMessage) {
onGameInitialized(((InitializeMessage) message).isFirst());
} else if (message instanceof GameStartsMessage) {
onGameStarted();
} else if (message instanceof EnergyMessage) {
onEnergyLevel(((EnergyMessage) message).getEnergyLevel());
} else if (message instanceof DeadMessage) {
onRobotDied();
} else if (message instanceof GameFinishesMessage) {
onGameFinished();
} else if (message instanceof ExitRobotMessage) {
onExitProgram();
}
}
private void onGameInitialized(boolean first) {
if (first) {
LOGGER.info("Game initialized for the first time, sending name " + NAME + " and colours.");
communicator.sendOutputMessage(new NameMessage(NAME));
communicator.sendOutputMessage(new ColourMessage(HOME_COLOUR, AWAY_COLOUR));
}
}
private void onGameStarted() {
LOGGER.info("Game started.");
startGameTimer();
}
private void onGameFinished() {
LOGGER.info("Game finished.");
stopGameTimer();
}
private void onRobotDied() {
LOGGER.info("Our robot died :-(");
stopGameTimer();
}
private void onExitProgram() {
LOGGER.info("Program exiting.");
communicator.setGameOver(true);
}
private void onEnergyLevel(int energyLevel) {
LOGGER.info("Received energy level: " + energyLevel);
}
}
|
package de.bwv_aachen.dijkstra.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import de.bwv_aachen.dijkstra.controller.Controller;
import de.bwv_aachen.dijkstra.model.Airport;
public class ConnectionVisualization extends View {
private static final long serialVersionUID = 1527659470763038523L;
private BufferedImage airportPicture;
private final int panelWidth = 660;
private final int panelHeight = 660;
private final Point panelCenter = new Point(panelWidth/2, panelHeight/2);
private final Color labelColor = Color.BLACK;
private final Font labelFont = new Font("sans-serif", Font.BOLD, 14);
private Point picCenter;
private HashMap<Airport,Point> points;
static int testNoRepaint = 0;
private final double circleRadius = 200D;
public ConnectionVisualization(Controller c) {
super("ConnectionVisualization",c);
try {
//Let the controller do this?
airportPicture = ImageIO.read(new File("res/airport-icon_2.gif"));
}
catch (IOException e) {
//TODO
System.out.println("Bild nicht gefunden");
}
picCenter = new Point(airportPicture.getWidth()/2, airportPicture.getHeight()/2);
points = new HashMap<Airport,Point>();
}
class VisualizationPanel extends JPanel {
private static final long serialVersionUID = -3979908130673351633L;
@Override
public void paint(Graphics g) {
//TODO: Replace with a Panel with an ImageIcon and a JLabel per Airport ???
super.paint(g); // call superclass's paint
//No runtime-intensive calculations here, since this method is called a huge amount of times!
setSize(panelWidth,panelHeight);
g.setFont(labelFont);
g.setColor(labelColor);
for(Map.Entry<Airport, Point> entry: points.entrySet()) {
Point p = entry.getValue();
g.drawImage(airportPicture, p.x-picCenter.x, p.y-picCenter.y, null);
g.drawString(entry.getKey().toString(), p.x, p.y);
}
}
}
@Override
public void draw() {
this.getContentPane().add(new VisualizationPanel());
this.pack();
if ( points.isEmpty() ) {
//determine the points for the airports
determinePoints();
}
this.setSize(panelWidth,panelHeight);
this.setVisible(true);
}
//The controller may also call this method. So we make it public!
public void determinePoints() {
Object[] airports = controller.getModel().getAirportList().values().toArray();
int numOfNodes = airports.length;
if (numOfNodes == 0)
return;
final double angle = Math.toRadians( 360D / numOfNodes );
for (int i = 0; i < numOfNodes; i++) {
double alpha = angle * i;
//The points are arranged in a n-gon with the radius circleRadius
int x = (int)Math.round(panelCenter.x + Math.sin(alpha) * circleRadius);
int y = (int)Math.round(panelCenter.y - Math.cos(alpha) * circleRadius);
//Remember the points for further use
points.put((Airport) airports[i], new Point(x,y));
}
}
}
|
package com.ore.infinium.systems;
import com.badlogic.ashley.core.*;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.ore.infinium.World;
import com.ore.infinium.components.*;
public class PowerOverlayRenderSystem extends EntitySystem {
public static int spriteCount;
public boolean overlayVisible = true;
// public TextureAtlas m_atlas;
private World m_world;
private SpriteBatch m_batch;
private ComponentMapper<PlayerComponent> playerMapper = ComponentMapper.getFor(PlayerComponent.class);
private ComponentMapper<SpriteComponent> spriteMapper = ComponentMapper.getFor(SpriteComponent.class);
private ComponentMapper<ItemComponent> itemMapper = ComponentMapper.getFor(ItemComponent.class);
private ComponentMapper<VelocityComponent> velocityMapper = ComponentMapper.getFor(VelocityComponent.class);
private ComponentMapper<TagComponent> tagMapper = ComponentMapper.getFor(TagComponent.class);
private ComponentMapper<PowerComponent> powerMapper = ComponentMapper.getFor(PowerComponent.class);
// public Sprite outputNode = new Sprite();
private boolean m_leftClicked;
private boolean m_dragInProgress;
private Entity dragSourceEntity;
private static final float powerNodeOffsetRatioX = 0.1f;
private static final float powerNodeOffsetRatioY = 0.1f;
public PowerOverlayRenderSystem(World world) {
m_world = world;
}
public void addedToEngine(Engine engine) {
m_batch = new SpriteBatch();
}
public void removedFromEngine(Engine engine) {
m_batch.dispose();
}
//todo sufficient until we get a spatial hash or whatever
private Entity entityAtPosition(Vector2 pos) {
ImmutableArray<Entity> entities = m_world.engine.getEntitiesFor(Family.all(PowerComponent.class).get());
SpriteComponent spriteComponent;
TagComponent tagComponent;
for (int i = 0; i < entities.size(); ++i) {
tagComponent = tagMapper.get(entities.get(i));
if (tagComponent != null && tagComponent.tag.equals("itemPlacementGhost")) {
continue;
}
spriteComponent = spriteMapper.get(entities.get(i));
Rectangle rectangle = new Rectangle(spriteComponent.sprite.getX() - (spriteComponent.sprite.getWidth() * 0.5f),
spriteComponent.sprite.getY() - (spriteComponent.sprite.getHeight() * 0.5f),
spriteComponent.sprite.getWidth(), spriteComponent.sprite.getHeight());
if (rectangle.contains(pos)) {
return entities.get(i);
}
}
return null;
}
public void leftMouseClicked() {
m_leftClicked = true;
//fixme prolly make a threshold for dragging
m_dragInProgress = true;
Vector3 unprojectedMouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
m_world.m_camera.unproject(unprojectedMouse);
//find the entity we're dragging on
dragSourceEntity = entityAtPosition(new Vector2(unprojectedMouse.x, unprojectedMouse.y));
Gdx.app.log("", "drag source" + dragSourceEntity);
}
public void leftMouseReleased() {
m_leftClicked = false;
if (m_dragInProgress) {
//check if drag can be connected
if (dragSourceEntity != null) {
Vector3 unprojectedMouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
m_world.m_camera.unproject(unprojectedMouse);
Entity dropEntity = entityAtPosition(new Vector2(unprojectedMouse.x, unprojectedMouse.y));
//if the drop is invalid/empty, or they attempted to drop on the same spot they dragged from, ignore
if (dropEntity == null || dropEntity == dragSourceEntity) {
dragSourceEntity = null;
m_dragInProgress = false;
Gdx.app.log("", "drag source release, target non existent, canceling.");
return;
}
PowerComponent sourcePowerComponent = powerMapper.get(dragSourceEntity);
PowerComponent dropPowerComponent = powerMapper.get(dropEntity);
if (!sourcePowerComponent.outputEntities.contains(dropEntity, true) &&
!dropPowerComponent.outputEntities.contains(dragSourceEntity, true)) {
sourcePowerComponent.outputEntities.add(dropEntity);
Gdx.app.log("", "drag source release, adding, count" + sourcePowerComponent.outputEntities.size);
}
dragSourceEntity = null;
}
m_dragInProgress = false;
}
}
public void update(float delta) {
if (!overlayVisible) {
return;
}
// m_batch.setProjectionMatrix(m_world.m_camera.combined);
m_batch.setProjectionMatrix(m_world.m_camera.combined);
m_batch.begin();
renderEntities(delta);
m_batch.end();
//screen space rendering
m_batch.setProjectionMatrix(m_world.m_client.viewport.getCamera().combined);
m_batch.begin();
m_world.m_client.bitmapFont_8pt.setColor(1, 0, 0, 1);
float fontY = 150;
float fontX = m_world.m_client.viewport.getRightGutterX() - 220;
m_batch.draw(m_world.m_atlas.findRegion("backgroundRect"), fontX - 10, fontY + 10, fontX + 100, fontY - 300);
m_world.m_client.bitmapFont_8pt.draw(m_batch, "Energy overlay visible (press E)", fontX, fontY);
fontY -= 15;
m_world.m_client.bitmapFont_8pt.draw(m_batch, "Input: N/A Output: N/A", fontX, fontY);
m_world.m_client.bitmapFont_8pt.setColor(1, 1, 1, 1);
m_batch.end();
}
private void renderEntities(float delta) {
//todo need to exclude blocks?
ImmutableArray<Entity> entities = m_world.engine.getEntitiesFor(Family.all(PowerComponent.class).get());
ItemComponent itemComponent;
SpriteComponent spriteComponent;
TagComponent tagComponent;
PowerComponent powerComponent;
if (m_dragInProgress && dragSourceEntity != null) {
SpriteComponent dragSpriteComponent = spriteMapper.get(dragSourceEntity);
Vector3 unprojectedMouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
m_world.m_camera.unproject(unprojectedMouse);
m_batch.setColor(1, 1, 0, 0.5f);
//in the middle of a drag, draw powernode from source, to mouse position
renderWire(new Vector2(unprojectedMouse.x, unprojectedMouse.y),
new Vector2(dragSpriteComponent.sprite.getX() + dragSpriteComponent.sprite.getWidth() * powerNodeOffsetRatioX,
dragSpriteComponent.sprite.getY() + dragSpriteComponent.sprite.getHeight() * powerNodeOffsetRatioY));
m_batch.setColor(1, 1, 1, 1);
}
for (int i = 0; i < entities.size(); ++i) {
itemComponent = itemMapper.get(entities.get(i));
assert itemComponent != null;
if (itemComponent.state != ItemComponent.State.InWorldState) {
continue;
}
tagComponent = tagMapper.get(entities.get(i));
if (tagComponent != null && tagComponent.tag.equals("itemPlacementGhost")) {
continue;
}
spriteComponent = spriteMapper.get(entities.get(i));
//for each power node that goes outward from this sprite, draw connection lines
renderPowerNode(spriteComponent);
powerComponent = powerMapper.get(entities.get(i));
SpriteComponent spriteOutputNodeComponent;
//go over each output of this entity, and draw a connection from this entity to the connected dest
for (int j = 0; j < powerComponent.outputEntities.size; ++j) {
powerComponent = powerMapper.get(entities.get(i));
spriteOutputNodeComponent = spriteMapper.get(powerComponent.outputEntities.get(j));
renderWire(new Vector2(spriteComponent.sprite.getX() + spriteComponent.sprite.getWidth() * powerNodeOffsetRatioX,
spriteComponent.sprite.getY() + spriteComponent.sprite.getHeight() * powerNodeOffsetRatioY),
new Vector2(spriteOutputNodeComponent.sprite.getX() + spriteOutputNodeComponent.sprite.getWidth() * powerNodeOffsetRatioX,
spriteOutputNodeComponent.sprite.getY() + spriteOutputNodeComponent.sprite.getHeight() * powerNodeOffsetRatioY));
}
}
}
private void renderWire(Vector2 source, Vector2 dest) {
Vector2 diff = new Vector2(source.x - dest.x, source.y - dest.y);
float rads = MathUtils.atan2(diff.y, diff.x);
float degrees = rads * MathUtils.radiansToDegrees - 90;
float powerLineWidth = 3.0f / World.PIXELS_PER_METER;
float powerLineHeight = Vector2.dst(source.x, source.y, dest.x, dest.y);
m_batch.draw(m_world.m_atlas.findRegion("power-node-line"),
dest.x,
dest.y,
0, 0,
powerLineWidth, powerLineHeight, 1.0f, 1.0f, degrees);
}
private void renderPowerNode(SpriteComponent spriteComponent) {
float powerNodeWidth = 20.0f / World.PIXELS_PER_METER;
float powerNodeHeight = 20.0f / World.PIXELS_PER_METER;
m_batch.draw(m_world.m_atlas.findRegion("power-node-circle"),
spriteComponent.sprite.getX() + (spriteComponent.sprite.getWidth() * powerNodeOffsetRatioX) - (powerNodeWidth * 0.5f),
spriteComponent.sprite.getY() + (spriteComponent.sprite.getHeight() * powerNodeOffsetRatioY) - (powerNodeHeight * 0.5f),
powerNodeWidth, powerNodeHeight);
}
}
|
package org.mariadb.jdbc;
import org.junit.Test;
import java.nio.charset.Charset;
import java.sql.*;
import static org.junit.Assert.fail;
public class PasswordEncodingTest extends BaseTest {
private static final String exoticPwd = "abéï";
@Test
public void testPwdCharset() throws Exception {
cancelForVersion(5, 6); //has password charset issue
String[] charsets = new String[]{"UTF-8",
"windows-1252",
"Big5"};
String[] charsetsMysql = new String[]{"utf8",
"latin1",
"big5"};
try {
for (int i = 0; i < charsets.length; i++) {
createUser(charsets[i], charsetsMysql[i]);
}
for (String currentCharsetName : charsets) {
try (Connection connection = DriverManager.getConnection("jdbc:mariadb://" + ((hostname != null) ? hostname : "localhost")
+ ":" + port + "/" + database + "?user=test" + currentCharsetName + "&password=" + exoticPwd)) {
//windows-1252 and windows-1250 will work have the same conversion for this password
if (!currentCharsetName.equals(Charset.defaultCharset().name())
&& (!"windows-1252".equals(currentCharsetName) || !Charset.defaultCharset().name().startsWith("windows-125"))) {
fail("must have failed for currentCharsetName=" + currentCharsetName + " using java default charset "
+ Charset.defaultCharset().name());
}
} catch (SQLInvalidAuthorizationSpecException sqle) {
if (currentCharsetName.equals(Charset.defaultCharset().name())) {
fail("must have not have failed for charsetName=" + currentCharsetName + " which is java default");
}
}
}
for (String charsetName : charsets) checkConnection(charsetName, charsets);
} finally {
Statement stmt = sharedConnection.createStatement();
for (String charsetName : charsets) {
try {
stmt.execute("DROP USER 'test" + charsetName + "'@'%'");
} catch (SQLException e) {
//nothing
}
}
}
}
private void createUser(String charsetName, String serverCharset) throws Exception {
try (Connection connection = setConnection()) {
MariaDbStatement stmt = connection.createStatement().unwrap(MariaDbStatement.class);
stmt.execute("set @@character_set_client='" + serverCharset + "'");
stmt.execute("CREATE USER 'test" + charsetName + "'@'%'");
//non jdbc method that send query according to charset
stmt.testExecute("GRANT ALL on *.* to 'test" + charsetName + "'@'%' identified by '" + exoticPwd + "'", Charset.forName(charsetName));
stmt.execute("FLUSH PRIVILEGES");
}
}
private void checkConnection(String charsetName, String[] charsets) throws Exception {
for (String currentCharsetName : charsets) {
try (Connection connection = DriverManager.getConnection("jdbc:mariadb://" + ((hostname != null) ? hostname : "localhost")
+ ":" + port + "/" + database + "?user=test" + charsetName + "&password="
+ exoticPwd + "&passwordCharacterEncoding=" + currentCharsetName)) {
if (!currentCharsetName.equals(charsetName)) {
fail("must have failed for charsetName=" + charsetName + " using passwordCharacterEncoding=" + currentCharsetName);
}
} catch (SQLInvalidAuthorizationSpecException sqle) {
if (currentCharsetName.equals(charsetName)) {
fail("must not have failed for charsetName=" + charsetName + " using passwordCharacterEncoding=" + currentCharsetName);
}
}
}
}
}
|
// ScanrReader.java
package loci.formats.in;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.ByteArrayHandle;
import loci.common.DataTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.NonNegativeInteger;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class ScanrReader extends FormatReader {
// -- Constants --
private static final String XML_FILE = "experiment_descriptor.xml";
private static final String EXPERIMENT_FILE = "experiment_descriptor.dat";
private static final String ACQUISITION_FILE = "AcquisitionLog.dat";
private static final String[] METADATA_SUFFIXES = new String[] {"dat", "xml"};
// -- Fields --
private Vector<String> metadataFiles = new Vector<String>();
private int wellRows, wellColumns;
private int fieldRows, fieldColumns;
private int wellCount = 0;
private Vector<String> channelNames = new Vector<String>();
private Hashtable<String, Integer> wellLabels =
new Hashtable<String, Integer>();
private Hashtable<Integer, Integer> wellNumbers =
new Hashtable<Integer, Integer>();
private String plateName;
private Double pixelSize;
private String[] tiffs;
private MinimalTiffReader reader;
// -- Constructor --
/** Constructs a new ScanR reader. */
public ScanrReader() {
super("Olympus ScanR", new String[] {"dat", "xml", "tif"});
domains = new String[] {FormatTools.HCS_DOMAIN};
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
Location file = new Location(id).getAbsoluteFile();
String name = file.getName();
if (name.equals(XML_FILE) || name.equals(EXPERIMENT_FILE) ||
name.equals(ACQUISITION_FILE))
{
return true;
}
Location parent = file.getParentFile();
if (parent != null) {
parent = parent.getParentFile();
}
return new Location(parent, XML_FILE).exists();
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
String localName = new Location(name).getName();
if (localName.equals(XML_FILE) || localName.equals(EXPERIMENT_FILE) ||
localName.equals(ACQUISITION_FILE))
{
return true;
}
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser p = new TiffParser(stream);
IFD ifd = p.getFirstIFD();
if (ifd == null) return false;
Object s = ifd.getIFDValue(IFD.SOFTWARE);
if (s == null) return false;
String software = s instanceof String[] ? ((String[]) s)[0] : s.toString();
return software.trim().equals("National Instruments IMAQ");
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
Vector<String> files = new Vector<String>();
for (String file : metadataFiles) {
if (file != null) files.add(file);
}
if (!noPixels && tiffs != null) {
int offset = getSeries() * getImageCount();
for (int i=0; i<getImageCount(); i++) {
if (tiffs[offset + i] != null) {
files.add(tiffs[offset + i]);
}
}
}
return files.toArray(new String[files.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
if (reader != null) {
reader.close();
}
reader = null;
tiffs = null;
plateName = null;
channelNames.clear();
fieldRows = fieldColumns = 0;
wellRows = wellColumns = 0;
metadataFiles.clear();
wellLabels.clear();
wellNumbers.clear();
wellCount = 0;
pixelSize = null;
}
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int index = getSeries() * getImageCount() + no;
if (tiffs[index] != null) {
reader.setId(tiffs[index]);
reader.openBytes(0, buf, x, y, w, h);
reader.close();
// mask out the sign bit
ByteArrayHandle pixels = new ByteArrayHandle(buf);
pixels.setOrder(
isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
for (int i=0; i<buf.length; i+=2) {
pixels.seek(i);
short value = pixels.readShort();
value = (short) (value & 0xfff);
pixels.seek(i);
pixels.writeShort(value);
}
buf = pixels.getBytes();
pixels.close();
}
return buf;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (metadataFiles.size() > 0) {
// this dataset has already been initialized
return;
}
// make sure we have the .xml file
if (!checkSuffix(id, "xml") && isGroupFiles()) {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
if (checkSuffix(id, "tif")) {
parent = parent.getParentFile();
}
String[] list = parent.list();
for (String file : list) {
if (file.equals(XML_FILE)) {
id = new Location(parent, file).getAbsolutePath();
super.initFile(id);
break;
}
}
if (!checkSuffix(id, "xml")) {
throw new FormatException("Could not find " + XML_FILE + " in " +
parent.getAbsolutePath());
}
}
else if (!isGroupFiles() && checkSuffix(id, "tif")) {
TiffReader r = new TiffReader();
r.setMetadataStore(getMetadataStore());
r.setId(id);
core = r.getCoreMetadata();
metadataStore = r.getMetadataStore();
Hashtable globalMetadata = r.getGlobalMetadata();
for (Object key : globalMetadata.keySet()) {
addGlobalMeta(key.toString(), globalMetadata.get(key));
}
r.close();
tiffs = new String[] {id};
reader = new MinimalTiffReader();
return;
}
Location dir = new Location(id).getAbsoluteFile().getParentFile();
String[] list = dir.list(true);
for (String file : list) {
Location f = new Location(dir, file);
if (!f.isDirectory() && checkSuffix(file, METADATA_SUFFIXES)) {
metadataFiles.add(f.getAbsolutePath());
}
}
// parse XML metadata
String xml = DataTools.readFile(id).trim();
// add the appropriate encoding, as some ScanR XML files use non-UTF8
// characters without specifying an encoding
if (xml.startsWith("<?")) {
xml = xml.substring(xml.indexOf("?>") + 2);
}
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + xml;
XMLTools.parseXML(xml, new ScanrHandler());
Vector<String> uniqueRows = new Vector<String>();
Vector<String> uniqueColumns = new Vector<String>();
for (String well : wellLabels.keySet()) {
if (!Character.isLetter(well.charAt(0))) continue;
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
wellRows = uniqueRows.size();
wellColumns = uniqueColumns.size();
if (wellRows * wellColumns != wellCount) {
adjustWellDimensions();
}
int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC();
if (nChannels == 0) nChannels = 1;
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellCount;
int nPos = fieldRows * fieldColumns;
if (nPos == 0) nPos = 1;
// get list of TIFF files
Location dataDir = new Location(dir, "data");
list = dataDir.list(true);
if (list == null) {
// try to find the TIFFs in the current directory
list = dir.list(true);
}
else dir = dataDir;
if (nTimepoints == 0 ||
list.length < nTimepoints * nChannels * nSlices * nWells * nPos)
{
nTimepoints = list.length / (nChannels * nWells * nPos * nSlices);
if (nTimepoints == 0) nTimepoints = 1;
}
tiffs = new String[nChannels * nWells * nPos * nTimepoints * nSlices];
int next = 0;
String[] keys = wellLabels.keySet().toArray(new String[wellLabels.size()]);
int realPosCount = 0;
for (int well=0; well<nWells; well++) {
int wellIndex = wellNumbers.get(well);
String wellPos = getBlock(wellIndex, "W");
int originalIndex = next;
for (int pos=0; pos<nPos; pos++) {
String posPos = getBlock(pos + 1, "P");
int posIndex = next;
for (int z=0; z<nSlices; z++) {
String zPos = getBlock(z, "Z");
for (int t=0; t<nTimepoints; t++) {
String tPos = getBlock(t, "T");
for (int c=0; c<nChannels; c++) {
for (String file : list) {
if (file.indexOf(wellPos) != -1 && file.indexOf(zPos) != -1 &&
file.indexOf(posPos) != -1 && file.indexOf(tPos) != -1 &&
file.indexOf(channelNames.get(c)) != -1)
{
tiffs[next++] = new Location(dir, file).getAbsolutePath();
break;
}
}
}
}
}
if (posIndex != next) realPosCount++;
}
if (next == originalIndex && well < keys.length) {
wellLabels.remove(keys[well]);
}
}
if (wellLabels.size() > 0 && wellLabels.size() != nWells) {
uniqueRows.clear();
uniqueColumns.clear();
for (String well : wellLabels.keySet()) {
if (!Character.isLetter(well.charAt(0))) continue;
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0) uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
nWells = uniqueRows.size() * uniqueColumns.size();
adjustWellDimensions();
}
if (realPosCount < nPos) {
nPos = realPosCount;
}
reader = new MinimalTiffReader();
reader.setId(tiffs[0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
// we strongly suspect that ScanR incorrectly records the
// signedness of the pixels
switch (pixelType) {
case FormatTools.INT8:
pixelType = FormatTools.UINT8;
break;
case FormatTools.INT16:
pixelType = FormatTools.UINT16;
break;
}
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
reader.close();
core = new CoreMetadata[nWells * nPos];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].sizeC = nChannels;
core[i].sizeZ = nSlices;
core[i].sizeT = nTimepoints;
core[i].sizeX = sizeX;
core[i].sizeY = sizeY;
core[i].pixelType = pixelType;
core[i].rgb = rgb;
core[i].interleaved = interleaved;
core[i].indexed = indexed;
core[i].littleEndian = littleEndian;
core[i].dimensionOrder = "XYCTZ";
core[i].imageCount = nSlices * nTimepoints * nChannels;
core[i].bitsPerPixel = 12;
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
int nFields = fieldRows * fieldColumns;
for (int i=0; i<getSeriesCount(); i++) {
MetadataTools.setDefaultCreationDate(store, id, i);
int field = i % nFields;
int well = i / nFields;
int wellIndex = wellNumbers.get(well) - 1;
int wellRow = wellIndex / wellColumns;
int wellCol = wellIndex % wellColumns;
store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
store.setWellColumn(new NonNegativeInteger(wellCol), 0, well);
store.setWellRow(new NonNegativeInteger(wellRow), 0, well);
String wellSample =
MetadataTools.createLSID("WellSample", 0, well, field);
store.setWellSampleID(wellSample, 0, well, field);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, well, field);
String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, well, field);
store.setImageID(imageID, i);
String name = "Well " + (wellIndex + 1) + ", Field " + (field + 1) +
" (Spot " + (i + 1) + ")";
store.setImageName(name, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
for (int c=0; c<getSizeC(); c++) {
store.setChannelName(channelNames.get(c), i, c);
}
if (pixelSize != null) {
store.setPixelsPhysicalSizeX(pixelSize, i);
store.setPixelsPhysicalSizeY(pixelSize, i);
}
}
String row = wellRows > 26 ? "Number" : "Letter";
String col = wellRows > 26 ? "Letter" : "Number";
store.setPlateRowNamingConvention(getNamingConvention(row), 0);
store.setPlateColumnNamingConvention(getNamingConvention(col), 0);
store.setPlateName(plateName, 0);
}
}
// -- Helper class --
class ScanrHandler extends DefaultHandler {
private String key, value;
private String qName;
private String wellIndex;
// -- DefaultHandler API methods --
public void characters(char[] ch, int start, int length) {
String v = new String(ch, start, length);
if (v.trim().length() == 0) return;
if (qName.equals("Name")) {
key = v;
}
else if (qName.equals("Val")) {
value = v.trim();
addGlobalMeta(key, value);
if (key.equals("columns/well")) {
fieldColumns = Integer.parseInt(value);
}
else if (key.equals("rows/well")) {
fieldRows = Integer.parseInt(value);
}
else if (key.equals("# slices")) {
core[0].sizeZ = Integer.parseInt(value);
}
else if (key.equals("timeloop real")) {
core[0].sizeT = Integer.parseInt(value);
}
else if (key.equals("timeloop count")) {
core[0].sizeT = Integer.parseInt(value) + 1;
}
else if (key.equals("name")) {
channelNames.add(value);
}
else if (key.equals("plate name")) {
plateName = value;
}
else if (key.equals("idle")) {
int lastIndex = channelNames.size() - 1;
if (value.equals("0") &&
!channelNames.get(lastIndex).equals("Autofocus"))
{
core[0].sizeC++;
}
else channelNames.remove(lastIndex);
}
else if (key.equals("well selection table + cDNA")) {
if (Character.isDigit(value.charAt(0))) {
wellIndex = value;
wellNumbers.put(new Integer(wellCount), new Integer(value));
wellCount++;
}
else {
wellLabels.put(value, new Integer(wellIndex));
}
}
else if (key.equals("conversion factor um/pixel")) {
pixelSize = new Double(value);
}
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
this.qName = qName;
}
}
// -- Helper methods --
private String getBlock(int index, String axis) {
String b = String.valueOf(index);
while (b.length() < 5) b = "0" + b;
return axis + b;
}
private void adjustWellDimensions() {
if (wellCount <= 8) {
wellColumns = 2;
wellRows = 4;
}
else if (wellCount <= 96) {
wellColumns = 12;
wellRows = 8;
}
else if (wellCount <= 384) {
wellColumns = 24;
wellRows = 16;
}
}
}
|
package org.roaringbitmap.needwork;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.roaringbitmap.RoaringBitmap;
import org.roaringbitmap.ZipRealDataRetriever;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class RandomAccess {
@Benchmark
public int branchyRoaring(BenchmarkState benchmarkState) {
int answer = 0;
org.roaringbitmap.Util.USE_BRANCHLESS_BINSEARCH = false;
for(int k : benchmarkState.queries) {
for(RoaringBitmap rb : benchmarkState.ac)
if(rb.contains(k))
answer++;
}
return answer;
}
@Benchmark
public int branchlessRoaring(BenchmarkState benchmarkState) {
int answer = 0;
org.roaringbitmap.Util.USE_BRANCHLESS_BINSEARCH = true;
for(int k : benchmarkState.queries) {
// on purpose we switch bitmaps between each contains to sabotage branchless
for(RoaringBitmap rb : benchmarkState.ac)
if(rb.contains(k))
answer++;
}
return answer;
}
@Benchmark
public int branchyRoaringWithRun(BenchmarkState benchmarkState) {
int answer = 0;
org.roaringbitmap.Util.USE_BRANCHLESS_BINSEARCH = false;
for(int k : benchmarkState.queries) {
for(RoaringBitmap rb : benchmarkState.rc)
if(rb.contains(k))
answer++;
}
return answer;
}
@Benchmark
public int branchlessRoaringWithRun(BenchmarkState benchmarkState) {
int answer = 0;
org.roaringbitmap.Util.USE_BRANCHLESS_BINSEARCH = true;
for(int k : benchmarkState.queries) {
// on purpose we switch bitmaps between each contains to sabotage branchless
for(RoaringBitmap rb : benchmarkState.rc)
if(rb.contains(k))
answer++;
}
return answer;
}
@State(Scope.Benchmark)
public static class BenchmarkState {
@Param ({// putting the data sets in alpha. order
"census-income", "census1881",
"dimension_008", "dimension_003",
"dimension_033", "uscensus2000",
"weather_sept_85", "wikileaks-noquotes"
,"census-income_srt","census1881_srt",
"weather_sept_85_srt","wikileaks-noquotes_srt"
})
String dataset;
int[] queries = new int[1024];
ArrayList<RoaringBitmap> ac = new ArrayList<RoaringBitmap>();
ArrayList<RoaringBitmap> rc = new ArrayList<RoaringBitmap>();
public BenchmarkState() {
}
@Setup
public void setup() throws Exception {
ZipRealDataRetriever dataRetriever = new ZipRealDataRetriever(dataset);
System.out.println();
System.out.println("Loading files from " + dataRetriever.getName());
int universe = 0;
for (int[] data : dataRetriever.fetchBitPositions()) {
RoaringBitmap basic = RoaringBitmap.bitmapOf(data);
ac.add(basic.clone());
int lv = basic.getReverseIntIterator().next();
if(lv > universe) universe = lv;
basic.runOptimize();
rc.add(basic);
}
Random rand = new Random(123);
for(int k = 0; k < queries.length; ++k)
queries[k] = rand.nextInt(universe+1);
System.out.println("loaded "+rc.size()+" bitmaps");
}
}
}
|
package dr.evomodel.branchratemodel;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evomodelxml.branchratemodel.StrictClockBranchRatesParser;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: StrictClockBranchRates.java,v 1.3 2006/01/09 17:44:30 rambaut Exp $
*/
public class StrictClockBranchRates extends AbstractBranchRateModel implements DifferentiableBranchRates {
private final Parameter rateParameter;
public StrictClockBranchRates(Parameter rateParameter) {
super(StrictClockBranchRatesParser.STRICT_CLOCK_BRANCH_RATES);
this.rateParameter = rateParameter;
addVariable(rateParameter);
}
public void handleModelChangedEvent(Model model, Object object, int index) {
// nothing to do
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
fireModelChanged();
}
protected void storeState() {
// nothing to do
}
protected void restoreState() {
// nothing to do
}
protected void acceptState() {
// nothing to do
}
public double getBranchRate(final Tree tree, final NodeRef node) {
return rateParameter.getParameterValue(0);
}
@Override
public double getBranchRateDifferential(Tree tree, NodeRef node) {
return 1.0;
}
@Override
public double getBranchRateSecondDifferential(Tree tree, NodeRef node) {
throw new RuntimeException("Not yet implemented");
}
@Override
public Parameter getRateParameter() { return rateParameter; }
@Override
public int getParameterIndexFromNode(NodeRef node) { return node.getNumber(); }
@Override
public ArbitraryBranchRates.BranchRateTransform getTransform() {
throw new RuntimeException("Not yet implemented");
}
@Override
public double[] updateGradientLogDensity(double[] gradient, double[] value, int from, int to) {
double total = 0.0;
for (double v : gradient) {
total += v;
}
return new double[] { total };
}
@Override
public double[] updateDiagonalHessianLogDensity(double[] diagonalHessian, double[] gradient,
double[] value, int from, int to) {
throw new RuntimeException("Not yet implemented");
}
}
|
package org.purl.wf4ever.robundle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class TestBundles {
protected void checkSignature(Path zip) throws IOException {
String MEDIATYPE = "application/vnd.wf4ever.robundle+zip";
// Check position 30++ according to RO Bundle specification
// http://purl.org/wf4ever/ro-bundle#ucf
byte[] expected = ("mimetype" + MEDIATYPE + "PK").getBytes("ASCII");
try (InputStream in = Files.newInputStream(zip)) {
byte[] signature = new byte[expected.length];
int MIME_OFFSET = 30;
assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
assertEquals(expected.length, in.read(signature));
assertArrayEquals(expected, signature);
}
}
@Test
public void close() throws Exception {
Bundle bundle = Bundles.createBundle();
assertTrue(Files.exists(bundle.getSource()));
assertTrue(bundle.getFileSystem().isOpen());
bundle.close();
assertFalse(Files.exists(bundle.getSource()));
assertFalse(bundle.getFileSystem().isOpen());
}
@Test
public void closeAndOpenBundle() throws Exception {
Bundle bundle = Bundles.createBundle();
Path zip = Bundles.closeBundle(bundle);
Bundles.openBundle(zip);
}
@Test
public void closeAndOpenBundleWithStringValue() throws Exception {
Bundle bundle = Bundles.createBundle();
Path hello = bundle.getRoot().resolve("hello.txt");
Bundles.setStringValue(hello, "Hello");
Path zip = Bundles.closeBundle(bundle);
Bundle newBundle = Bundles.openBundle(zip);
Path newHello = newBundle.getRoot().resolve("hello.txt");
assertEquals("Hello", Bundles.getStringValue(newHello));
}
@Test
public void closeAndSaveBundle() throws Exception {
Bundle bundle = Bundles.createBundle();
Path destination = Files.createTempFile("test", ".zip");
Files.delete(destination);
assertFalse(Files.exists(destination));
Bundles.closeAndSaveBundle(bundle, destination);
assertTrue(Files.exists(destination));
}
@Test
public void closeBundle() throws Exception {
Bundle bundle = Bundles.createBundle();
Path zip = Bundles.closeBundle(bundle);
assertTrue(Files.isReadable(zip));
assertEquals(zip, bundle.getSource());
checkSignature(zip);
}
@Test
public void createBundle() throws Exception {
Path source = null;
try (Bundle bundle = Bundles.createBundle()) {
assertTrue(Files.isDirectory(bundle.getRoot()));
source = bundle.getSource();
assertTrue(Files.exists(source));
}
// As it was temporary file it should be deleted on close
assertFalse(Files.exists(source));
}
@Test
public void createBundlePath() throws Exception {
Path source = Files.createTempFile("test", ".zip");
Files.delete(source);
try (Bundle bundle = Bundles.createBundle(source)) {
assertTrue(Files.isDirectory(bundle.getRoot()));
assertEquals(source, bundle.getSource());
assertTrue(Files.exists(source));
}
// As it was a specific path, it should NOT be deleted on close
assertTrue(Files.exists(source));
}
@Test
public void createBundlePathExists() throws Exception {
Path source = Files.createTempFile("test", ".zip");
assertTrue(Files.exists(source)); // will be overwritten
try (Bundle bundle = Bundles.createBundle(source)) {
}
// As it was a specific path, it should NOT be deleted on close
assertTrue(Files.exists(source));
}
@Test(expected=IOException.class)
public void createBundleExistsAsDirFails() throws Exception {
Path source = Files.createTempDirectory("test");
try (Bundle bundle = Bundles.createBundle(source)) {
}
}
@Test
public void getReference() throws Exception {
Bundle bundle = Bundles.createBundle();
Path hello = bundle.getRoot().resolve("hello");
Bundles.setReference(hello, URI.create("http://example.org/test"));
URI uri = Bundles.getReference(hello);
assertEquals("http://example.org/test", uri.toASCIIString());
}
@Test
public void getReferenceFromWin8() throws Exception {
Bundle bundle = Bundles.createBundle();
Path win8 = bundle.getRoot().resolve("win8");
Path win8Url = bundle.getRoot().resolve("win8.url");
Files.copy(getClass().getResourceAsStream("/win8.url"), win8Url);
URI uri = Bundles.getReference(win8);
assertEquals("http://example.com/made-in-windows-8", uri.toASCIIString());
}
@Test
public void getStringValue() throws Exception {
Bundle bundle = Bundles.createBundle();
Path hello = bundle.getRoot().resolve("hello");
String string = "A string";
Bundles.setStringValue(hello, string);
assertEquals(string, Bundles.getStringValue(hello));
assertEquals(null, Bundles.getStringValue(null));
}
protected boolean isEmpty(Path path) throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
return !ds.iterator().hasNext();
}
}
@Test
public void isMissing() throws Exception {
Bundle bundle = Bundles.createBundle();
Path missing = bundle.getRoot().resolve("missing");
assertFalse(Bundles.isValue(missing));
assertTrue(Bundles.isMissing(missing));
assertFalse(Bundles.isReference(missing));
}
@Test
public void isReference() throws Exception {
Bundle bundle = Bundles.createBundle();
Path ref = bundle.getRoot().resolve("ref");
Bundles.setReference(ref, URI.create("http://example.org/test"));
assertTrue(Bundles.isReference(ref));
assertFalse(Bundles.isMissing(ref));
assertFalse(Bundles.isValue(ref));
}
@Test
public void isValue() throws Exception {
Bundle bundle = Bundles.createBundle();
Path hello = bundle.getRoot().resolve("hello");
Bundles.setStringValue(hello, "Hello");
assertTrue(Bundles.isValue(hello));
assertFalse(Bundles.isReference(hello));
}
protected List<String> ls(Path path) throws IOException {
List<String> paths = new ArrayList<>();
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
for (Path p : ds) {
paths.add(p.getFileName() + "");
}
}
Collections.sort(paths);
return paths;
}
@Test
public void safeMove() throws Exception {
Path tmp = Files.createTempDirectory("test");
Path f1 = tmp.resolve("f1");
Files.createFile(f1);
assertFalse(isEmpty(tmp));
Bundle db = Bundles.createBundle();
Path f2 = db.getRoot().resolve("f2");
Bundles.safeMove(f1, f2);
assertTrue(isEmpty(tmp));
assertEquals(Arrays.asList("f2", "mimetype"), ls(db.getRoot()));
}
@Test(expected = IOException.class)
public void safeMoveFails() throws Exception {
Path tmp = Files.createTempDirectory("test");
Path f1 = tmp.resolve("f1");
Path d1 = tmp.resolve("d1");
Files.createFile(f1);
Files.createDirectory(d1);
try {
Bundles.safeMove(f1, d1);
} finally {
assertTrue(Files.exists(f1));
assertEquals(Arrays.asList("d1", "f1"), ls(tmp));
}
}
@Test
public void setReference() throws Exception {
Bundle bundle = Bundles.createBundle();
Path ref = bundle.getRoot().resolve("ref");
Bundles.setReference(ref, URI.create("http://example.org/test"));
URI uri = URI.create("http://example.org/test");
Path f = Bundles.setReference(ref, uri);
assertEquals("ref.url", f.getFileName().toString());
assertEquals(bundle.getRoot(), f.getParent());
assertFalse(Files.exists(ref));
List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII"));
assertEquals(3, uriLines.size());
assertEquals("[InternetShortcut]", uriLines.get(0));
assertEquals("URL=http://example.org/test", uriLines.get(1));
assertEquals("", uriLines.get(2));
}
@Test
public void setReferenceIri() throws Exception {
Bundle bundle = Bundles.createBundle();
Path ref = bundle.getRoot().resolve("ref");
URI uri = new URI("http", "xn--bcher-kva.example.com", "/s\u00F8iland/\u2603snowman", "\u2605star");
Path f = Bundles.setReference(ref, uri);
List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII"));
// TODO: Double-check that this is actually correct escaping :)
assertEquals("URL=http://xn--bcher-kva.example.com/s%C3%B8iland/%E2%98%83snowman#%E2%98%85star",
uriLines.get(1));
}
@Test
public void setStringValue() throws Exception {
Bundle bundle = Bundles.createBundle();
Path file = bundle.getRoot().resolve("file");
String string = "A string";
Bundles.setStringValue(file, string);
assertEquals(string, Files.readAllLines(file, Charset.forName("UTF-8")).get(0));
}
@Test
public void withExtension() throws Exception {
Path testDir = Files.createTempDirectory("test");
Path fileTxt = testDir.resolve("file.txt");
assertEquals("file.txt", fileTxt.getFileName().toString()); // better be!
Path fileHtml = Bundles.withExtension(fileTxt, ".html");
assertEquals(fileTxt.getParent(), fileHtml.getParent());
assertEquals("file.html", fileHtml.getFileName().toString());
Path fileDot = Bundles.withExtension(fileTxt, ".");
assertEquals("file.", fileDot.getFileName().toString());
Path fileEmpty = Bundles.withExtension(fileTxt, "");
assertEquals("file", fileEmpty.getFileName().toString());
Path fileDoc = Bundles.withExtension(fileEmpty, ".doc");
assertEquals("file.doc", fileDoc.getFileName().toString());
Path fileManyPdf = Bundles.withExtension(fileTxt, ".test.many.pdf");
assertEquals("file.test.many.pdf", fileManyPdf.getFileName().toString());
Path fileManyTxt = Bundles.withExtension(fileManyPdf, ".txt");
assertEquals("file.test.many.txt", fileManyTxt.getFileName().toString());
}
}
|
package ru.eqlbin.utils.net.ipv4.test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class SimpleTestWatcher extends TestWatcher {
public SimpleTestWatcher() {}
@Override
protected void succeeded(Description description) {
System.out.println(
String.format("%-6s [%s]: %s",
"OK",
description.getTestClass().getSimpleName(),
description.getMethodName())
);
}
@Override
protected void failed(Throwable e, Description description) {
System.out.println(
String.format("%-6s [%s]: %s
"FAILED",
description.getTestClass().getSimpleName(),
description.getMethodName(),
e)
);
}
}
|
import gov.nih.mipav.model.file.*;
import gov.nih.mipav.model.structures.ModelImage;
import gov.nih.mipav.model.structures.ModelStorageBase;
import gov.nih.mipav.plugins.PlugInFile;
import gov.nih.mipav.view.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import loci.common.DataTools;
import loci.formats.*;
import loci.formats.gui.GUITools;
import loci.formats.meta.IMetadata;
public class PlugInBioFormatsImporter implements PlugInFile {
// -- Constants --
/** Update progress bar no more often than this many milliseconds. */
protected static final int PROGRESS_THRESHOLD = 100;
// -- Fields --
protected DimensionSwapper reader;
protected JFileChooser chooser;
// -- Constructor --
public PlugInBioFormatsImporter() {
reader = new DimensionSwapper(new ChannelSeparator());
}
// -- PlugInFile API methods --
public boolean canReadImages() {
return true;
}
public boolean canWriteImages() {
return false;
}
public boolean isExtensionSupported(String ext) {
String[] suffixes = reader.getSuffixes();
ext = ext.toLowerCase();
// suffixes are alphabetized; use binary search
int min = 0, max = suffixes.length - 1;
while (min <= max) {
int index = (min + max) / 2;
int value = ext.compareTo(suffixes[index]);
if (value < 0) min = index + 1; // suffix is later in the list
else if (value > 0) max = index - 1; // suffix is earlier in the list
else return true; // found suffix
}
return false; // suffix not found
}
public void readImage() {
final ViewUserInterface mipav = ViewUserInterface.getReference();
// prompt user to choose a file
if (chooser == null) {
chooser = GUITools.buildFileChooser(reader);
chooser.setCurrentDirectory(new File(Preferences.getImageDirectory()));
}
JFrame parent = mipav.getMainFrame();
int rval = chooser.showOpenDialog(parent);
if (rval != JFileChooser.APPROVE_OPTION) return; // user canceled
final File file = chooser.getSelectedFile();
// load the image in a separate thread
Thread importerThread = new Thread("BioFormats-Importer") {
public void run() {
String name = file.getName();
String dir = file.getParent();
// open file using Bio-Formats
setMessage(mipav, "Importing " + name + "...", true);
String id = file.getPath();
try {
long tic = System.currentTimeMillis();
IMetadata store = MetadataTools.createOMEXMLMetadata();
reader.setMetadataStore(store);
reader.setId(id);
// MIPAV assumes 4-D data in XYZT order
reader.setOutputOrder("XYZTC");
// harvest some core metadata
int imageCount = reader.getImageCount();
boolean little = reader.isLittleEndian();
int pixelType = reader.getPixelType();
int bpp = FormatTools.getBytesPerPixel(pixelType);
boolean floating = FormatTools.isFloatingPoint(pixelType);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int sizeZ = reader.getSizeZ();
int sizeT = reader.getSizeT();
int sizeC = reader.getSizeC();
String imageName = store.getImageName(0);
if (sizeC > 1) {
throw new FormatException(
"Multichannel data is unsupported at the moment");
}
// compute MIPAV buffer type
int mipavType;
switch (pixelType) {
case FormatTools.INT8:
mipavType = ModelStorageBase.BYTE;
break;
case FormatTools.UINT8:
mipavType = ModelStorageBase.UBYTE;
break;
case FormatTools.INT16:
mipavType = ModelStorageBase.SHORT;
break;
case FormatTools.UINT16:
mipavType = ModelStorageBase.USHORT;
break;
case FormatTools.INT32:
mipavType = ModelStorageBase.INTEGER;
break;
case FormatTools.UINT32:
mipavType = ModelStorageBase.UINTEGER;
break;
case FormatTools.FLOAT:
mipavType = ModelStorageBase.FLOAT;
break;
case FormatTools.DOUBLE:
mipavType = ModelStorageBase.DOUBLE;
break;
default:
throw new FormatException("Unsupported pixel type: " + pixelType);
}
// harvest physical resolution
Float dimPhysSizeX = store.getDimensionsPhysicalSizeX(0, 0);
Float dimPhysSizeY = store.getDimensionsPhysicalSizeY(0, 0);
Float dimPhysSizeZ = store.getDimensionsPhysicalSizeZ(0, 0);
Float dimTimeInc = store.getDimensionsTimeIncrement(0, 0);
float physSizeX = dimPhysSizeX == null ?
1.0f : dimPhysSizeX.floatValue();
float physSizeY = dimPhysSizeY == null ?
1.0f : dimPhysSizeY.floatValue();
float physSizeZ = dimPhysSizeZ == null ?
1.0f : dimPhysSizeZ.floatValue();
float timeInc = dimTimeInc == null ? 1.0f : dimTimeInc.floatValue();
// compute dimensional extents
int[] dimExtents = {sizeX, sizeY, sizeZ, sizeT};
float[] res = {physSizeX, physSizeY, physSizeZ, timeInc};
int[] units = {
FileInfoBase.MICROMETERS, FileInfoBase.MICROMETERS,
FileInfoBase.MICROMETERS, FileInfoBase.SECONDS
};
// create MIPAV image object
ModelImage modelImage =
new ModelImage(mipavType, dimExtents, imageName);
// import planes into MIPAV image
byte[] buf = new byte[bpp * sizeX * sizeY];
for (int i=0; i<imageCount; i++) {
setMessage(mipav,
"Reading plane #" + (i + 1) + "/" + imageCount, false);
reader.openBytes(i, buf);
// convert byte array to appropriate primitive type
int offset = i * buf.length;
Object array = DataTools.makeDataArray(buf, bpp, floating, little);
// assign data to MIPAV image object
switch (mipavType) {
case ModelStorageBase.BYTE:
case ModelStorageBase.UBYTE:
modelImage.importData(offset, (byte[]) array, false);
break;
case ModelStorageBase.SHORT:
case ModelStorageBase.USHORT:
modelImage.importData(offset, (short[]) array, false);
break;
case ModelStorageBase.INTEGER:
case ModelStorageBase.UINTEGER:
modelImage.importData(offset, (int[]) array, false);
break;
case ModelStorageBase.FLOAT:
modelImage.importData(offset, (float[]) array, false);
break;
case ModelStorageBase.DOUBLE:
modelImage.importData(offset, (double[]) array, false);
break;
default:
throw new FormatException("Unknown buffer type: " + mipavType);
}
}
setMessage(mipav, "Finishing import...", true);
// create a FileInfo object for each image plane
FileInfoBase[] fileInfo = new FileInfoBase[imageCount];
for (int i=0; i<imageCount; i++) {
// HACK: Use FileInfoImageXML since FileInfoBase is abstract.
fileInfo[i] = new FileInfoImageXML(name, dir, FileUtility.XML);
fileInfo[i].setExtents(dimExtents);
fileInfo[i].setResolutions(res);
fileInfo[i].setUnitsOfMeasure(units);
fileInfo[i].setDataType(mipavType);
}
modelImage.setFileInfo(fileInfo);
// scale color range and display MIPAV image
modelImage.calcMinMax();
new ViewJFrameImage(modelImage);
long toc = System.currentTimeMillis();
long time = toc - tic;
long avg = time / imageCount;
setMessage(mipav, name + ": Read " + imageCount + " planes in " +
(time / 1000f) + " seconds (" + avg + " ms/plane)", true);
}
catch (FormatException exc) {
exc.printStackTrace();
MipavUtil.displayError(
"An error occurred parsing the file: " + exc.getMessage());
}
catch (IOException exc) {
exc.printStackTrace();
MipavUtil.displayError(
"An I/O error occurred reading the file: " + exc.getMessage());
}
}
};
importerThread.start();
}
public void writeImage(ModelImage image) {
throw new IllegalStateException("Unsupported");
}
// -- Helper methods --
private long lastTime = 0;
private synchronized void setMessage(final ViewUserInterface mipav,
final String message, final boolean force)
{
long time = System.currentTimeMillis();
long elapsed = time - lastTime;
if (elapsed >= PROGRESS_THRESHOLD || force) {
lastTime = time;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mipav.setMessageText(message);
}
});
}
}
}
|
package cn.net.openid.jos.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author Sutra Zhou
*
*/
public class Persona implements Serializable {
private static final long serialVersionUID = 1223541515197309353L;
private String id;
private User user;
private String name;
/**
* Any UTF-8 string that the End User wants to use as a nickname.
*/
private String nickname;
private String email;
/**
* UTF-8 string free text representation of the End User's full name.
*/
private String fullname;
/**
* The End User's date of birth as YYYY-MM-DD. Any values whose
* representation uses fewer than the specified number of digits should be
* zero-padded. The length of this value MUST always be 10. If the End User
* user does not want to reveal any particular component of this value, it
* MUST be set to zero. For instance, if a End User wants to specify that
* his date of birth is in 1980, but not the month or day, the value
* returned SHALL be "1980-00-00".
*/
private String dob;
/**
* The End User's gender, "M" for male, "F" for female.
*/
private String gender;
/**
* UTF-8 string free text that SHOULD conform to the End User's country's
* postal system.
*/
private String postcode;
private String country;
private String language;
private String timezone;
private Date creationDate;
public Persona() {
user = new User();
creationDate = new Date();
}
/**
* @param user
*/
public Persona(User user) {
this.user = user;
creationDate = new Date();
}
/**
* @return user
*/
public User getUser() {
return user;
}
/**
* @param user
* user
*/
public void setUser(User user) {
this.user = user;
}
/**
* @return country
*/
public String getCountry() {
return country;
}
/**
* @param country
* country
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return dob
*/
public String getDob() {
return dob;
}
/**
* @param dob
* dob
*/
public void setDob(String dob) {
this.dob = dob;
}
/*
* public void setDob(Date date) { this.dob = DOB_FORMAT.format(date); }
*/
/**
* @return email
*/
public String getEmail() {
return email;
}
/**
* @param email
* email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return fullname
*/
public String getFullname() {
return fullname;
}
/**
* @param fullname
* fullname
*/
public void setFullname(String fullname) {
this.fullname = fullname;
}
/**
* @return gender
*/
public String getGender() {
return gender;
}
/**
* @param gender
* gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* @return id
*/
public String getId() {
return id;
}
/**
* @param id
* id
*/
public void setId(String id) {
this.id = id;
}
/**
* @return language
*/
public String getLanguage() {
return language;
}
/**
* @param language
* language
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name
* name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return nickname
*/
public String getNickname() {
return nickname;
}
/**
* @param nickname
* nickname
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* @return postcode
*/
public String getPostcode() {
return postcode;
}
/**
* @param postcode
* postcode
*/
public void setPostcode(String postcode) {
this.postcode = postcode;
}
/**
* @return timezone
*/
public String getTimezone() {
return timezone;
}
/**
* @param timezone
* timezone
*/
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public void setLocale(Locale locale) {
this.country = locale.getCountry();
this.language = locale.getLanguage();
}
public Locale getLocale() {
return new Locale(this.language, this.country);
}
/**
* @return the creationDate
*/
public Date getCreationDate() {
return creationDate;
}
/**
* @param creationDate
* the creationDate to set
*/
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Map<String, String> toMap() {
Map<String, String> ret = new HashMap<String, String>();
ret.put("nickname", this.getNickname());
ret.put("email", this.getEmail());
ret.put("fullname", this.getFullname());
ret.put("dob", this.getDob());
ret.put("gender", this.getGender());
ret.put("postcode", this.getPostcode());
ret.put("country", this.getCountry());
ret.put("language", this.getLanguage());
ret.put("timezone", this.getTimezone());
return ret;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Persona other = (Persona) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
package org.muteswan.client.ui;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.muteswan.client.R;
import org.muteswan.client.TorStatus;
import org.muteswan.client.muteswan;
import org.muteswan.client.R.id;
import org.muteswan.client.R.layout;
import org.muteswan.client.data.Identity;
import org.muteswan.client.data.IdentityStore;
import org.muteswan.client.data.Circle;
import org.muteswan.client.data.CircleStore;
import org.muteswan.client.data.MuteswanMessage;
import org.muteswan.client.ui.LatestMessages.LatestMessagesListAdapter;
import org.json.JSONException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class WriteMsg extends ListActivity {
protected static final String SENT = "sent";
Circle circle;
boolean[] signSelections;
CharSequence[] signIdentities;
Identity[] identities;
String initialText;
final ArrayList<Circle> circles = new ArrayList<Circle>();
Boolean[] checkedCircles;
ListView listView;
public void onResume() {
super.onResume();
sendingMsgDialog = null;
}
public void onDestroy() {
super.onDestroy();
sendingMsgDialog = null;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
CircleStore cs = new CircleStore(getApplicationContext(),true);
if (extras != null) {
circle = new Circle(this,extras.getString("circle"));
initialText = extras.getString("initialText");
}
//initialize circles list
Log.v("CircleSize", "Circle store size: " + cs.size());
checkedCircles = new Boolean[cs.size()];
for (Circle c : cs) {
circles.add(c);
if (circle != null && c.getShortname().equals(circle.getShortname())) {
checkedCircles[cs.indexOf(c)] = true;
} else {
checkedCircles[cs.indexOf(c)] = false;
}
}
//setListAdapter(new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_multiple_choice, circleStrings));
setContentView(R.layout.writemsg);
// if (circle == null) {
setListAdapter(new WriteMsgListAdapter(null));
listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setClickable(false);
//} else {
// TextView tv = (TextView) findViewById(R.id.newPostLabel);
// tv.setText("");
TextView prompt = (TextView) findViewById(R.id.android_writemsgPrompt);
if (circle != null && prompt != null)
prompt.setText("Post to " + circle.getShortname());
IdentityStore idStore = new IdentityStore(getApplicationContext());
identities = idStore.asArray(true);
signIdentities = new CharSequence[identities.length];
for (int i=0; i<identities.length;i++) {
signIdentities[i] = identities[i].getName();
}
signSelections = new boolean[signIdentities.length];
for(int i=0; i<signSelections.length; i++) {
signSelections[i] = false;
}
final Button postButton = (Button) findViewById(R.id.submitMsg);
postButton.setOnClickListener(submitMsg);
if (initialText != null) {
EditText newMsgText = (EditText) findViewById(R.id.newMsgText);
newMsgText.setText(initialText);
}
}
@Override
protected void onListItemClick(ListView lv, View v, int pos, long id)
{
super.onListItemClick(lv, v, pos, id);
CheckedTextView tv = (CheckedTextView) v.findViewById(R.id.writeMsgCircleTextView);
if (tv.isChecked()) {
checkedCircles[pos] = false;
tv.setChecked(false);
} else {
checkedCircles[pos] = true;
tv.setChecked(true);
}
}
public class WriteMsgListAdapter extends BaseAdapter {
private Context context;
public WriteMsgListAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return circles.size();
}
@Override
public Object getItem(int position) {
return circles.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.writemsgcirclelist,
parent, false);
CheckedTextView circleTextView = (CheckedTextView) layout.findViewById(R.id.writeMsgCircleTextView);
circleTextView.setText(circles.get(position).getShortname());
if (checkedCircles[position] == true)
circleTextView.setChecked(true);
return layout;
}
}
@Override
protected Dialog onCreateDialog( int id )
{
return
new AlertDialog.Builder( this )
.setTitle( "Sign message with identity" )
.setMultiChoiceItems(signIdentities, signSelections, new DialogSelectionClickHandler() )
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.create();
}
public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
{
public void onClick( DialogInterface dialog, int clicked, boolean selected )
{
signSelections[clicked] = selected;
Log.v("WriteMsg", "Set " + clicked + " to " + selected);
}
}
public class DialogButtonClickHandler implements DialogInterface.OnClickListener
{
public void onClick( DialogInterface dialog, int clicked )
{
switch( clicked )
{
case DialogInterface.BUTTON_POSITIVE:
break;
}
}
}
public Button.OnClickListener selectSigButtonHandler = new View.OnClickListener() {
public void onClick( View v ) {
Log.v("WriteMsg", "select sig button clicked.\n");
showDialog( 0 );
}
};
protected ProgressDialog sendingMsgDialog;
private HashMap<String,String> sendingDialogData = new HashMap<String,String>();
final Handler updateSendDialog = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
if (b.getString("error") != null) {
if (sendingMsgDialog != null)
sendingMsgDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(WriteMsg.this);
builder.setMessage("A problem occurred: " + b.getString("error"))
.setCancelable(true).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}}
);
AlertDialog alert = builder.create();
alert.show();
return;
}
//sendingMsgDialog.dismiss();
//sendingMsgDialog.setCancelable(true);
if (sendingMsgDialog != null)
sendingMsgDialog.setMessage("Message posted: " + b.get("circles"));
if (b.get("circle") != null) {
sendingDialogData.put((String) b.get("circle"), (String)b.get("status"));
if (sendingMsgDialog != null)
sendingMsgDialog.setMessage(renderDialog(false));
}
//FIXME: not workable
Boolean finishedSending = true;
for (String key : sendingDialogData.keySet()) {
if (checkedCircles[b.getInt("position")] == true && sendingDialogData.get(key).equals(WriteMsg.SENT)) {
checkedCircles[b.getInt("position")] = false;
//circleTextView.setChecked(true);
}
if (!sendingDialogData.get(key).equals(WriteMsg.SENT)) {
finishedSending = false;
continue;
}
}
if (finishedSending == true) {
if (sendingMsgDialog != null)
sendingMsgDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(WriteMsg.this);
builder.setMessage("All messages sent successfully.")
.setCancelable(true).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}}
);
AlertDialog alert = builder.create();
alert.show();
//sendingMsgDialog.setMessage("All messages sent successfully.");
}
//for (Circle c : circles) {
// tv.setChecked(false);
//Toast.makeText(getApplicationContext(), "Message posted.", Toast.LENGTH_LONG).show();
}
};
private String renderDialog(Boolean finished) {
String dialogText = "Sending messages:";
for (String key : sendingDialogData.keySet()) {
dialogText = dialogText + "\n" + key + ": " + sendingDialogData.get(key);
}
return dialogText;
}
public Button.OnClickListener submitMsg = new Button.OnClickListener() {
public void onClick(final View v) {
EditText newMsgText = (EditText) findViewById(R.id.newMsgText);
Editable txt = newMsgText.getText();
final String txtData = txt.toString();
sendingMsgDialog = ProgressDialog.show(v.getContext(), "", "Sending message...", true);
sendingMsgDialog.setCancelable(true);
//FIXME: max sigs?
final Identity[] signIds = new Identity[50];
int j = 0;
for(int i=0; i<signSelections.length; i++) {
if (signSelections[i] == true) {
signIds[j] = identities[i];
j++;
}
}
// final Handler dismissDialog = new Handler() {
// @Override
// public void handleMessage(Message msg) {
// sendingMsgDialog.dismiss();
// Toast.makeText(v.getContext(), "Message posted.", Toast.LENGTH_LONG).show();
Boolean atleastOneCircle = false;
for (final Circle cir: circles) {
if (checkedCircles[circles.indexOf(cir)] == false)
continue;
atleastOneCircle = true;
if (txtData == null || txtData.equals("")) {
Bundle b = new Bundle();
Message msg = Message.obtain();
b.putString("error", "Empty message.");
msg.setData(b);
updateSendDialog.sendMessage(msg);
return;
}
//TextView txt2 = new TextView(v.getContext());
if (signIds[0] != null) {
Log.v("WriteMsg", "Posting with signatures...");
new Thread() {
public void run() {
Bundle b = new Bundle();
Message msg = Message.obtain();
b.putString("circle", cir.getShortname());
b.putString("status", "sending...");
msg.setData(b);
updateSendDialog.sendMessage(msg);
try {
Integer httpCode = cir.postMsg(txtData,signIds);
Bundle b2 = new Bundle();
Message msg2 = Message.obtain();
b2.putString("circle", cir.getShortname());
b2.putInt("position",circles.indexOf(cir));
msg2.setData(b2);
if (httpCode == 200) {
b2.putString("status", WriteMsg.SENT);
} else if (httpCode >= 500) {
b2.putString("status", "server error");
} else if (httpCode < 0) {
b2.putString("status", "timeout");
}
updateSendDialog.sendMessage(msg2);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
} else {
new Thread() {
public void run() {
Bundle b = new Bundle();
Message msg = Message.obtain();
msg.setData(b);
b.putString("circle", cir.getShortname());
b.putString("status", "sending...");
updateSendDialog.sendMessage(msg);
try {
Integer httpCode = cir.postMsg(txtData);
Bundle b2 = new Bundle();
Message msg2 = Message.obtain();
b2.putString("circle", cir.getShortname());
b2.putInt("position",circles.indexOf(cir));
msg2.setData(b2);
if (httpCode == 200) {
b2.putString("status", WriteMsg.SENT);
} else if (httpCode >= 500) {
b2.putString("status", "server error");
} else if (httpCode < 0) {
b2.putString("status", "timeout");
}
updateSendDialog.sendMessage(msg2);
//dismissDialog.sendEmptyMessage(0);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
if (atleastOneCircle == false) {
Bundle b2 = new Bundle();
Message msg2 = Message.obtain();
b2.putString("error", "No circle selected.");
msg2.setData(b2);
updateSendDialog.sendMessage(msg2);
}
}
};
}
|
package info.elexis.server.core.p2.console;
import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.elexis.server.core.p2.internal.HTTPServiceHelper;
import info.elexis.server.core.p2.internal.ProvisioningHelper;
@Component(service = CommandProvider.class, immediate = true)
public class ConsoleCommandProvider implements CommandProvider {
public static final String MAIN_CMD = "es_p2";
public static final String HELP_PREPEND = "Usage: " + MAIN_CMD + " ";
private Logger log = LoggerFactory.getLogger(ConsoleCommandProvider.class);
public void _es_p2(CommandInterpreter ci) {
final String argument = ci.nextArgument();
try {
if (argument == null) {
System.out.println(getHelp());
return;
}
switch (argument.toLowerCase()) {
case "repo":
System.out.println(repo(ci));
return;
case "features":
System.out.println(features(ci));
return;
case "executeUpdate":
System.out.println(ProvisioningHelper.updateAllFeatures().getMessage());
return;
default:
System.out.println(getHelp());
return;
}
} catch (Exception e) {
log.error("Execution error on argument " + argument, e);
}
}
private String features(final CommandInterpreter ci) {
final String argument = ci.nextArgument();
if (argument == null) {
return HELP_PREPEND + "features (listLocal | install | uninstall)";
}
final String featureName = ci.nextArgument();
switch (argument) {
case "listLocal":
return ProvisioningHelper.getAllInstalledFeatures().stream()
.map(i -> i.getId() + " (" + i.getVersion() + ")").reduce((u, t) -> u + "\n" + t).get();
case "install":
return ProvisioningHelper.installFeature(featureName);
case "uninstall":
return ProvisioningHelper.uninstallFeature(featureName);
}
return getHelp();
}
private String repo(final CommandInterpreter ci) {
final String argument = ci.nextArgument();
if (argument == null) {
return HELP_PREPEND + "repo (list | add | remove )";
}
switch (argument) {
case "list":
return HTTPServiceHelper.getRepoInfo(null).toString();
case "add":
return repoManage(true, ci);
case "remove":
return repoManage(false, ci);
default:
break;
}
return getHelp();
}
private String repoManage(boolean b, CommandInterpreter ci) {
final String argument = ci.nextArgument();
if (argument == null) {
return HELP_PREPEND + "repo (list | add ) repo_url [username] [password]";
}
final String username = ci.nextArgument();
final String password = ci.nextArgument();
if (b) {
return HTTPServiceHelper.doRepositoryAdd(argument, username, password).getStatusInfo().toString();
} else {
return HTTPServiceHelper.doRepositoryRemove(argument).getStatusInfo().toString();
}
}
@Override
public String getHelp() {
return HELP_PREPEND + "(repo | features | executeUpdate)";
}
}
|
/*
* $Id: TestIdentityManagerImpl.java,v 1.27 2013-07-19 17:11:59 barry409 Exp $
*/
package org.lockss.protocol;
import java.io.File;
import java.io.StringReader;
import java.util.*;
import junit.framework.Test;
import org.lockss.util.*;
import org.lockss.config.*;
import org.lockss.daemon.status.*;
import org.lockss.plugin.*;
import org.lockss.poller.*;
import org.lockss.repository.*;
import org.lockss.test.*;
/** Test cases for org.lockss.protocol.IdentityManager that assume the
* IdentityManager has been initialized. See TestIdentityManagerInit for
* more IdentityManager tests. */
public abstract class TestIdentityManagerImpl extends LockssTestCase {
/**
* <p>A version of {@link TestIdentityManagerImpl} that forces the
* serialization compatibility mode to
* {@link CXSerializer#CASTOR_MODE}.</p>
* @author Thib Guicherd-Callin
*/
public static class WithCastor extends TestIdentityManagerImpl {
public void setUp() throws Exception {
super.setUp();
ConfigurationUtil.addFromArgs(CXSerializer.PARAM_COMPATIBILITY_MODE,
Integer.toString(CXSerializer.CASTOR_MODE));
}
}
/**
* <p>A version of {@link TestIdentityManagerImpl} that forces the
* serialization compatibility mode to
* {@link CXSerializer#XSTREAM_MODE}.</p>
* @author Thib Guicherd-Callin
*/
public static class WithXStream extends TestIdentityManagerImpl {
public void setUp() throws Exception {
super.setUp();
ConfigurationUtil.addFromArgs(CXSerializer.PARAM_COMPATIBILITY_MODE,
Integer.toString(CXSerializer.XSTREAM_MODE));
}
}
public static Test suite() {
return variantSuites(TestIdentityManagerImpl.class);
}
Object testIdKey;
private MockLockssDaemon theDaemon;
private TestableIdentityManager idmgr;
String tempDirPath;
PeerIdentity peer1;
PeerIdentity peer2;
PeerIdentity peer3;
PeerIdentity peer4;
MockArchivalUnit mau;
private static final String LOCAL_IP = "127.1.2.3";
private static final String IP_2 = "127.6.5.4";
private static final String LOCAL_V3_ID = "TCP:[127.1.2.3]:3141";
private static final int LOCAL_PORT_NUM = 3141;
// private static final String LOCAL_PORT = "3141";
private static final String LOCAL_PORT = Integer.toString(LOCAL_PORT_NUM);
public void setUp() throws Exception {
super.setUp();
mau = new MockArchivalUnit();
tempDirPath = getTempDir().getAbsolutePath() + File.separator;
ConfigurationUtil.setCurrentConfigFromProps(commonConfig());
theDaemon = getMockLockssDaemon();
idmgr = new TestableIdentityManager();
idmgr.initService(theDaemon);
theDaemon.setIdentityManager(idmgr);
theDaemon.setHistoryRepository(new MockHistoryRepository(), mau);
idmgr.startService();
}
public void tearDown() throws Exception {
if (idmgr != null) {
idmgr.stopService();
idmgr = null;
}
super.tearDown();
}
Properties commonConfig() {
Properties p = new Properties();
p.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath);
p.setProperty(IdentityManager.PARAM_IDDB_DIR, tempDirPath + "iddb");
p.setProperty(IdentityManager.PARAM_LOCAL_IP, LOCAL_IP);
p.setProperty(IdentityManager.PARAM_IDDB_DIR, tempDirPath);
p.setProperty(IdentityManager.PARAM_MIN_PERCENT_AGREEMENT, "0.9");
return p;
}
void setupPeer123() throws IdentityManager.MalformedIdentityKeyException {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
peer2 = idmgr.stringToPeerIdentity("127.0.0.2");
peer3 = idmgr.stringToPeerIdentity("127.0.0.3");
peer4 = idmgr.stringToPeerIdentity("tcp:[127.0.0.4]:4444");
}
public void testSetupLocalIdentitiesV1Only()
throws IdentityManager.MalformedIdentityKeyException {
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
assertNull(mgr.localPeerIdentities[Poll.V3_PROTOCOL]);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V1_PROTOCOL];
PeerIdentity pid2 = mgr.stringToPeerIdentity(LOCAL_IP);
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
assertSame(pid1, pid2);
PeerAddress pa = pid1.getPeerAddress();
assertTrue(pa instanceof PeerAddress.Udp);
assertEquals(LOCAL_IP, ((PeerAddress.Udp)pa).getIPAddr().getHostAddress());
assertEquals(ListUtil.list(pid1), mgr.getLocalPeerIdentities());
}
public void testSetupLocalIdentitiesV3Normal()
throws IdentityManager.MalformedIdentityKeyException {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_PORT,
LOCAL_PORT);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS,
LOCAL_V3_ID);
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
String key = IDUtil.ipAddrToKey(LOCAL_IP, LOCAL_PORT_NUM);
PeerIdentity pid2 = mgr.stringToPeerIdentity(key);
assertSame(pid1, pid2);
PeerAddress pa = pid1.getPeerAddress();
assertTrue(pa instanceof PeerAddress.Tcp);
assertEquals(LOCAL_IP, ((PeerAddress.Tcp)pa).getIPAddr().getHostAddress());
assertEquals(LOCAL_PORT_NUM, ((PeerAddress.Tcp)pa).getPort());
assertEquals(ListUtil.list(mgr.stringToPeerIdentity(LOCAL_IP),pid1),
mgr.getLocalPeerIdentities());
}
public void testSetupLocalIdentitiesV3Only()
throws IdentityManager.MalformedIdentityKeyException {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_PORT,
LOCAL_PORT);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS,
LOCAL_V3_ID);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_ENABLE_V1,
"false");
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
assertNull(mgr.localPeerIdentities[Poll.V1_PROTOCOL]);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
String key = IDUtil.ipAddrToKey(LOCAL_IP, LOCAL_PORT_NUM);
PeerIdentity pid2 = mgr.stringToPeerIdentity(key);
assertSame(pid1, pid2);
PeerAddress pa = pid1.getPeerAddress();
assertTrue(pa instanceof PeerAddress.Tcp);
assertEquals(LOCAL_IP, ((PeerAddress.Tcp)pa).getIPAddr().getHostAddress());
assertEquals(LOCAL_PORT_NUM, ((PeerAddress.Tcp)pa).getPort());
assertEquals(ListUtil.list(pid1), mgr.getLocalPeerIdentities());
}
public void testSetupLocalIdentitiesV3FromLocalV3IdentityParam()
throws Exception {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_IDENTITY,
LOCAL_V3_ID);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS,
LOCAL_V3_ID);
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
String key = IDUtil.ipAddrToKey(LOCAL_IP, LOCAL_PORT_NUM);
PeerIdentity pid2 = mgr.stringToPeerIdentity(key);
assertSame(pid1, pid2);
PeerAddress pa = pid1.getPeerAddress();
assertTrue(pa instanceof PeerAddress.Tcp);
assertEquals(LOCAL_IP, ((PeerAddress.Tcp)pa).getIPAddr().getHostAddress());
assertEquals(LOCAL_PORT_NUM, ((PeerAddress.Tcp)pa).getPort());
}
public void testSetupLocalIdentitiesV3Override()
throws IdentityManager.MalformedIdentityKeyException {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_PORT,
LOCAL_PORT,
IdentityManager.PARAM_LOCAL_V3_IDENTITY,
IDUtil.ipAddrToKey(IP_2,
(LOCAL_PORT_NUM + 123)));
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.setupLocalIdentities();
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
PeerAddress pa = pid1.getPeerAddress();
assertTrue(pa instanceof PeerAddress.Tcp);
assertEquals(IP_2, ((PeerAddress.Tcp)pa).getIPAddr().getHostAddress());
assertEquals(LOCAL_PORT_NUM + 123, ((PeerAddress.Tcp)pa).getPort());
}
/** test for method stringToPeerIdentity **/
public void testStringToPeerIdentity() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
assertNotNull(peer1);
assertSame(peer1, idmgr.stringToPeerIdentity("127.0.0.1"));
peer2 = idmgr.stringToPeerIdentity("127.0.0.2");
assertNotNull(peer2);
assertNotEquals(peer1, peer2);
peer3 = idmgr.stringToPeerIdentity(IDUtil.ipAddrToKey("127.0.0.2", "300"));
assertNotNull(peer3);
assertNotEquals(peer3, peer2);
assertNotEquals(peer3, peer1);
}
// XXX this should go away
public void testStringToPeerIdentityNull() throws Exception {
peer1 = idmgr.stringToPeerIdentity(null);
assertTrue(peer1.isLocalIdentity());
assertSame(peer1, idmgr.getLocalPeerIdentity(Poll.V1_PROTOCOL));
}
/** test for method ipAddrToPeerIdentity **/
public void testIPAddrToPeerIdentity() throws Exception {
IPAddr ip1 = IPAddr.getByName("127.0.0.1");
IPAddr ip2 = IPAddr.getByName("127.0.0.2");
IPAddr ip3 = IPAddr.getByName("127.0.0.3");
peer1 = idmgr.ipAddrToPeerIdentity(ip1);
assertNotNull(peer1);
assertSame(peer1, idmgr.ipAddrToPeerIdentity(ip1));
assertSame(peer1, idmgr.stringToPeerIdentity("127.0.0.1"));
peer2 = idmgr.ipAddrToPeerIdentity(ip2);
assertNotNull(peer2);
assertNotEquals(peer1, peer2);
assertSame(peer2, idmgr.stringToPeerIdentity("127.0.0.2"));
peer3 = idmgr.ipAddrToPeerIdentity(ip2, 300);
assertNotNull(peer3);
assertNotEquals(peer3, peer2);
assertNotEquals(peer3, peer1);
assertSame(peer3,
idmgr.stringToPeerIdentity(IDUtil.ipAddrToKey("127.0.0.2",
"300")));
}
// XXX this should go away
public void testIPAddrToPeerIdentityNull() throws Exception {
peer1 = idmgr.ipAddrToPeerIdentity(null);
assertTrue(peer1.isLocalIdentity());
assertSame(peer1, idmgr.getLocalPeerIdentity(Poll.V1_PROTOCOL));
}
public void testIdentityToIPAddr() throws Exception {
IPAddr ip1 = IPAddr.getByName("127.0.0.1");
IPAddr ip2 = IPAddr.getByName("127.0.0.2");
peer1 = idmgr.ipAddrToPeerIdentity(ip1);
peer2 = idmgr.ipAddrToPeerIdentity(ip2);
assertEquals(ip1, idmgr.identityToIPAddr(peer1));
assertEquals(ip2, idmgr.identityToIPAddr(peer2));
}
public void testIdentityToIPAddrV3() throws Exception {
peer1 = idmgr.stringToPeerIdentity(IDUtil.ipAddrToKey("127.0.0.1", "23"));
try {
idmgr.identityToIPAddr(peer1);
fail("identityToIPAddr(V3PeerId) should throw");
} catch (IllegalArgumentException e) {
}
}
public void testGetLocalIdentity() {
peer1 = idmgr.getLocalPeerIdentity(Poll.V1_PROTOCOL);
assertTrue(peer1.isLocalIdentity());
assertTrue(idmgr.isLocalIdentity(peer1));
String key = peer1.getIdString();
assertTrue(idmgr.isLocalIdentity(key));
}
public void testGetLocalIdentityIll() {
try {
peer1 = idmgr.getLocalPeerIdentity(Poll.MAX_PROTOCOL + 32);
fail("getLocalPeerIdentity(" + (Poll.MAX_PROTOCOL + 32) +
") should throw");
} catch (IllegalArgumentException e) {
}
}
void checkReputation(int orgRep, int maxDelta, int curRep) {
if(maxDelta > 0) {
assertTrue(curRep <= orgRep + maxDelta);
}
else if(maxDelta < 0) {
assertTrue(curRep >= orgRep + maxDelta);
}
}
/** test for method agreeWithVote(..) */
public void testAgreeWithVote() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1, IdentityManager.AGREE_VOTE);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.AGREE_VOTE],
idmgr.getReputation(peer1));
}
/** test for method disagreeWithVote(..) */
public void testDisagreeWithVote() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.DISAGREE_VOTE);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.DISAGREE_VOTE],
idmgr.getReputation(peer1));
}
/** test for method callInternalPoll(..) */
public void testCallInternalPoll() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.CALL_INTERNAL);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.CALL_INTERNAL],
idmgr.getReputation(peer1));
}
/** test for method spoofDetected(..) */
public void testSpoofDetected() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.SPOOF_DETECTED);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.SPOOF_DETECTED],
idmgr.getReputation(peer1));
}
/** test for method replayDected(..) */
public void testReplayDetected() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.REPLAY_DETECTED);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.REPLAY_DETECTED],
idmgr.getReputation(peer1));
}
/** test for method acttackDetected(..) */
public void testAttackDetected() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.ATTACK_DETECTED);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.ATTACK_DETECTED],
idmgr.getReputation(peer1));
}
/** test for method voteNotVerify(..) */
public void testVoteNotVerify() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.VOTE_NOTVERIFIED);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.VOTE_NOTVERIFIED],
idmgr.getReputation(peer1));
}
/** test for method voteVerify(..) */
public void testVoteVerify() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.VOTE_VERIFIED);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.VOTE_VERIFIED],
idmgr.getReputation(peer1));
}
/** test for method voteDisown(..) */
public void testVoteDisown() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
int rep = idmgr.getReputation(peer1);
idmgr.changeReputation(peer1,IdentityManager.VOTE_DISOWNED);
checkReputation(rep, idmgr.reputationDeltas[IdentityManager.VOTE_DISOWNED],
idmgr.getReputation(peer1));
}
public void testStoreIdentities() throws Exception {
setupPeer123();
idmgr.storeIdentities();
}
public void testLoadIdentities() throws Exception {
// Store
setupPeer123();
idmgr.storeIdentities();
// Load
MockLockssDaemon otherDaemon = getMockLockssDaemon();
IdentityManagerImpl im = new IdentityManagerImpl();
im.initService(otherDaemon);
otherDaemon.setIdentityManager(im);
im.reloadIdentities();
im.findPeerIdentity("127.0.0.2");
}
public void testSignalAgreedThrowsOnNullAu() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
try {
idmgr.signalAgreed(peer1, null);
fail("Should have thrown on a null au");
} catch (IllegalArgumentException e) {
}
}
public void testSignalAgreedThrowsOnNullId() throws Exception {
try {
idmgr.signalAgreed(null, mau);
fail("Should have thrown on a null au");
} catch (IllegalArgumentException e) {
}
}
public void testSignalDisagreedThrowsOnNullAu() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
try {
idmgr.signalDisagreed(peer1, null);
fail("Should have thrown on a null au");
} catch (IllegalArgumentException e) {
}
}
public void testSignalDisagreedThrowsOnNullId() throws Exception {
try {
idmgr.signalDisagreed(null, mau);
fail("Should have thrown on a null au");
} catch (IllegalArgumentException e) {
}
}
public void testSignalAgreedWithLocalIdentity() throws Exception {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_PORT,
LOCAL_PORT);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS,
LOCAL_V3_ID);
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
assertEmpty(mgr.getAgreed(mau));
mgr.signalAgreed(pid1,mau);
assertEquals(1, mgr.getAgreed(mau).size());
assertNotNull(mgr.getAgreed(mau).get(pid1));
}
public void testSignalDisagreedWithLocalIdentity() throws Exception {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_PORT,
LOCAL_PORT);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS,
LOCAL_V3_ID);
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
assertEmpty(mgr.getDisagreed(mau));
mgr.signalDisagreed(pid1,mau);
assertEquals(1, mgr.getDisagreed(mau).size());
assertNotNull(mgr.getDisagreed(mau).get(pid1));
}
public void testSignalWithLocalIdentityDoesntRemove() throws Exception {
TimeBase.setSimulated(10);
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_LOCAL_V3_PORT,
LOCAL_PORT);
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS,
LOCAL_V3_ID);
IdentityManagerImpl mgr = new IdentityManagerImpl();
mgr.initService(theDaemon);
PeerIdentity pid1 = mgr.localPeerIdentities[Poll.V3_PROTOCOL];
assertTrue("Peer ID is not a local identity.", pid1.isLocalIdentity());
assertEmpty(mgr.getDisagreed(mau));
mgr.signalDisagreed(pid1,mau);
assertEquals(1, mgr.getDisagreed(mau).size());
assertNotNull(mgr.getDisagreed(mau).get(pid1));
assertEmpty(mgr.getAgreed(mau));
TimeBase.step();
mgr.signalAgreed(pid1,mau);
assertEquals(1, mgr.getAgreed(mau).size());
assertNotNull(mgr.getAgreed(mau).get(pid1));
assertEquals(1, mgr.getDisagreed(mau).size());
assertNotNull(mgr.getDisagreed(mau).get(pid1));
TimeBase.step();
mgr.signalDisagreed(pid1,mau);
assertEquals(1, mgr.getAgreed(mau).size());
assertNotNull(mgr.getAgreed(mau).get(pid1));
assertEquals(1, mgr.getDisagreed(mau).size());
assertNotNull(mgr.getDisagreed(mau).get(pid1));
}
public void testGetAgreeThrowsOnNullAu() throws Exception {
try {
idmgr.getAgreed(null);
fail("Should have thrown on a null au");
} catch (IllegalArgumentException e) {
}
}
public void testGetAgreedNoneSet() throws Exception {
assertEmpty(idmgr.getAgreed(mau));
}
public void testHasAgreed() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
assertFalse(idmgr.hasAgreed(peer1, mau));
assertFalse(idmgr.hasAgreed(peer2, mau));
idmgr.signalAgreed(peer1, mau);
assertTrue(idmgr.hasAgreed(peer1, mau));
assertFalse(idmgr.hasAgreed(peer2, mau));
TimeBase.step();
idmgr.signalAgreed(peer2, mau);
assertTrue(idmgr.hasAgreed(peer1, mau));
assertTrue(idmgr.hasAgreed(peer2, mau));
}
public void testGetAgreed() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
idmgr.signalAgreed(peer1, mau);
TimeBase.step();
idmgr.signalAgreed(peer2, mau);
Map expected = new HashMap();
expected.put(peer1, new Long(10));
expected.put(peer2, new Long(11));
assertEquals(expected, idmgr.getAgreed(mau));
}
public void testSignalPartialAgreement() throws Exception {
setupPeer123();
idmgr.signalPartialAgreement(peer1, mau, 0.85f);
idmgr.signalPartialAgreement(peer2, mau, 0.95f);
idmgr.signalPartialAgreement(peer3, mau, 1.00f);
assertEquals(0.85f, idmgr.getPercentAgreement(peer1, mau), 0.001f);
assertEquals(0.95f, idmgr.getPercentAgreement(peer2, mau), 0.001f);
assertEquals(1.00f, idmgr.getPercentAgreement(peer3, mau), 0.001f);
}
public void testSignalPartialAgreementDisagreementThreshold()
throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
assertFalse(idmgr.hasAgreed(peer1, mau));
assertFalse(idmgr.hasAgreed(peer2, mau));
assertFalse(idmgr.hasAgreed(peer3, mau));
idmgr.signalPartialAgreement(peer1, mau, 0.49f);
TimeBase.step();
idmgr.signalPartialAgreement(peer2, mau, 0.50f);
TimeBase.step();
idmgr.signalPartialAgreement(peer3, mau, 0.51f);
Map expectedDisagree = new HashMap();
expectedDisagree.put(peer1, new Long(10));
Map expectedAgree = new HashMap();
expectedAgree.put(peer2, new Long(11));
expectedAgree.put(peer3, new Long(12));
assertFalse(idmgr.hasAgreed(peer1, mau));
assertTrue(idmgr.hasAgreed(peer2, mau));
assertTrue(idmgr.hasAgreed(peer3, mau));
assertEquals(expectedDisagree, idmgr.getDisagreed(mau));
assertEquals(expectedAgree, idmgr.getAgreed(mau));
}
public void testGetIdentityAgreements() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
idmgr.signalAgreed(peer1, mau);
TimeBase.step();
idmgr.signalAgreed(peer2, mau);
idmgr.signalDisagreed(peer2, mau);
idmgr.signalPartialAgreement(peer4, mau, 0.8f);
// now create IdentityAgreement objects that should be equal to what
// idmgr created.
IdentityManager.IdentityAgreement ida1 =
new IdentityManager.IdentityAgreement(peer1);
ida1.setLastAgree(10);
ida1.setPercentAgreement(1.0f);
ida1.setHighestPercentAgreement(1.0f);
IdentityManager.IdentityAgreement ida2 =
new IdentityManager.IdentityAgreement(peer2);
ida2.setLastAgree(11);
ida2.setLastDisagree(11);
ida2.setHighestPercentAgreement(1.0f);
IdentityManager.IdentityAgreement ida4 =
new IdentityManager.IdentityAgreement(peer4);
idmgr.signalPartialAgreement(peer4, mau, 0.8f);
ida4.setPercentAgreement(0.8f);
ida4.setLastAgree(11);
// Set set1 = SetUtil.set(ida1, ida2);
// Set set2 = SetUtil.theSet(idmgr.getIdentityAgreements(mau));
// Iterator it1 = set1.iterator();
// Iterator it2 = set2.iterator();
// while (it1.hasNext()) {
// Object obj1 = it1.next();
// Object obj2 = it2.next();
// System.err.println(obj1.getClass().getName());
// System.err.println(obj2.getClass().getName());
// assertEquals(obj1, obj2);
// assertEquals(set1.size(), set2.size());
// assertTrue(set2.containsAll(set1));
// assertTrue(set1.containsAll(set2));
// assertTrue(set1.equals(set2));
// assertTrue(SetUtil.set(ida1, ida2).equals(SetUtil.theSet(idmgr.getIdentityAgreements(mau))));
assertEquals(SetUtil.set(ida1, ida2, ida4),
SetUtil.theSet(idmgr.getIdentityAgreements(mau)));
idmgr.setIdentity(Poll.V1_PROTOCOL, null);
assertEquals(SetUtil.set(ida4),
SetUtil.theSet(idmgr.getIdentityAgreements(mau)));
}
public void testHasAgreeMap() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
assertFalse(idmgr.hasAgreeMap(mau));
idmgr.signalAgreed(peer1, mau);
assertTrue(idmgr.hasAgreeMap(mau));
}
// ensure that deisctivating and reactivating an AU gets it's old data
// back (i.e., uses auid not au as key in maps
public void testAgreedUsesAuid() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
idmgr.signalAgreed(peer1, mau);
TimeBase.step();
idmgr.signalAgreed(peer2, mau);
Map expected = new HashMap();
expected.put(peer1, new Long(10));
expected.put(peer2, new Long(11));
assertEquals(expected, idmgr.getAgreed(mau));
MockArchivalUnit mau2 = new MockArchivalUnit();
// simulate desctivating and reactivating an AU, which creates a new AU
// instance with the same auid
mau2.setAuId(mau.getAuId());
assertEquals(expected, idmgr.getAgreed(mau2));
}
public void testDisagreeDoesntRemove() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
idmgr.signalAgreed(peer1, mau);
idmgr.signalAgreed(peer2, mau);
idmgr.signalDisagreed(peer1, mau);
Map expected = new HashMap();
expected.put(peer1, new Long(10));
expected.put(peer2, new Long(10));
assertEquals(expected, idmgr.getAgreed(mau));
}
public void testGetCachesToRepairFromThrowsOnNullAu()
throws Exception {
try {
idmgr.getCachesToRepairFrom(null);
fail("Should have thrown on a null au");
} catch (IllegalArgumentException e) {
}
}
public void testGetCachesToRepairFromNoneSet() throws Exception {
assertEmpty(idmgr.getCachesToRepairFrom(mau));
}
public void testCachesToRepairFrom() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
idmgr.signalAgreed(peer1, mau);
idmgr.signalDisagreed(peer2, mau);
TimeBase.step();
idmgr.signalDisagreed(peer1, mau);
idmgr.signalAgreed(peer2, mau);
idmgr.signalAgreed(peer3, mau);
List toRepair = idmgr.getCachesToRepairFrom(mau);
assertSameElements(ListUtil.list(peer1, peer2, peer3), toRepair);
// peer2,3 can be in either order, but peer1 must be last because it
// has a disagreement
assertEquals(peer1, toRepair.get(2));
}
public void testAgreeUpdatesTime() throws Exception {
TimeBase.setSimulated(10);
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
idmgr.signalAgreed(peer1, mau);
TimeBase.step(15);
idmgr.signalAgreed(peer1, mau);
Map expected = new HashMap();
expected.put(peer1, new Long(25));
assertEquals(expected, idmgr.getAgreed(mau));
}
public void testMultipleAus() throws Exception {
TimeBase.setSimulated(10);
setupPeer123();
MockArchivalUnit mau1 = new MockArchivalUnit();
MockArchivalUnit mau2 = new MockArchivalUnit();
log.info("auid1: " + mau1.getAuId());
log.info("auid2: " + mau2.getAuId());
theDaemon.setHistoryRepository(new MockHistoryRepository(), mau1);
theDaemon.setHistoryRepository(new MockHistoryRepository(), mau2);
idmgr.signalAgreed(peer1, mau1);
idmgr.signalAgreed(peer2, mau2);
idmgr.signalDisagreed(peer1, mau2);
Map expected = new HashMap();
expected.put(peer2, new Long(10));
assertEquals(expected, idmgr.getAgreed(mau2));
expected = new HashMap();
expected.put(peer1, new Long(10));
assertEquals(expected, idmgr.getAgreed(mau1));
}
public void testIdentityAgreementEquals() {
IdentityManager.IdentityAgreement a1 = new MyIdentityAgreement("id1");
IdentityManager.IdentityAgreement a2 = new MyIdentityAgreement("id1");
IdentityManager.IdentityAgreement a3 = new MyIdentityAgreement("id3");
assertEquals(a1, a2);
assertNotEquals(a1, a3);
a1.setLastAgree(8);
assertNotEquals(a1, a2);
a2.setLastAgree(8);
assertEquals(a1, a2);
a1.setLastDisagree(12);
assertNotEquals(a1, a2);
a2.setLastDisagree(12);
assertEquals(a1, a2);
}
public void testIdentityAgreementHash() {
IdentityManager.IdentityAgreement a1 = new MyIdentityAgreement("id1");
IdentityManager.IdentityAgreement a2 = new MyIdentityAgreement("id1");
assertEquals(a1.hashCode(), a2.hashCode());
a1.setLastAgree(8);
a2.setLastAgree(8);
a1.setLastDisagree(12);
a2.setLastDisagree(12);
assertEquals(a1.hashCode(), a2.hashCode());
}
static class MyIdentityAgreement extends IdentityManager.IdentityAgreement {
MyIdentityAgreement(String id) {
super();
setId(id);
}
}
public void testStoreIdentityAgreement() throws Exception {
MockHistoryRepository hRep = new MockHistoryRepository();
theDaemon.setHistoryRepository(hRep, mau);
setupPeer123();
idmgr.signalAgreed(peer1, mau);
idmgr.signalAgreed(peer2, mau);
idmgr.signalDisagreed(peer1, mau);
idmgr.signalDisagreed(peer3, mau);
List expected = new ArrayList();
IdentityManager.IdentityAgreement ida =
new IdentityManager.IdentityAgreement(peer1);
ida.setLastAgree(10);
ida.setLastDisagree(10);
ida.setPercentAgreement(0.0f);
ida.setHighestPercentAgreement(1.0f);
expected.add(ida);
assertContains(SetUtil.theSet(hRep.getStoredIdentityAgreement()), ida);
ida = new IdentityManager.IdentityAgreement(peer2);
ida.setLastAgree(10);
ida.setPercentAgreement(1.0f);
ida.setHighestPercentAgreement(1.0f);
expected.add(ida);
assertContains(hRep.getStoredIdentityAgreement(), ida);
ida = new IdentityManager.IdentityAgreement(peer3);
ida.setLastDisagree(10);
ida.setPercentAgreement(0.0f);
ida.setHighestPercentAgreement(0.0f);
expected.add(ida);
assertContains(hRep.getStoredIdentityAgreement(), ida);
assertSameElements(expected, hRep.getStoredIdentityAgreement());
assertEquals(3, hRep.getStoredIdentityAgreement().size());
}
public void testLoadIdentityAgreement() throws Exception {
MockHistoryRepository hRep = new MockHistoryRepository();
theDaemon.setHistoryRepository(hRep, mau);
setupPeer123();
List loadList = new ArrayList(3);
IdentityManager.IdentityAgreement ida =
new IdentityManager.IdentityAgreement(peer1);
ida.setLastAgree(10);
ida.setLastDisagree(10);
loadList.add(ida);
ida = new IdentityManager.IdentityAgreement(peer2);
ida.setLastAgree(10);
loadList.add(ida);
ida = new IdentityManager.IdentityAgreement(peer3);
ida.setLastDisagree(10);
loadList.add(ida);
hRep.setLoadedIdentityAgreement(loadList);
idmgr.forceReloadMap(mau);
Map agree = new HashMap();
agree.put(peer1, new Long(10));
agree.put(peer2, new Long(10));
assertEquals(agree, idmgr.getAgreed(mau));
Map disagree = new HashMap();
disagree.put(peer1, new Long(10));
disagree.put(peer3, new Long(10));
assertEquals(disagree, idmgr.getDisagreed(mau));
}
public void testLoadIdentityAgreementMerge() throws Exception {
// ConfigurationUtil.setFromArgs(IdentityManager.PARAM_MERGE_RESTORED_AGREE_MAP, "true");
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_MERGE_RESTORED_AGREE_MAP,
"true");
MockHistoryRepository hRep = new MockHistoryRepository();
theDaemon.setHistoryRepository(hRep, mau);
setupPeer123();
List loadList = new ArrayList(3);
IdentityManager.IdentityAgreement ida =
new IdentityManager.IdentityAgreement(peer1);
ida.setLastAgree(10);
ida.setLastDisagree(10);
loadList.add(ida);
ida = new IdentityManager.IdentityAgreement(peer2);
ida.setLastAgree(10);
loadList.add(ida);
ida = new IdentityManager.IdentityAgreement(peer3);
ida.setLastDisagree(10);
loadList.add(ida);
TimeBase.setSimulated(9);
idmgr.signalAgreed(peer1, mau);
idmgr.signalDisagreed(peer2, mau);
TimeBase.step(2);
idmgr.signalAgreed(peer2, mau);
idmgr.signalDisagreed(peer2, mau);
idmgr.signalAgreed(peer3, mau);
hRep.setLoadedIdentityAgreement(loadList);
idmgr.forceReloadMap(mau);
Map agree = new HashMap();
agree.put(peer1, new Long(10));
agree.put(peer2, new Long(11));
agree.put(peer3, new Long(11));
assertEquals(agree, idmgr.getAgreed(mau));
Map disagree = new HashMap();
disagree.put(peer1, new Long(10));
disagree.put(peer2, new Long(11));
disagree.put(peer3, new Long(10));
assertEquals(disagree, idmgr.getDisagreed(mau));
}
public void testLoadIdentityAgreementNoMerge() throws Exception {
ConfigurationUtil.addFromArgs(IdentityManager.PARAM_MERGE_RESTORED_AGREE_MAP,
"false");
MockHistoryRepository hRep = new MockHistoryRepository();
theDaemon.setHistoryRepository(hRep, mau);
setupPeer123();
List loadList = new ArrayList(3);
IdentityManager.IdentityAgreement ida =
new IdentityManager.IdentityAgreement(peer1);
ida.setLastAgree(10);
ida.setLastDisagree(10);
loadList.add(ida);
ida = new IdentityManager.IdentityAgreement(peer2);
ida.setLastAgree(10);
loadList.add(ida);
ida = new IdentityManager.IdentityAgreement(peer3);
ida.setLastDisagree(10);
loadList.add(ida);
TimeBase.setSimulated(9);
idmgr.signalAgreed(peer1, mau);
idmgr.signalDisagreed(peer2, mau);
TimeBase.step(2);
idmgr.signalAgreed(peer2, mau);
idmgr.signalDisagreed(peer2, mau);
idmgr.signalAgreed(peer3, mau);
hRep.setLoadedIdentityAgreement(loadList);
idmgr.forceReloadMap(mau);
Map agree = new HashMap();
agree.put(peer1, new Long(10));
agree.put(peer2, new Long(10));
assertEquals(agree, idmgr.getAgreed(mau));
Map disagree = new HashMap();
disagree.put(peer1, new Long(10));
disagree.put(peer3, new Long(10));
assertEquals(disagree, idmgr.getDisagreed(mau));
}
public void testLoadIdentityAgreementCompat() throws Exception {
XStreamSerializer deserializer;
IdentityManager.IdentityAgreement identityAgreement;
String noHintsSerialized =
" <org.lockss.protocol.IdentityManager-IdentityAgreement>\n" +
" <lastAgree>12345</lastAgree>\n" +
" <lastDisagree>67890</lastDisagree>\n" +
" <percentAgreement>0.7</percentAgreement>\n" +
" <highestPercentAgreement>0.8</highestPercentAgreement>\n" +
" <id>TCP:[127.0.0.1]:8805</id>\n" +
" </org.lockss.protocol.IdentityManager-IdentityAgreement>\n";
deserializer = new XStreamSerializer();
identityAgreement = (IdentityManager.IdentityAgreement)
deserializer.deserialize(new StringReader(noHintsSerialized));
assertEquals(12345, identityAgreement.getLastAgree());
assertEquals(67890, identityAgreement.getLastDisagree());
assertEquals(0.7f, identityAgreement.getPercentAgreement());
assertEquals(0.8f, identityAgreement.getHighestPercentAgreement());
assertEquals("TCP:[127.0.0.1]:8805", identityAgreement.getId());
// No hints in the serialized structure, so -1.0 provided.
assertEquals(-1.0f, identityAgreement.getPercentAgreementHint());
assertEquals(-1.0f, identityAgreement.getHighestPercentAgreementHint());
String haveHintsSerialized =
" <org.lockss.protocol.IdentityManager-IdentityAgreement>\n" +
" <lastAgree>12345</lastAgree>\n" +
" <lastDisagree>67890</lastDisagree>\n" +
" <percentAgreement>0.7</percentAgreement>\n" +
" <highestPercentAgreement>0.8</highestPercentAgreement>\n" +
" <percentAgreementHint>0.4</percentAgreementHint>\n" +
" <highestPercentAgreementHint>0.5</highestPercentAgreementHint>\n" +
" <haveHints>true</haveHints>\n" +
" <id>TCP:[127.0.0.1]:8805</id>\n" +
" </org.lockss.protocol.IdentityManager-IdentityAgreement>\n";
deserializer = new XStreamSerializer();
identityAgreement = (IdentityManager.IdentityAgreement)
deserializer.deserialize(new StringReader(haveHintsSerialized));
assertEquals(12345, identityAgreement.getLastAgree());
assertEquals(67890, identityAgreement.getLastDisagree());
assertEquals(0.7f, identityAgreement.getPercentAgreement());
assertEquals(0.8f, identityAgreement.getHighestPercentAgreement());
assertEquals(0.4f, identityAgreement.getPercentAgreementHint());
assertEquals(0.5f, identityAgreement.getHighestPercentAgreementHint());
assertEquals("TCP:[127.0.0.1]:8805", identityAgreement.getId());
}
/**
* Tests that the IP address info fed to the IdentityManagerStatus object
* looks like an IP address (x.x.x.x)
*/
public void testStatusInterface() throws Exception {
peer1 = idmgr.stringToPeerIdentity("127.0.0.1");
peer2 = idmgr.stringToPeerIdentity("127.0.0.2");
idmgr.signalAgreed(peer1, mau);
idmgr.signalAgreed(peer2, mau);
Map idMap = idmgr.getIdentityMap();
Set expectedAddresses = new HashSet();
expectedAddresses.add("127.0.0.1");
expectedAddresses.add("127.0.0.2");
expectedAddresses.add(LOCAL_IP);
for (Iterator iter = idMap.values().iterator();
iter.hasNext();) {
LcapIdentity id = ((PeerIdentityStatus)iter.next()).getLcapIdentity();
assertTrue(id.getPeerIdentity() + " not found in " + expectedAddresses,
expectedAddresses.contains(id.getPeerIdentity().getIdString()));
}
assertEquals(expectedAddresses.size(), idMap.size()); //2 above,plus me
assertEquals(SetUtil.theSet(idMap.values()),
SetUtil.theSet(idmgr.getPeerIdentityStatusList()));
}
public void testGetUdpPeerIdentities() throws Exception {
Collection udpPeers = idmgr.getUdpPeerIdentities();
assertNotNull(udpPeers);
idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001");
idmgr.findPeerIdentity("tcp:[127.0.0.1]:8002");
idmgr.findPeerIdentity("tcp:[127.0.0.1]:8003");
idmgr.findPeerIdentity("tcp:[127.0.0.1]:8004");
PeerIdentity id1 = idmgr.findPeerIdentity("127.0.0.2");
PeerIdentity id2 = idmgr.findPeerIdentity("127.0.0.3");
PeerIdentity id3 = idmgr.findPeerIdentity("127.0.0.4");
udpPeers = idmgr.getUdpPeerIdentities();
log.info("udp peers: " + udpPeers);
assertEquals(3, udpPeers.size());
Collection expectedPeers =
ListUtil.list(id1, id2, id3);
assertTrue(udpPeers.containsAll(expectedPeers));
assertTrue(expectedPeers.containsAll(udpPeers));
}
public void testGetTcpPeerIdentities() throws Exception {
Collection tcpPeers = idmgr.getTcpPeerIdentities();
assertNotNull(tcpPeers);
assertEquals(0, tcpPeers.size());
PeerIdentity id1 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001");
PeerIdentity id2 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8002");
PeerIdentity id3 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8003");
PeerIdentity id4 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8004");
idmgr.findPeerIdentity("127.0.0.2");
idmgr.findPeerIdentity("127.0.0.3");
idmgr.findPeerIdentity("127.0.0.4");
tcpPeers = idmgr.getTcpPeerIdentities();
log.info("tcp peers: " + tcpPeers);
assertEquals(4, tcpPeers.size());
Collection expectedPeers =
ListUtil.list(id1, id2, id3, id4);
assertTrue(tcpPeers.containsAll(expectedPeers));
assertTrue(expectedPeers.containsAll(tcpPeers));
}
public void testNormalizePeerIdentities() throws Exception {
PeerIdentity id1 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001");
assertSame(id1, idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001"));
assertSame(id1, idmgr.findPeerIdentity("TCP:[127.0.0.1]:8001"));
assertSame(id1, idmgr.findPeerIdentity("tcp:[127.00.0.1]:8001"));
assertSame(id1, idmgr.findPeerIdentity("tcp:[127.0.0.1]:08001"));
assertSame(id1, idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001"));
assertNotEquals(id1, idmgr.findPeerIdentity("tcp:[127.0.0.2]:8001"));
assertNotEquals(id1, idmgr.findPeerIdentity("tcp:[127.0.0.1]:8002"));
PeerIdentity id2 = idmgr.findPeerIdentity("tcp:[::1]:9729");
assertSame(id2, idmgr.findPeerIdentity("tcp:[::1]:9729"));
assertSame(id2, idmgr.findPeerIdentity("TCP:[::1]:9729"));
assertSame(id2, idmgr.findPeerIdentity("tcp:[0:0:0:0:0:0:0:1]:9729"));
assertSame(id2, idmgr.findPeerIdentity("tcp:[0:0:00:0000:0:0:0:1]:9729"));
assertSame(id2, idmgr.findPeerIdentity("TCP:[::1]:09729"));
assertNotEquals(id2, idmgr.findPeerIdentity("tcp:[::2]:9729"));
assertNotEquals(id2, idmgr.findPeerIdentity("tcp:[::1]:9720"));
}
void assertIsTcpAddr(String expIp, int expPort, PeerAddress pad) {
PeerAddress.Tcp tpad = (PeerAddress.Tcp)pad;
assertEquals(expIp, tpad.getIPAddr().toString());
assertEquals(expPort, tpad.getPort());
}
public void testPeerAddressMap() throws Exception {
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_PEER_ADDRESS_MAP,
"tcp:[127.0.0.1]:8001,tcp:[127.0.3.4]:6602;"+
"tcp:[127.0.0.2]:8003,tcp:[127.0.5.4]:7702;");
PeerIdentity id1 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001");
PeerIdentity id2 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8002");
PeerIdentity id3 = idmgr.findPeerIdentity("tcp:[127.0.0.2]:8003");
assertIsTcpAddr("127.0.3.4", 6602, id1.getPeerAddress());
assertIsTcpAddr("127.0.0.1", 8002, id2.getPeerAddress());
assertIsTcpAddr("127.0.5.4", 7702, id3.getPeerAddress());
}
public void testGetUiUrlStem() throws Exception {
PeerIdentity id1 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8001");
PeerIdentity id2 = idmgr.findPeerIdentity("tcp:[127.0.0.1]:8002");
PeerIdentity id3 = idmgr.findPeerIdentity("tcp:[127.0.0.2]:8003");
assertNull(idmgr.getUiUrlStem(id1));
assertNull(idmgr.getUiUrlStem(id2));
assertNull(idmgr.getUiUrlStem(id3));
assertEquals("http://127.0.0.1:1234", id1.getUiUrlStem(1234));
assertEquals("http://127.0.0.1:1234", id2.getUiUrlStem(1234));
assertEquals("http://127.0.0.2:1234", id3.getUiUrlStem(1234));
String map = "tcp:[127.0.0.1]:8001,http://127.0.0.1:3333;" +
"tcp:[127.0.0.2]:8003,http://127.0.0.22:4444";
ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_UI_STEM_MAP, map);
assertEquals("http://127.0.0.1:3333", id1.getUiUrlStem(1234));
assertEquals("http://127.0.0.1:1234", id2.getUiUrlStem(1234));
assertEquals("http://127.0.0.22:4444", id3.getUiUrlStem(1234));
}
private class TestableIdentityManager extends IdentityManagerImpl {
Map identities = null;
public Map getIdentityMap() {
return identities;
}
protected IdentityManagerStatus makeStatusAccessor() {
this.identities = theLcapIdentities;
return new MockIdentityManagerStatus();
}
void forceReloadMap(ArchivalUnit au) {
Map map = findAuAgreeMap(au);
synchronized (map) {
map.put(AGREE_MAP_INIT_KEY, "true"); // ensure map is reread
}
}
void setIdentity(int proto, PeerIdentity pid) {
localPeerIdentities[proto] = pid;
}
}
private class MockIdentityManagerStatus
extends IdentityManagerStatus {
public MockIdentityManagerStatus() {
super(idmgr);
}
public String getDisplayName() {
throw new UnsupportedOperationException();
}
public void populateTable(StatusTable table) {
throw new UnsupportedOperationException();
}
public boolean requiresKey() {
throw new UnsupportedOperationException();
}
}
public static void main(String[] argv) {
String[] testCaseList = {TestIdentityManagerImpl.class.getName()};
junit.swingui.TestRunner.main(testCaseList);
}
}
|
package org.robolectric.shadows;
import android.app.Activity;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.R;
import org.robolectric.Robolectric;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;
import org.robolectric.util.TestUtil;
import org.xmlpull.v1.XmlPullParser;
import java.io.InputStream;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.robolectric.Robolectric.shadowOf;
@RunWith(TestRunners.WithDefaults.class)
public class ResourcesTest {
private Resources resources;
@Before
public void setup() throws Exception {
resources = new Activity().getResources();
}
@Test
public void getString() throws Exception {
assertThat(resources.getString(R.string.hello)).isEqualTo("Hello");
}
@Test
public void getString_withReference() throws Exception {
assertThat(resources.getString(R.string.greeting)).isEqualTo("Howdy");
}
@Test
public void getString_withInterpolation() throws Exception {
assertThat(resources.getString(R.string.interpolate, "value")).isEqualTo("Here's a value!");
}
@Test
public void getString_withHtml() throws Exception {
assertThat(resources.getString(R.string.some_html, "value")).isEqualTo("Hello, world");
}
@Test
public void getText_withHtml() throws Exception {
// todo: this needs to change...
assertThat(resources.getText(R.string.some_html, "value")).isEqualTo("Hello, world");
}
@Test
public void getText_withLayoutId() throws Exception {
// todo: this needs to change...
assertThat(resources.getText(R.layout.different_screen_sizes, "value")).isEqualTo("./src/test/resources/res/layout/different_screen_sizes.xml");
}
@Test
public void getStringArray() throws Exception {
assertThat(resources.getStringArray(R.array.items)).isEqualTo(new String[] {"foo", "bar"});
assertThat(resources.getStringArray(R.array.greetings)).isEqualTo(new String[] {"hola", "Hello"});
}
@Test
public void getInt() throws Exception {
assertThat(resources.getInteger(R.integer.meaning_of_life)).isEqualTo(42);
assertThat(resources.getInteger(R.integer.test_integer1)).isEqualTo(2000);
assertThat(resources.getInteger(R.integer.test_integer2)).isEqualTo(9);
assertThat(resources.getInteger(R.integer.test_large_hex)).isEqualTo(-65536);
assertThat(resources.getInteger(R.integer.test_value_with_zero)).isEqualTo(7210);
}
@Test
public void getInt_withReference() throws Exception {
assertThat(resources.getInteger(R.integer.reference_to_meaning_of_life)).isEqualTo(42);
}
@Test
public void getIntArray() throws Exception {
assertThat(resources.getIntArray(R.array.empty_int_array)).isEqualTo(new int[] {});
assertThat(resources.getIntArray(R.array.zero_to_four_int_array)).isEqualTo(new int[] {0, 1, 2, 3, 4});
assertThat(resources.getIntArray(R.array.with_references_int_array)).isEqualTo(new int[] {0, 2000, 1});
}
@Test
public void getBoolean() throws Exception {
assertThat(resources.getBoolean(R.bool.false_bool_value)).isEqualTo(false);
assertThat(resources.getBoolean(R.bool.integers_are_true)).isEqualTo(true);
}
@Test
public void getBoolean_withReference() throws Exception {
assertThat(resources.getBoolean(R.bool.reference_to_true)).isEqualTo(true);
}
@Test
public void getDimension() throws Exception {
assertThat(resources.getDimension(R.dimen.test_dip_dimen)).isEqualTo(20f);
assertThat(resources.getDimension(R.dimen.test_dp_dimen)).isEqualTo(8f);
assertThat(resources.getDimension(R.dimen.test_in_dimen)).isEqualTo(99f * 240);
assertThat(resources.getDimension(R.dimen.test_mm_dimen)).isEqualTo(((float) (42f / 25.4 * 240)));
assertThat(resources.getDimension(R.dimen.test_px_dimen)).isEqualTo(15f);
assertThat(resources.getDimension(R.dimen.test_pt_dimen)).isEqualTo(12 / 0.3f);
assertThat(resources.getDimension(R.dimen.test_sp_dimen)).isEqualTo(0); // huh?
}
@Test
public void getDimensionPixelSize() throws Exception {
assertThat(resources.getDimensionPixelSize(R.dimen.test_dip_dimen)).isEqualTo(20);
assertThat(resources.getDimensionPixelSize(R.dimen.test_dp_dimen)).isEqualTo(8);
assertThat(resources.getDimensionPixelSize(R.dimen.test_in_dimen)).isEqualTo(99 * 240);
assertThat(resources.getDimensionPixelSize(R.dimen.test_mm_dimen)).isEqualTo(397);
assertThat(resources.getDimensionPixelSize(R.dimen.test_px_dimen)).isEqualTo(15);
assertThat(resources.getDimensionPixelSize(R.dimen.test_pt_dimen)).isEqualTo(40);
assertThat(resources.getDimensionPixelSize(R.dimen.test_sp_dimen)).isEqualTo(1);
}
@Test
public void getDimensionPixelOffset() throws Exception {
assertThat(resources.getDimensionPixelOffset(R.dimen.test_dip_dimen)).isEqualTo(20);
assertThat(resources.getDimensionPixelOffset(R.dimen.test_dp_dimen)).isEqualTo(8);
assertThat(resources.getDimensionPixelOffset(R.dimen.test_in_dimen)).isEqualTo(99 * 240);
assertThat(resources.getDimensionPixelOffset(R.dimen.test_mm_dimen)).isEqualTo(396);
assertThat(resources.getDimensionPixelOffset(R.dimen.test_px_dimen)).isEqualTo(15);
assertThat(resources.getDimensionPixelOffset(R.dimen.test_pt_dimen)).isEqualTo(40);
assertThat(resources.getDimensionPixelOffset(R.dimen.test_sp_dimen)).isEqualTo(0);
}
@Test
public void getDimension_withReference() throws Exception {
assertThat(resources.getBoolean(R.bool.reference_to_true)).isEqualTo(true);
}
@Test(expected = Resources.NotFoundException.class)
public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
resources.getStringArray(-1);
}
@Test(expected = Resources.NotFoundException.class)
public void getIntegerArray_shouldThrowExceptionIfNotFound() throws Exception {
resources.getIntArray(-1);
}
@Test public void getQuantityString() throws Exception {
assertThat(resources.getQuantityString(R.plurals.beer, 0)).isEqualTo("Howdy");
assertThat(resources.getQuantityString(R.plurals.beer, 1)).isEqualTo("One beer");
assertThat(resources.getQuantityString(R.plurals.beer, 2)).isEqualTo("Two beers");
assertThat(resources.getQuantityString(R.plurals.beer, 3)).isEqualTo("%d beers, yay!");
}
@Test
public void testConfiguration() {
Configuration configuration = resources.getConfiguration();
assertThat(configuration).isNotNull();
assertThat(configuration.locale).isNotNull();
}
@Test
public void testConfigurationReturnsTheSameInstance() {
assertThat(resources.getConfiguration()).isSameAs(resources.getConfiguration());
}
@Test
public void testNewTheme() {
assertThat(resources.newTheme()).isNotNull();
}
@Test(expected = Resources.NotFoundException.class)
public void testGetDrawableNullRClass() throws Exception {
assertThat(resources.getDrawable(-12345)).isInstanceOf(BitmapDrawable.class);
}
/**
* given an R.anim.id value, will return an AnimationDrawable
*/
@Test
public void testGetAnimationDrawable() {
assertThat(resources.getDrawable(R.anim.animation_list)).isInstanceOf(AnimationDrawable.class);
}
@Test @Config(qualifiers = "fr")
public void testGetValuesResFromSpecificQualifiers() {
assertThat(resources.getString(R.string.hello)).isEqualTo("Bonjour");
}
/**
* given an R.color.id value, will return a ColorDrawable
*/
@Test
public void testGetColorDrawable() {
Drawable drawable = resources.getDrawable(R.color.color_with_alpha);
assertThat(drawable).isInstanceOf(ColorDrawable.class);
assertThat(((ColorDrawable) drawable).getColor()).isEqualTo(0x802C76AD);
}
@Test
public void getColor() {
assertThat(resources.getColor(R.color.color_with_alpha)).isEqualTo(0x802C76AD);
}
@Test
public void getColor_withReference() {
assertThat(resources.getColor(R.color.background)).isEqualTo(0xfff5f5f5);
}
@Test(expected = Resources.NotFoundException.class)
public void testGetColor_Missing() {
resources.getColor(R.color.test_color_1);
}
/**
* given an R.color.id value, will return a ColorStateList
*/
@Test
public void testGetColorStateList() {
assertThat(resources.getColorStateList(R.color.color_state_list)).isInstanceOf(ColorStateList.class);
}
/**
* given an R.drawable.id value, will return a BitmapDrawable
*/
@Test
public void testGetBitmapDrawable() {
assertThat(resources.getDrawable(R.drawable.an_image)).isInstanceOf(BitmapDrawable.class);
}
/**
* given an R.drawable.id value, will return a NinePatchDrawable for .9.png file
*/
@Test
public void testGetNinePatchDrawable() {
assertThat(Robolectric.getShadowApplication().getResources().getDrawable(R.drawable.nine_patch_drawable)).isInstanceOf(NinePatchDrawable.class);
}
@Test(expected = Resources.NotFoundException.class)
public void testGetBitmapDrawableForUnknownId() {
assertThat(resources.getDrawable(Integer.MAX_VALUE)).isInstanceOf(BitmapDrawable.class);
}
@Test
public void testGetIdentifier() throws Exception {
final String resourceType = "string";
final String packageName = Robolectric.application.getPackageName();
final String resourceName = "hello";
final int resId1 = resources.getIdentifier(resourceName, resourceType, packageName);
assertThat(resId1).isEqualTo(R.string.hello);
final String typedResourceName = resourceType + "/" + resourceName;
final int resId2 = resources.getIdentifier(typedResourceName, resourceType, packageName);
assertThat(resId2).isEqualTo(R.string.hello);
final String fqn = packageName + ":" + typedResourceName;
final int resId3 = resources.getIdentifier(fqn, resourceType, packageName);
assertThat(resId3).isEqualTo(R.string.hello);
}
@Test
public void testDensity() {
Activity activity = new Activity();
assertThat(activity.getResources().getDisplayMetrics().density).isEqualTo(1f);
shadowOf(activity.getResources()).setDensity(1.5f);
assertThat(activity.getResources().getDisplayMetrics().density).isEqualTo(1.5f);
Activity anotherActivity = new Activity();
assertThat(anotherActivity.getResources().getDisplayMetrics().density).isEqualTo(1.5f);
}
@Test
public void displayMetricsShouldNotHaveLotsOfZeros() throws Exception {
Activity activity = new Activity();
assertThat(activity.getResources().getDisplayMetrics().heightPixels).isEqualTo(800);
assertThat(activity.getResources().getDisplayMetrics().widthPixels).isEqualTo(480);
}
@Test
public void getSystemShouldReturnSystemResources() throws Exception {
assertThat(Resources.getSystem()).isInstanceOf(Resources.class);
}
@Test
public void multipleCallsToGetSystemShouldReturnSameInstance() throws Exception {
assertThat(Resources.getSystem()).isEqualTo(Resources.getSystem());
}
@Test
public void applicationResourcesShouldHaveBothSystemAndLocalValues() throws Exception {
Activity activity = new Activity();
assertThat(activity.getResources().getString(android.R.string.copy)).isEqualTo("Copy");
assertThat(activity.getResources().getString(R.string.copy)).isEqualTo("Local Copy");
}
@Test
public void systemResourcesShouldReturnCorrectSystemId() throws Exception {
assertThat(Resources.getSystem().getIdentifier("copy", "string", "android")).isEqualTo(android.R.string.copy);
}
@Test
public void systemResourcesShouldReturnZeroForLocalId() throws Exception {
assertThat(Resources.getSystem().getIdentifier("copy", "string", TestUtil.TEST_PACKAGE)).isEqualTo(0);
}
@Test
public void testGetXml() throws Exception {
XmlResourceParser parser = resources.getXml(R.xml.preferences);
assertThat(parser).isNotNull();
assertThat(findRootTag(parser)).isEqualTo("PreferenceScreen");
parser = resources.getXml(R.layout.custom_layout);
assertThat(parser).isNotNull();
assertThat(findRootTag(parser)).isEqualTo("org.robolectric.util.CustomView");
parser = resources.getXml(R.menu.test);
assertThat(parser).isNotNull();
assertThat(findRootTag(parser)).isEqualTo("menu");
parser = resources.getXml(R.drawable.rainbow);
assertThat(parser).isNotNull();
assertThat(findRootTag(parser)).isEqualTo("layer-list");
parser = resources.getXml(R.anim.test_anim_1);
assertThat(parser).isNotNull();
assertThat(findRootTag(parser)).isEqualTo("set");
parser = resources.getXml(R.color.color_state_list);
assertThat(parser).isNotNull();
assertThat(findRootTag(parser)).isEqualTo("selector");
}
@Test(expected = Resources.NotFoundException.class)
public void testGetXml_nonexistentResource() {
resources.getXml(0);
}
@Test(expected = Resources.NotFoundException.class)
public void testGetXml_nonxmlfile() {
resources.getXml(R.drawable.an_image);
}
@Test
public void shouldLoadRawResources() throws Exception {
InputStream resourceStream = resources.openRawResource(R.raw.raw_resource);
assertThat(resourceStream).isNotNull();
assertThat(TestUtil.readString(resourceStream)).isEqualTo("raw txt file contents");
}
@Test
public void shouldLoadRawResourcesFromLibraries() throws Exception {
InputStream resourceStream = resources.openRawResource(R.raw.lib_raw_resource);
assertThat(resourceStream).isNotNull();
assertThat(TestUtil.readString(resourceStream)).isEqualTo("from lib3");
}
private static String findRootTag(XmlResourceParser parser) throws Exception {
int event;
do {
event = parser.next();
} while (event != XmlPullParser.START_TAG);
return parser.getName();
}
}
|
package org.zstack.compute.host;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.asyncbatch.While;
import org.zstack.core.cascade.CascadeConstant;
import org.zstack.core.cascade.CascadeFacade;
import org.zstack.core.cloudbus.*;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.config.GlobalConfigFacade;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.allocator.HostAllocatorConstant;
import org.zstack.header.core.Completion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.NopeCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.HostCanonicalEvents.HostDeletedData;
import org.zstack.header.host.HostCanonicalEvents.HostStatusChangedData;
import org.zstack.header.host.HostErrors.Opaque;
import org.zstack.header.host.HostMaintenancePolicyExtensionPoint.HostMaintenancePolicy;
import org.zstack.header.message.APIDeleteMessage;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.vm.*;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.function.ForEachFunction;
import org.zstack.utils.logging.CLogger;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.zstack.core.Platform.err;
import static org.zstack.core.Platform.operr;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public abstract class HostBase extends AbstractHost {
protected static final CLogger logger = Utils.getLogger(HostBase.class);
protected HostVO self;
@Autowired
protected CloudBus bus;
@Autowired
protected DatabaseFacade dbf;
@Autowired
protected ThreadFacade thdf;
@Autowired
protected HostExtensionPointEmitter extpEmitter;
@Autowired
protected GlobalConfigFacade gcf;
@Autowired
protected HostManager hostMgr;
@Autowired
protected CascadeFacade casf;
@Autowired
protected ErrorFacade errf;
@Autowired
protected HostTracker tracker;
@Autowired
protected PluginRegistry pluginRgty;
@Autowired
protected EventFacade evtf;
@Autowired
protected HostMaintenancePolicyManager hostMaintenancePolicyMgr;
public static class HostDisconnectedCanonicalEvent extends CanonicalEventEmitter {
HostCanonicalEvents.HostDisconnectedData data;
public HostDisconnectedCanonicalEvent(String hostUuid, ErrorCode reason) {
data = new HostCanonicalEvents.HostDisconnectedData();
data.hostUuid = hostUuid;
data.reason = reason;
}
public void fire() {
fire(HostCanonicalEvents.HOST_DISCONNECTED_PATH, data);
}
}
protected final String id;
protected abstract void pingHook(Completion completion);
protected abstract int getVmMigrateQuantity();
protected abstract void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next);
protected abstract void connectHook(ConnectHostInfo info, Completion complete);
protected abstract void updateOsHook(String exclude, Completion completion);
protected HostBase(HostVO self) {
this.self = self;
id = "Host-" + self.getUuid();
}
protected void checkStatus() {
if (HostStatus.Connected != self.getStatus()) {
ErrorCode cause = err(HostErrors.HOST_IS_DISCONNECTED, "host[uuid:%s, name:%s] is in status[%s], cannot perform required operation", self.getUuid(), self.getName(), self.getStatus());
throw new OperationFailureException(err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, cause, "unable to do the operation because the host is in status of Disconnected"));
}
}
protected void checkState() {
if (HostState.PreMaintenance == self.getState() || HostState.Maintenance == self.getState()) {
throw new OperationFailureException(operr("host[uuid:%s, name:%s] is in state[%s], cannot perform required operation", self.getUuid(), self.getName(), self.getState()));
}
}
protected void checkStateAndStatus() {
checkState();
checkStatus();
}
protected abstract int getHostSyncLevel();
protected void handleApiMessage(APIMessage msg) {
if (msg instanceof APIChangeHostStateMsg) {
handle((APIChangeHostStateMsg) msg);
} else if (msg instanceof APIDeleteHostMsg) {
handle((APIDeleteHostMsg) msg);
} else if (msg instanceof APIReconnectHostMsg) {
handle((APIReconnectHostMsg) msg);
} else if (msg instanceof APIUpdateHostMsg) {
handle((APIUpdateHostMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
protected HostVO updateHost(APIUpdateHostMsg msg) {
boolean update = false;
if (msg.getName() != null) {
self.setName(msg.getName());
update = true;
}
if (msg.getDescription() != null) {
self.setDescription(msg.getDescription());
update = true;
}
if (msg.getManagementIp() != null) {
self.setManagementIp(msg.getManagementIp());
update = true;
}
return update ? self : null;
}
private void handle(APIUpdateHostMsg msg) {
HostVO vo = updateHost(msg);
if (vo != null) {
self = dbf.updateAndRefresh(vo);
}
APIUpdateHostEvent evt = new APIUpdateHostEvent(msg.getId());
evt.setInventory(getSelfInventory());
bus.publish(evt);
}
protected void maintenanceHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("maintenance-mode-host-%s-ip-%s", self.getUuid(), self.getManagementIp()));
List<String> operateVmUuids = Q.New(VmInstanceVO.class)
.select(VmInstanceVO_.uuid)
.eq(VmInstanceVO_.hostUuid, self.getUuid())
.notEq(VmInstanceVO_.state, VmInstanceState.Unknown)
.listValues();
Map<HostMaintenancePolicy, Set<String>> policyVmMap = map(
e(HostMaintenancePolicy.MigrateVm, new HashSet<>(operateVmUuids)),
e(HostMaintenancePolicy.StopVm, new HashSet<>()));
for (HostMaintenancePolicyExtensionPoint ext : pluginRgty.getExtensionList(HostMaintenancePolicyExtensionPoint.class)) {
Map<String, HostMaintenancePolicy> vmUuidPolicyMap = ext.getHostMaintenanceVmOperationPolicy(getSelfInventory());
logger.debug(String.format("HostMaintenancePolicyExtensionPoint[%s] preset maintenance policy for host[uuid:%s] to %s",
ext.getClass(), self.getUuid(), vmUuidPolicyMap));
vmUuidPolicyMap.forEach((vmUuid, policy) -> policyVmMap.get(policy).add(vmUuid));
}
// default policy is migrate, but stop policy setting is high priority
policyVmMap.values().forEach(vmUuids -> vmUuids.retainAll(operateVmUuids));
policyVmMap.get(HostMaintenancePolicy.MigrateVm).removeAll(policyVmMap.get(HostMaintenancePolicy.StopVm));
final int quantity = getVmMigrateQuantity();
DebugUtils.Assert(quantity != 0, "getVmMigrateQuantity() cannot return 0");
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "try-migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<String> vmUuids = new ArrayList<>(policyVmMap.get(HostMaintenancePolicy.MigrateVm));
if (vmUuids.isEmpty()) {
trigger.next();
return;
}
int migrateQuantity = quantity;
HostInventory host = getSelfInventory();
List<String> vmFailedToMigrate = Collections.synchronizedList(new ArrayList<String>());
for (OrderVmBeforeMigrationDuringHostMaintenanceExtensionPoint ext : pluginRgty.getExtensionList(OrderVmBeforeMigrationDuringHostMaintenanceExtensionPoint.class)) {
List<String> ordered = ext.orderVmBeforeMigrationDuringHostMaintenance(host, vmUuids);
if (ordered != null) {
vmUuids = ordered;
logger.debug(String.format("%s ordered VMs for host maintenance, to keep the order, we will migrate VMs one by one",
ext.getClass()));
migrateQuantity = 1;
}
}
new While<>(vmUuids).step((vmUuid, compl) -> {
MigrateVmMsg msg = new MigrateVmMsg();
msg.setVmInstanceUuid(vmUuid);
bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, vmUuid);
bus.send(msg, new CloudBusCallBack(compl) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
vmFailedToMigrate.add(msg.getVmInstanceUuid());
}
compl.done();
}
});
}, migrateQuantity).run(new NoErrorCompletion() {
@Override
public void done() {
if (!vmFailedToMigrate.isEmpty()) {
if (HostMaintenancePolicyManager.HostMaintenancePolicy.JustMigrate.equals(hostMaintenancePolicyMgr.getHostMaintenancePolicy(self.getUuid()))) {
trigger.fail(operr("failed to migrate vm[uuids:%s] on host[uuid:%s, name:%s, ip:%s], will try stopping it.",
vmFailedToMigrate, self.getUuid(), self.getName(), self.getManagementIp()));
return;
}
logger.warn(String.format("failed to migrate vm[uuids:%s] on host[uuid:%s, name:%s, ip:%s], will try stopping it.",
vmFailedToMigrate, self.getUuid(), self.getName(), self.getManagementIp()));
policyVmMap.get(HostMaintenancePolicy.StopVm).addAll(vmFailedToMigrate);
policyVmMap.get(HostMaintenancePolicy.MigrateVm).removeAll(vmFailedToMigrate);
}
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "stop-vm-not-migrated";
@Override
public void run(FlowTrigger trigger, Map data) {
if (policyVmMap.get(HostMaintenancePolicy.StopVm).isEmpty()) {
trigger.next();
return;
}
List<String> vmUuids = Q.New(VmInstanceVO.class).select(VmInstanceVO_.uuid)
.in(VmInstanceVO_.uuid, policyVmMap.get(HostMaintenancePolicy.StopVm)).listValues();
stopFailedToMigrateVms(vmUuids, trigger);
}
private void stopFailedToMigrateVms(List<String> vmUuids, final FlowTrigger trigger) {
List<ErrorCode> errors = Collections.synchronizedList(new ArrayList<>());
List<String> vmFailedToStop = Collections.synchronizedList(new ArrayList<>());
new While<>(vmUuids).step((vmUuid, coml) -> {
StopVmInstanceMsg msg = new StopVmInstanceMsg();
msg.setVmInstanceUuid(vmUuid);
bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, vmUuid);
bus.send(msg, new CloudBusCallBack(coml) {
@Override
public void run(MessageReply reply) {
logger.debug(String.format("stop vm[uuid:%s] after migration failure", vmUuid));
if (!reply.isSuccess() && dbf.isExist(vmUuid, VmInstanceVO.class)) {
errors.add(reply.getError());
vmFailedToStop.add(vmUuid);
}
coml.done();
}
});
}, quantity).run(new NoErrorCompletion() {
@Override
public void done() {
if (errors.isEmpty() || HostGlobalConfig.IGNORE_ERROR_ON_MAINTENANCE_MODE.value(Boolean.class)) {
trigger.next();
} else {
trigger.fail(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
String.format("failed to stop vm[uuids:%s] on host[uuid:%s, name:%s, ip:%s]",
vmFailedToStop, self.getUuid(), self.getName(), self.getManagementIp()),
errors));
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "run-extension-point-after-maintenance";
@Override
public void run(FlowTrigger trigger, Map data) {
runExtensionPoints(pluginRgty.getExtensionList(HostAfterMaintenanceExtensionPoint.class).iterator(), new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
private void runExtensionPoints(Iterator<HostAfterMaintenanceExtensionPoint> it, Completion completion1) {
if (!it.hasNext()) {
completion1.success();
return;
}
HostAfterMaintenanceExtensionPoint ext = it.next();
ext.afterMaintenanceExtensionPoint(getSelfInventory(), new Completion(completion1) {
@Override
public void success() {
runExtensionPoints(it, completion1);
}
@Override
public void fail(ErrorCode errorCode) {
completion1.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final APIReconnectHostMsg msg) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
APIReconnectHostEvent evt = new APIReconnectHostEvent(msg.getId());
if (!reply.isSuccess()) {
evt.setError(err(HostErrors.UNABLE_TO_RECONNECT_HOST, reply.getError(), reply.getError().getDetails()));
logger.debug(String.format("failed to reconnect host[uuid:%s] because %s", self.getUuid(), reply.getError()));
}else{
self = dbf.reload(self);
evt.setInventory((getSelfInventory()));
}
bus.publish(evt);
}
});
}
private void deleteHostByApiMessage(APIDeleteHostMsg msg) {
final APIDeleteHostEvent evt = new APIDeleteHostEvent(msg.getId());
final String issuer = HostVO.class.getSimpleName();
final List<HostInventory> ctx = Arrays.asList(HostInventory.valueOf(self));
if (self.getState() == HostState.Enabled) {
changeState(HostStateEvent.disable);
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("delete-host-%s", msg.getUuid()));
if (msg.getDeletionMode() == APIDeleteMessage.DeletionMode.Permissive) {
chain.then(new NoRollbackFlow() {
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
} else {
chain.then(new NoRollbackFlow() {
@Override
public void run(final FlowTrigger trigger, Map data) {
casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
}
chain.done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion());
bus.publish(evt);
HostDeletedData d = new HostDeletedData();
d.setInventory(HostInventory.valueOf(self));
d.setHostUuid(self.getUuid());
evtf.fire(HostCanonicalEvents.HOST_DELETED_PATH, d);
}
}).error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
evt.setError(err(SysErrors.DELETE_RESOURCE_ERROR, errCode, errCode.getDetails()));
bus.publish(evt);
}
}).start();
}
private void handle(final APIDeleteHostMsg msg) {
deleteHostByApiMessage(msg);
}
protected HostState changeState(HostStateEvent event) {
HostState currentState = self.getState();
HostState next = currentState.nextState(event);
changeStateHook(currentState, event, next);
extpEmitter.beforeChange(self, event);
self.setState(next);
self = dbf.updateAndRefresh(self);
extpEmitter.afterChange(self, event, currentState);
logger.debug(String.format("Host[%s]'s state changed from %s to %s", self.getUuid(), currentState, self.getState()));
return self.getState();
}
protected void changeStateByApiMessage(final APIChangeHostStateMsg msg, final NoErrorCompletion completion) {
thdf.chainSubmit(new ChainTask(msg, completion) {
@Override
public String getSyncSignature() {
return String.format("change-host-state-%s", self.getUuid());
}
private void done(SyncTaskChain chain) {
completion.done();
chain.next();
}
@Override
public void run(final SyncTaskChain chain) {
final APIChangeHostStateEvent evt = new APIChangeHostStateEvent(msg.getId());
HostStateEvent stateEvent = HostStateEvent.valueOf(msg.getStateEvent());
stateEvent = stateEvent == HostStateEvent.maintain ? HostStateEvent.preMaintain : stateEvent;
try {
extpEmitter.preChange(self, stateEvent);
} catch (HostException he) {
evt.setError(err(SysErrors.CHANGE_RESOURCE_STATE_ERROR, he.getMessage()));
bus.publish(evt);
done(chain);
return;
}
if (HostStateEvent.preMaintain == stateEvent) {
HostState originState = self.getState();
changeState(HostStateEvent.preMaintain);
maintenanceHook(new Completion(msg, chain) {
@Override
public void success() {
changeState(HostStateEvent.maintain);
evt.setInventory(HostInventory.valueOf(self));
bus.publish(evt);
done(chain);
}
@Override
public void fail(ErrorCode errorCode) {
evt.setError(err(HostErrors.UNABLE_TO_ENTER_MAINTENANCE_MODE, errorCode, errorCode.getDetails()));
HostStateEvent rollbackEvent = dbf.reload(self).getState().getTargetStateDrivenEvent(originState);
DebugUtils.Assert(rollbackEvent != null, "rollbackEvent not found!");
changeState(rollbackEvent);
bus.publish(evt);
done(chain);
}
});
} else {
if (hostOutOfMaintenance(stateEvent)) {
// host is out of maintenance mode, track and reconnect it.
tracker.trackHost(self.getUuid());
// change host status to connecting
// jira: ZSTAC-15944
changeConnectionState(HostStatusEvent.connecting);
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
}
HostInventory inv = HostInventory.valueOf(self);
evt.setInventory(inv);
bus.publish(evt);
done(chain);
}
}
private boolean hostOutOfMaintenance(HostStateEvent stateEvent) {
HostState origState = self.getState();
HostState state = changeState(stateEvent);
return origState == HostState.Maintenance && state != HostState.Maintenance;
}
@Override
public String getName() {
return String.format("change-host-state-%s", self.getUuid());
}
});
}
protected void handle(final APIChangeHostStateMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "change-host-state-" + self.getUuid();
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
changeStateByApiMessage(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
protected void handleLocalMessage(Message msg) {
if (msg instanceof ChangeHostStateMsg) {
handle((ChangeHostStateMsg) msg);
} else if (msg instanceof HostDeletionMsg) {
handle((HostDeletionMsg) msg);
} else if (msg instanceof ConnectHostMsg) {
handle((ConnectHostMsg) msg);
} else if (msg instanceof ReconnectHostMsg) {
handle((ReconnectHostMsg) msg);
} else if (msg instanceof ChangeHostConnectionStateMsg) {
handle((ChangeHostConnectionStateMsg) msg);
} else if (msg instanceof PingHostMsg) {
handle((PingHostMsg) msg);
} else if (msg instanceof UpdateHostOSMsg) {
handle((UpdateHostOSMsg) msg);
} else {
HostBaseExtensionFactory ext = hostMgr.getHostBaseExtensionFactory(msg);
if (ext != null) {
Host h = ext.getHost(self);
if (h != null) {
h.handleMessage(msg);
return;
}
}
bus.dealWithUnknownMessage(msg);
}
}
private void handle(UpdateHostOSMsg msg) {
UpdateHostOSReply reply = new UpdateHostOSReply();
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "update-host-os-of-cluster-" + msg.getClusterUuid();
}
@Override
public int getSyncLevel() {
return HostGlobalConfig.HOST_UPDATE_OS_PARALLELISM_DEGREE.value(Integer.class);
}
@Override
public void run(SyncTaskChain chain) {
updateOsHook(msg.getExcludePackages(), new Completion(msg, chain) {
@Override
public void success() {
bus.reply(msg, reply);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
chain.next();
}
});
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
private void handle(final PingHostMsg msg) {
final PingHostReply reply = new PingHostReply();
if (self.getStatus() == HostStatus.Connecting) {
reply.setError(operr("host is connecting, ping failed"));
bus.reply(msg, reply);
return;
}
final Integer MAX_PING_CNT = HostGlobalConfig.MAXIMUM_PING_FAILURE.value(Integer.class);
final List<Integer> stepCount = new ArrayList<>();
for(int i = 1; i <= MAX_PING_CNT; i ++){
stepCount.add(i);
}
final List<ErrorCode> errs = new ArrayList<>();
new While<>(stepCount).each((currentStep, compl) -> pingHook(new Completion(compl) {
@Override
public void success() {
compl.allDone();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("ping host failed (%d/%d): %s", currentStep, MAX_PING_CNT, errorCode.toString()));
errs.add(errorCode);
if (errs.size() != stepCount.size()) {
int sleep = HostGlobalConfig.SLEEP_TIME_AFTER_PING_FAILURE.value(Integer.class);
if (sleep > 0) {
try {
TimeUnit.SECONDS.sleep(sleep);
} catch (InterruptedException ignored) {
}
}
}
compl.done();
}
})).run(new NoErrorCompletion(msg) {
@Override
public void done() {
if (errs.size() == stepCount.size()){
final ErrorCode errorCode = errs.get(0);
reply.setConnected(false);
reply.setCurrentHostStatus(self.getStatus().toString());
reply.setError(errorCode);
reply.setSuccess(true);
Boolean noReconnect = (Boolean) errorCode.getFromOpaque(Opaque.NO_RECONNECT_AFTER_PING_FAILURE.toString());
reply.setNoReconnect(noReconnect != null && noReconnect);
if(!Q.New(HostVO.class).eq(HostVO_.uuid, msg.getHostUuid()).isExists()){
reply.setNoReconnect(true);
bus.reply(msg, reply);
return;
}
if (!self.getStatus().equals(HostStatus.Disconnected)) {
new HostDisconnectedCanonicalEvent(self.getUuid(), errorCode).fire();
}
changeConnectionState(HostStatusEvent.disconnected);
bus.reply(msg, reply);
} else {
reply.setConnected(true);
reply.setCurrentHostStatus(self.getStatus().toString());
bus.reply(msg, reply);
extpEmitter.hostPingTask(HypervisorType.valueOf(self.getHypervisorType()), getSelfInventory());
}
}
});
}
private void handle(final HostDeletionMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
HostInventory hinv = HostInventory.valueOf(self);
extpEmitter.beforeDelete(hinv);
deleteHook();
extpEmitter.afterDelete(hinv);
bus.reply(msg, new HostDeletionReply());
tracker.untrackHost(self.getUuid());
chain.next();
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
@Override
public String getName() {
return String.format("host-deletion-%s", self.getUuid());
}
});
}
private void reconnectHost(final ReconnectHostMsg msg, final NoErrorCompletion completion) {
thdf.chainSubmit(new ChainTask(msg, completion) {
@Override
public String getSyncSignature() {
return String.format("reconnect-host-%s", self.getUuid());
}
private void finish(SyncTaskChain chain) {
chain.next();
completion.done();
}
@Override
public void run(final SyncTaskChain chain) {
checkState();
if (msg.isSkipIfHostConnected() && HostStatus.Connected == self.getStatus()) {
finish(chain);
return;
}
ConnectHostMsg connectMsg = new ConnectHostMsg(self.getUuid());
connectMsg.setNewAdd(false);
bus.makeTargetServiceIdByResourceUuid(connectMsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(connectMsg, new CloudBusCallBack(msg, chain, completion) {
@Override
public void run(MessageReply reply) {
ReconnectHostReply r = new ReconnectHostReply();
if (reply.isSuccess()) {
logger.debug(String.format("Successfully reconnect host[uuid:%s]", self.getUuid()));
} else {
r.setError(err(HostErrors.UNABLE_TO_RECONNECT_HOST, reply.getError(), reply.getError().getDetails()));
logger.debug(String.format("Failed to reconnect host[uuid:%s] because %s",
self.getUuid(), reply.getError()));
}
bus.reply(msg, r);
}
});
// no need to block the queue, because the ConnectHostMsg will be queued as well
finish(chain);
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
private void handle(final ReconnectHostMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "reconnect-host-" + self.getUuid();
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
reconnectHost(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void handle(final ChangeHostConnectionStateMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "change-host-connection-state-" + self.getUuid();
}
private void reestablishConnection() {
try {
extpEmitter.connectionReestablished(HypervisorType.valueOf(self.getHypervisorType()), getSelfInventory());
} catch (HostException e) {
throw new OperationFailureException(operr(e.getMessage()));
}
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
HostStatusEvent cevt = HostStatusEvent.valueOf(msg.getConnectionStateEvent());
HostStatus next = self.getStatus().nextStatus(cevt);
if (self.getStatus() == HostStatus.Disconnected && next == HostStatus.Connected) {
try {
reestablishConnection();
} catch (OperationFailureException e) {
cevt = HostStatusEvent.disconnected;
new HostDisconnectedCanonicalEvent(self.getUuid(), e.getErrorCode()).fire();
}
}
changeConnectionState(cevt);
bus.reply(msg, new ChangeHostConnectionStateReply());
chain.next();
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
protected abstract HostInventory getSelfInventory();
protected boolean changeConnectionState(final HostStatusEvent event) {
return changeConnectionState(event, null);
}
protected boolean changeConnectionState(final HostStatusEvent event, Runnable runnable) {
String hostUuid = self.getUuid();
self = dbf.reload(self);
if(self == null){
throw new CloudRuntimeException(String.format("change host connection state fail, can not find the host[%s]", hostUuid));
}
HostStatus before = self.getStatus();
HostStatus next = before.nextStatus(event);
if (before == next) {
return false;
}
self.setStatus(next);
Optional.ofNullable(runnable).ifPresent(Runnable::run);
self = dbf.updateAndRefresh(self);
logger.debug(String.format("Host %s [uuid:%s] changed connection state from %s to %s",
self.getName(), self.getUuid(), before, next));
HostStatusChangedData data = new HostStatusChangedData();
data.setHostUuid(self.getUuid());
data.setNewStatus(next.toString());
data.setOldStatus(before.toString());
data.setInventory(HostInventory.valueOf(self));
evtf.fire(HostCanonicalEvents.HOST_STATUS_CHANGED_PATH, data);
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AfterChangeHostStatusExtensionPoint.class),
new ForEachFunction<AfterChangeHostStatusExtensionPoint>() {
@Override
public void run(AfterChangeHostStatusExtensionPoint arg) {
arg.afterChangeHostStatus(self.getUuid(), before, next);
}
});
return true;
}
private void handle(final ConnectHostMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return String.format("connect-host-%s", self.getUuid());
}
@Override
public void run(SyncTaskChain chain) {
checkState();
final ConnectHostReply reply = new ConnectHostReply();
final FlowChain flowChain = FlowChainBuilder.newShareFlowChain();
flowChain.setName(String.format("connect-host-%s", self.getUuid()));
flowChain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "connect-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
changeConnectionState(HostStatusEvent.connecting);
connectHook(ConnectHostInfo.fromConnectHostMsg(msg), new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-post-connect-extensions";
@Override
public void run(FlowTrigger trigger, Map data) {
FlowChain postConnectChain = FlowChainBuilder.newSimpleFlowChain();
postConnectChain.allowEmptyFlow();
self = dbf.reload(self);
HostInventory inv = getSelfInventory();
for (PostHostConnectExtensionPoint p : pluginRgty.getExtensionList(PostHostConnectExtensionPoint.class)) {
Flow flow = p.createPostHostConnectFlow(inv);
if (flow != null) {
postConnectChain.then(flow);
}
}
postConnectChain.done(new FlowDoneHandler(trigger) {
@Override
public void handle(Map data) {
trigger.next();
}
}).error(new FlowErrorHandler(trigger) {
@Override
public void handle(ErrorCode errCode, Map data) {
trigger.fail(errCode);
}
}).start();
}
});
flow(new NoRollbackFlow() {
String __name__ = "recalculate-host-capacity";
@Override
public void run(FlowTrigger trigger, Map data) {
RecalculateHostCapacityMsg msg = new RecalculateHostCapacityMsg();
msg.setHostUuid(self.getUuid());
bus.makeLocalServiceId(msg, HostAllocatorConstant.SERVICE_ID);
bus.send(msg);
trigger.next();
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
changeConnectionState(HostStatusEvent.connected);
tracker.trackHost(self.getUuid());
CollectionUtils.safeForEach(pluginRgty.getExtensionList(HostAfterConnectedExtensionPoint.class),
ext -> ext.afterHostConnected(getSelfInventory()));
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
changeConnectionState(HostStatusEvent.disconnected);
if (!msg.isNewAdd()) {
tracker.trackHost(self.getUuid());
}
new HostDisconnectedCanonicalEvent(self.getUuid(), errCode).fire();
reply.setError(errCode);
bus.reply(msg, reply);
}
});
Finally(new FlowFinallyHandler(msg) {
@Override
public void Finally() {
chain.next();
}
});
}
}).start();
}
@Override
public String getName() {
return "connect-host";
}
});
}
private void changeStateByLocalMessage(final ChangeHostStateMsg msg, final NoErrorCompletion completion) {
thdf.chainSubmit(new ChainTask(msg, completion) {
@Override
public String getSyncSignature() {
return String.format("change-host-state-%s", self.getUuid());
}
private void done(SyncTaskChain chain) {
completion.done();
chain.next();
}
@Override
public void run(SyncTaskChain chain) {
ChangeHostStateReply reply = new ChangeHostStateReply();
if (self.getState() != HostState.Enabled && self.getState() != HostState.Disabled) {
done(chain);
return;
}
HostStateEvent stateEvent = HostStateEvent.valueOf(msg.getStateEvent());
changeState(stateEvent);
HostInventory inv = HostInventory.valueOf(self);
reply.setInventory(inv);
bus.reply(msg, reply);
done(chain);
}
@Override
public String getName() {
return String.format("change-host-state-%s", self.getUuid());
}
});
}
private void handle(final ChangeHostStateMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getName() {
return "change-host-state-" + self.getUuid();
}
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
changeStateByLocalMessage(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public int getSyncLevel() {
return getHostSyncLevel();
}
});
}
}
|
package com.bugsnag;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import com.bugsnag.android.BreadcrumbType;
import com.bugsnag.android.Bugsnag;
import com.bugsnag.android.Callback;
import com.bugsnag.android.Client;
import com.bugsnag.android.Configuration;
import com.bugsnag.android.JsonStream;
import com.bugsnag.android.MetaData;
import com.bugsnag.android.Report;
import com.bugsnag.android.Severity;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.uimanager.ViewManager;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class BugsnagReactNative extends ReactContextBaseJavaModule {
private ReactContext reactContext;
private String libraryVersion;
private String bugsnagAndroidVersion;
final static Logger logger = Logger.getLogger("bugsnag-react-native");
public static ReactPackage getPackage() {
return new BugsnagPackage();
}
public static Client start(Context context) {
Client client = Bugsnag.init(context);
// The first session starts during JS initialization
// Applications which have specific components in RN instead of the primary
// way to interact with the application should instead leverage startSession
// manually.
client.setAutoCaptureSessions(false);
return client;
}
public static Client startWithApiKey(Context context, String APIKey) {
Client client = Bugsnag.init(context, APIKey);
client.setAutoCaptureSessions(false);
return client;
}
public static Client startWithConfiguration(Context context, Configuration config) {
config.setAutoCaptureSessions(false);
return Bugsnag.init(context, config);
}
public BugsnagReactNative(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
libraryVersion = null;
bugsnagAndroidVersion = null;
}
@Override
public String getName() {
return "BugsnagReactNative";
}
@ReactMethod
public void startSession() {
Bugsnag.startSession();
}
@ReactMethod
public void startWithOptions(ReadableMap options) {
String apiKey = null;
if (options.hasKey("apiKey")) {
apiKey = options.getString("apiKey");
}
Client client = getClient(apiKey);
libraryVersion = options.getString("version");
bugsnagAndroidVersion = client.getClass().getPackage().getSpecificationVersion();
configureRuntimeOptions(client, options);
logger.info(String.format("Initialized Bugsnag React Native %s/Android %s",
libraryVersion,
bugsnagAndroidVersion));
}
@ReactMethod
public void leaveBreadcrumb(ReadableMap options) {
String name = options.getString("name");
Bugsnag.leaveBreadcrumb(name,
parseBreadcrumbType(options.getString("type")),
readStringMap(options.getMap("metadata")));
}
@ReactMethod
public void notify(ReadableMap payload) {
notifyBlocking(payload, false, null);
}
@ReactMethod
public void notifyBlocking(ReadableMap payload, boolean blocking, com.facebook.react.bridge.Callback callback) {
if (!payload.hasKey("errorClass")) {
logger.warning("Bugsnag could not notify: No error class");
return;
}
if (!payload.hasKey("stacktrace")) {
logger.warning("Bugsnag could not notify: No stacktrace");
return;
}
final String errorClass = payload.getString("errorClass");
final String errorMessage = payload.getString("errorMessage");
final String rawStacktrace = payload.getString("stacktrace");
logger.info(String.format("Sending exception: %s - %s %s\n",
errorClass, errorMessage, rawStacktrace));
JavaScriptException exc = new JavaScriptException(errorClass,
errorMessage,
rawStacktrace);
DiagnosticsCallback handler = new DiagnosticsCallback(libraryVersion,
bugsnagAndroidVersion,
payload);
Map<String, Object> map = new HashMap<>();
String severity = payload.getString("severity");
String severityReason = payload.getString("severityReason");
map.put("severity", severity);
map.put("severityReason", severityReason);
Bugsnag.internalClientNotify(exc, map, blocking, handler);
if (callback != null)
callback.invoke();
}
@ReactMethod
public void setUser(ReadableMap userInfo) {
String userId = userInfo.hasKey("id") ? userInfo.getString("id") : null;
String email = userInfo.hasKey("email") ? userInfo.getString("email") : null;
String name = userInfo.hasKey("name") ? userInfo.getString("name") : null;
Bugsnag.setUser(userId, email, name);
}
@ReactMethod
public void clearUser() {
Bugsnag.clearUser();
}
/**
* Convert a typed map into a string Map
*/
private Map<String, String> readStringMap(ReadableMap map) {
Map<String,String> output = new HashMap<>();
ReadableMapKeySetIterator iterator = map.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableMap pair = map.getMap(key);
switch (pair.getString("type")) {
case "boolean":
output.put(key, String.valueOf(pair.getBoolean("value")));
break;
case "number":
output.put(key, String.valueOf(pair.getDouble("value")));
break;
case "string":
output.put(key, pair.getString("value"));
break;
case "map":
output.put(key, String.valueOf(readStringMap(pair.getMap("value"))));
break;
}
}
return output;
}
private Client getClient(String apiKey) {
Client client;
try {
client = Bugsnag.getClient();
} catch (IllegalStateException exception) {
if (apiKey != null) {
client = Bugsnag.init(this.reactContext, apiKey);
} else {
client = Bugsnag.init(this.reactContext);
}
}
return client;
}
private BreadcrumbType parseBreadcrumbType(String value) {
for (BreadcrumbType type : BreadcrumbType.values()) {
if (type.toString().equals(value)) {
return type;
}
}
return BreadcrumbType.MANUAL;
}
private void configureRuntimeOptions(Client client, ReadableMap options) {
client.setIgnoreClasses("com.facebook.react.common.JavascriptException");
Configuration config = client.getConfig();
if (options.hasKey("appVersion")) {
String version = options.getString("appVersion");
if (version != null && version.length() > 0)
client.setAppVersion(version);
}
String notify = null;
String sessions = null;
if (options.hasKey("endpoint")) {
notify = options.getString("endpoint");
}
if (options.hasKey("sessionsEndpoint")) {
sessions = options.getString("sessionsEndpoint");
}
if (notify != null && notify.length() > 0) {
config.setEndpoints(notify, sessions);
} else if (sessions != null && sessions.length() > 0) {
logger.warning("The session tracking endpoint should not be set without the error reporting endpoint.");
}
if (options.hasKey("releaseStage")) {
String releaseStage = options.getString("releaseStage");
if (releaseStage != null && releaseStage.length() > 0)
client.setReleaseStage(releaseStage);
}
if (options.hasKey("autoNotify")) {
if (options.getBoolean("autoNotify")) {
client.enableExceptionHandler();
} else {
client.disableExceptionHandler();
}
}
if (options.hasKey("codeBundleId")) {
String codeBundleId = options.getString("codeBundleId");
if (codeBundleId != null && codeBundleId.length() > 0)
client.addToTab("app", "codeBundleId", codeBundleId);
}
if (options.hasKey("notifyReleaseStages")) {
ReadableArray stages = options.getArray("notifyReleaseStages");
if (stages != null && stages.size() > 0) {
String releaseStages[] = new String[stages.size()];
for (int i = 0; i < stages.size(); i++) {
releaseStages[i] = stages.getString(i);
}
client.setNotifyReleaseStages(releaseStages);
}
}
if (options.hasKey("automaticallyCollectBreadcrumbs")) {
boolean autoCapture = options.getBoolean("automaticallyCollectBreadcrumbs");
config.setAutomaticallyCollectBreadcrumbs(autoCapture);
}
// Process session tracking last in case the effects of other options
// should be captured as a part of the session
if (options.hasKey("autoCaptureSessions")) {
boolean autoCapture = options.getBoolean("autoCaptureSessions");
config.setAutoCaptureSessions(autoCapture);
if (autoCapture) {
// The launch event session is skipped because autoCaptureSessions
// was not set when Bugsnag was first initialized. Manually sending a
// session to compensate.
client.startSession();
}
}
}
}
class BugsnagPackage implements ReactPackage {
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@SuppressWarnings("rawtypes") // the ReactPackage interface uses a raw type, ignore it
@Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new BugsnagReactNative(reactContext));
}
}
/**
* Attaches report diagnostics before delivery
*/
class DiagnosticsCallback implements Callback {
static final String NOTIFIER_NAME = "Bugsnag for React Native";
static final String NOTIFIER_URL = "https://github.com/bugsnag/bugsnag-react-native";
final private Severity severity;
final private String context;
final private String groupingHash;
final private Map<String, Object> metadata;
final private String libraryVersion;
final private String bugsnagAndroidVersion;
DiagnosticsCallback(String libraryVersion,
String bugsnagAndroidVersion,
ReadableMap payload) {
this.libraryVersion = libraryVersion;
this.bugsnagAndroidVersion = bugsnagAndroidVersion;
severity = parseSeverity(payload.getString("severity"));
metadata = readObjectMap(payload.getMap("metadata"));
if (payload.hasKey("context"))
context = payload.getString("context");
else
context = null;
if (payload.hasKey("groupingHash"))
groupingHash = payload.getString("groupingHash");
else
groupingHash = null;
}
Severity parseSeverity(String value) {
switch (value) {
case "error": return Severity.ERROR;
case "info": return Severity.INFO;
case "warning":
default:
return Severity.WARNING;
}
}
/**
* Convert a typed map from JS into a Map
*/
Map<String, Object> readObjectMap(ReadableMap map) {
Map<String, Object> output = new HashMap<>();
ReadableMapKeySetIterator iterator = map.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableMap pair = map.getMap(key);
switch (pair.getString("type")) {
case "boolean":
output.put(key, pair.getBoolean("value"));
break;
case "number":
output.put(key, pair.getDouble("value"));
break;
case "string":
output.put(key, pair.getString("value"));
break;
case "map":
output.put(key, readObjectMap(pair.getMap("value")));
break;
}
}
return output;
}
@Override
public void beforeNotify(Report report) {
report.getNotifier().setName(NOTIFIER_NAME);
report.getNotifier().setURL(NOTIFIER_URL);
report.getNotifier().setVersion(String.format("%s (Android %s)",
libraryVersion,
bugsnagAndroidVersion));
if (groupingHash != null && groupingHash.length() > 0)
report.getError().setGroupingHash(groupingHash);
if (context != null && context.length() > 0)
report.getError().setContext(context);
if (metadata != null) {
MetaData reportMetadata = report.getError().getMetaData();
for (String tab : metadata.keySet()) {
Object value = metadata.get(tab);
if (value instanceof Map) {
@SuppressWarnings("unchecked") // ignore type erasure when casting Map
Map<String, Object> values = (Map<String, Object>) value;
for (String key : values.keySet()) {
reportMetadata.addToTab(tab, key, values.get(key));
}
}
}
}
}
}
/**
* Creates a streamable exception with a JavaScript stacktrace
*/
class JavaScriptException extends Exception implements JsonStream.Streamable {
private static final String EXCEPTION_TYPE = "browserjs";
private static final long serialVersionUID = 1175784680140218622L;
private final String name;
private final String rawStacktrace;
JavaScriptException(String name, String message, String rawStacktrace) {
super(message);
this.name = name;
this.rawStacktrace = rawStacktrace;
}
public void toStream(@NonNull JsonStream writer) throws IOException {
writer.beginObject();
writer.name("errorClass").value(name);
writer.name("message").value(getLocalizedMessage());
writer.name("type").value(EXCEPTION_TYPE);
writer.name("stacktrace");
writer.beginArray();
for (String rawFrame : rawStacktrace.split("\\n")) {
writer.beginObject();
String methodComponents[] = rawFrame.split("@", 2);
String fragment = methodComponents[0];
if (methodComponents.length == 2) {
writer.name("method").value(methodComponents[0]);
fragment = methodComponents[1];
}
int columnIndex = fragment.lastIndexOf(":");
if (columnIndex != -1) {
String columnString = fragment.substring(columnIndex + 1, fragment.length());
try {
int columnNumber = Integer.parseInt(columnString);
writer.name("columnNumber").value(columnNumber);
} catch (NumberFormatException e) {
BugsnagReactNative.logger.info(String.format(
"Failed to parse column: '%s'",
columnString));
}
fragment = fragment.substring(0, columnIndex);
}
int lineNumberIndex = fragment.lastIndexOf(":");
if (lineNumberIndex != -1) {
String lineNumberString = fragment.substring(lineNumberIndex + 1, fragment.length());
try {
int lineNumber = Integer.parseInt(lineNumberString);
writer.name("lineNumber").value(lineNumber);
} catch (NumberFormatException e) {
BugsnagReactNative.logger.info(String.format(
"Failed to parse lineNumber: '%s'",
lineNumberString));
}
fragment = fragment.substring(0, lineNumberIndex);
}
writer.name("file").value(fragment);
writer.endObject();
}
writer.endArray();
writer.endObject();
}
}
|
//package edu.hypower.gatech.phidget;
import com.phidgets.*;
import com.phidgets.event.*;
import java.util.concurrent.*;
public class EventDrivenInterfaceKit implements RawDataListener
//public class EventDrivenInterfaceKit
{
@Override
public void rawData(RawDataEvent arg0)
{
// TODO Auto-generated method stub
}
public static void main(String args[]) throws Exception
{
final InterfaceKitPhidget ikit;
ikit = new InterfaceKitPhidget();
ikit.addAttachListener(new AttachListener() {
public void attached(AttachEvent event) {
int serialNumber = 0;
String name = new String();
try {
serialNumber = ((Phidget)event.getSource()).getSerialNumber();
name = ((Phidget)event.getSource()).getDeviceName();
}
catch(PhidgetException exception) {
System.out.println(exception.getDescription());
}
System.out.println("Device" + name + " serial: " + Integer.toString(serialNumber));
}
});
ikit.addSensorChangeListener(new SensorChangeListener() {
public void sensorChanged(SensorChangeEvent sensorEvent) {
if(sensorEvent.getIndex() == 0) {
float currMotion = sensorEvent.getValue();
System.out.println("Motion changed to " + Float.toString(currMotion));
//could just do this to get raw value
//System.out.println(sensorEvent);
}
}
});
ikit.openAny();
ikit.waitForAttachment();
Thread.sleep(500);
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// ikit.close();
// ikit = null;
//TODO: remove listener
//example on using manager, not so sure
// Manager manager;
// manager = new Manager();
// manager.addAttachListener(attach);
// manager.open();
// System.in.read();
// manager.close();
// manager = null;
}
}
|
package hudson.slaves;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assume.assumeFalse;
import hudson.BulkChange;
import hudson.Functions;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.queue.QueueTaskFuture;
import hudson.tasks.Builder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.RealJenkinsRule;
import org.jvnet.hudson.test.SleepBuilder;
/**
* @author Kohsuke Kawaguchi
*/
public class NodeProvisionerTest {
@Rule public RealJenkinsRule rr = new RealJenkinsRule();
@Before
public void setUp() {
// run 10x the regular speed to speed up the test
rr.javaOptions(
"-Dhudson.model.LoadStatistics.clock=" + TimeUnit.SECONDS.toMillis(1),
"-Dhudson.slaves.NodeProvisioner.initialDelay=" + TimeUnit.SECONDS.toMillis(10),
"-Dhudson.slaves.NodeProvisioner.recurrencePeriod=" + TimeUnit.SECONDS.toMillis(1));
}
/**
* Latch synchronization primitive that waits for N thread to pass the checkpoint.
* <p>
* This is used to make sure we get a set of builds that run long enough.
*/
static class Latch {
/** Initial value */
public final transient CountDownLatch counter;
private final int init;
Latch(int n) {
this.init = n;
this.counter = new CountDownLatch(n);
}
void block() throws InterruptedException {
this.counter.countDown();
this.counter.await(60, TimeUnit.SECONDS);
}
/**
* Creates a builder that blocks until the latch opens.
*/
public Builder createBuilder() {
return new Builder() {
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException {
block();
return true;
}
};
}
}
/**
* Scenario: schedule a build and see if one agent is provisioned.
*/
// TODO fragile
@Test public void autoProvision() throws Throwable {
assumeFalse("TODO: Windows container agents do not have enough resources to run this test", Functions.isWindows() && System.getenv("CI") != null);
rr.then(NodeProvisionerTest::_autoProvision);
}
private static void _autoProvision(JenkinsRule r) throws Exception {
try (BulkChange bc = new BulkChange(r.jenkins)) {
DummyCloudImpl cloud = initHudson(10, r);
FreeStyleProject p = createJob(new SleepBuilder(10), r);
Future<FreeStyleBuild> f = p.scheduleBuild2(0);
f.get(30, TimeUnit.SECONDS); // if it's taking too long, abort.
// since there's only one job, we expect there to be just one slave
assertEquals(1, cloud.numProvisioned);
}
}
/**
* Scenario: we got a lot of jobs all of the sudden, and we need to fire up a few nodes.
*/
// TODO fragile
@Test public void loadSpike() throws Throwable {
assumeFalse("TODO: Windows container agents do not have enough resources to run this test", Functions.isWindows() && System.getenv("CI") != null);
rr.then(NodeProvisionerTest::_loadSpike);
}
private static void _loadSpike(JenkinsRule r) throws Exception {
try (BulkChange bc = new BulkChange(r.jenkins)) {
DummyCloudImpl cloud = initHudson(0, r);
verifySuccessfulCompletion(buildAll(create5SlowJobs(new Latch(5), r)), r);
// the time it takes to complete a job is eternally long compared to the time it takes to launch
// a new slave, so in this scenario we end up allocating 5 slaves for 5 jobs.
assertEquals(5, cloud.numProvisioned);
}
}
/**
* Scenario: make sure we take advantage of statically configured agents.
*/
// TODO fragile
@Test public void baselineSlaveUsage() throws Throwable {
assumeFalse("TODO: Windows container agents do not have enough resources to run this test", Functions.isWindows() && System.getenv("CI") != null);
rr.then(NodeProvisionerTest::_baselineSlaveUsage);
}
private static void _baselineSlaveUsage(JenkinsRule r) throws Exception {
try (BulkChange bc = new BulkChange(r.jenkins)) {
DummyCloudImpl cloud = initHudson(0, r);
// add agents statically upfront
r.createSlave().toComputer().connect(false).get();
r.createSlave().toComputer().connect(false).get();
verifySuccessfulCompletion(buildAll(create5SlowJobs(new Latch(5), r)), r);
// we should have used two static slaves, thus only 3 slaves should have been provisioned
assertEquals(3, cloud.numProvisioned);
}
}
/**
* Scenario: loads on one label shouldn't translate to load on another label.
*/
// TODO fragile
@Test public void labels() throws Throwable {
assumeFalse("TODO: Windows container agents do not have enough resources to run this test", Functions.isWindows() && System.getenv("CI") != null);
rr.then(NodeProvisionerTest::_labels);
}
private static void _labels(JenkinsRule r) throws Exception {
try (BulkChange bc = new BulkChange(r.jenkins)) {
DummyCloudImpl cloud = initHudson(0, r);
Label blue = r.jenkins.getLabel("blue");
Label red = r.jenkins.getLabel("red");
cloud.label = red;
// red jobs
List<FreeStyleProject> redJobs = create5SlowJobs(new Latch(5), r);
for (FreeStyleProject p : redJobs)
p.setAssignedLabel(red);
// blue jobs
List<FreeStyleProject> blueJobs = create5SlowJobs(new Latch(5), r);
for (FreeStyleProject p : blueJobs)
p.setAssignedLabel(blue);
// build all
List<Future<FreeStyleBuild>> blueBuilds = buildAll(blueJobs);
verifySuccessfulCompletion(buildAll(redJobs), r);
// cloud should only give us 5 nodes for 5 red jobs
assertEquals(5, cloud.numProvisioned);
// and all blue jobs should be still stuck in the queue
for (Future<FreeStyleBuild> bb : blueBuilds)
assertFalse(bb.isDone());
}
}
@Issue("JENKINS-67635")
@Test
public void testJobWithCloudLabelExpressionProvisionsOnlyOneAgent() throws Throwable {
assumeFalse("TODO: Windows container agents do not have enough resources to run this test", Functions.isWindows() && System.getenv("CI") != null);
rr.then(NodeProvisionerTest::_testJobWithCloudLabelExpressionProvisionsOnlyOneAgent);
}
private static void _testJobWithCloudLabelExpressionProvisionsOnlyOneAgent(JenkinsRule r) throws Exception {
DummyCloudImpl3 cloud1 = new DummyCloudImpl3(r);
DummyCloudImpl3 cloud2 = new DummyCloudImpl3(r);
cloud1.label = Label.get("cloud-1-label");
cloud2.label = Label.get("cloud-2-label");
r.jenkins.clouds.add(cloud1);
r.jenkins.clouds.add(cloud2);
FreeStyleProject p = r.createFreeStyleProject();
p.setAssignedLabel(Label.parseExpression("cloud-1-label || cloud-2-label"));
QueueTaskFuture<FreeStyleBuild> futureBuild = p.scheduleBuild2(0);
FreeStyleBuild build = futureBuild.waitForStart();
r.assertBuildStatusSuccess(r.waitForCompletion(build));
assertEquals(1, cloud1.numProvisioned);
assertEquals(0, cloud2.numProvisioned);
}
private static class DummyCloudImpl3 extends Cloud {
private final transient JenkinsRule caller;
public int numProvisioned;
private Label label;
DummyCloudImpl3() {
super("DummyCloudImpl3");
this.caller = null;
}
DummyCloudImpl3(JenkinsRule caller) {
super("DummyCloudImpl3");
this.caller = caller;
}
@Override
public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) {
List<NodeProvisioner.PlannedNode> r = new ArrayList<>();
if (! this.canProvision(label))
return r;
while (excessWorkload > 0) {
numProvisioned++;
Future<Node> f = Computer.threadPoolForRemoting.submit(new DummyCloudImpl3.Launcher());
r.add(new NodeProvisioner.PlannedNode(name + " #" + numProvisioned, f, 1));
excessWorkload -= 1;
}
return r;
}
@Override
public boolean canProvision(Label label) {
return label.matches(this.label.listAtoms());
}
private final class Launcher implements Callable<Node> {
private volatile Computer computer;
private Launcher() {}
@Override
public Node call() throws Exception {
DumbSlave slave = caller.createSlave(label);
computer = slave.toComputer();
computer.connect(false).get();
return slave;
}
}
@Override
public Descriptor<Cloud> getDescriptor() {
throw new UnsupportedOperationException();
}
}
private static FreeStyleProject createJob(Builder builder, JenkinsRule r) throws IOException {
FreeStyleProject p = r.createFreeStyleProject();
p.setAssignedLabel(null); // let it roam free, or else it ties itself to the built-in node since we have no agents
p.getBuildersList().add(builder);
return p;
}
private static DummyCloudImpl initHudson(int delay, JenkinsRule r) throws IOException {
// start a dummy service
DummyCloudImpl cloud = new DummyCloudImpl(r, delay);
r.jenkins.clouds.add(cloud);
// no build on the built-in node, to make sure we get everything from the cloud
r.jenkins.setNumExecutors(0);
r.jenkins.setNodes(Collections.emptyList());
return cloud;
}
private static List<FreeStyleProject> create5SlowJobs(Latch l, JenkinsRule r) throws IOException {
List<FreeStyleProject> jobs = new ArrayList<>();
for (int i = 0; i < l.init; i++)
//set a large delay, to simulate the situation where we need to provision more agents
// to keep up with the load
jobs.add(createJob(l.createBuilder(), r));
return jobs;
}
/**
* Builds all the given projects at once.
*/
private static List<Future<FreeStyleBuild>> buildAll(List<FreeStyleProject> jobs) {
System.out.println("Scheduling builds for " + jobs.size() + " jobs");
List<Future<FreeStyleBuild>> builds = new ArrayList<>();
for (FreeStyleProject job : jobs)
builds.add(job.scheduleBuild2(0));
return builds;
}
private static void verifySuccessfulCompletion(List<Future<FreeStyleBuild>> builds, JenkinsRule r) throws Exception {
System.out.println("Waiting for a completion");
for (Future<FreeStyleBuild> f : builds) {
r.assertBuildStatusSuccess(f.get());
}
}
}
|
package seedu.address.storage;
import java.io.File;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import guitests.AddressBookGuiTest;
public class SaveCommandTest extends AddressBookGuiTest {
private static final String TEST_SAVE_DIRECTORY = "src/test/data/testfile.xml";
@Test
public void save_withDefaultTestPath() {
saveFile(TEST_SAVE_DIRECTORY);
assertSaveFileExists(TEST_SAVE_DIRECTORY);
}
private void saveFile(String saveDirectory) {
String saveCommand = "save " + saveDirectory;
commandBox.runCommand(saveCommand);
}
private void assertSaveFileExists(String saveDirectory) {
File testSaveFile = new File(saveDirectory);
assertTrue(testSaveFile.exists());
testSaveFile.delete();
}
}
|
package com.bugsnag;
import com.bugsnag.android.BreadcrumbType;
import com.bugsnag.android.Bugsnag;
import com.bugsnag.android.Client;
import com.bugsnag.android.Configuration;
import android.content.Context;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
public class BugsnagReactNative extends ReactContextBaseJavaModule {
private ReactContext reactContext;
private String libraryVersion;
private String bugsnagAndroidVersion;
static final Logger logger = Logger.getLogger("bugsnag-react-native");
public static ReactPackage getPackage() {
return new BugsnagPackage();
}
/**
* Instantiates a bugsnag client using the API key in the AndroidManifest.xml
*
* @param context the application context
* @return the bugsnag client
*/
public static Client start(Context context) {
Client client = Bugsnag.init(context);
// The first session starts during JS initialization
// Applications which have specific components in RN instead of the primary
// way to interact with the application should instead leverage startSession
// manually.
client.setAutoCaptureSessions(false);
return client;
}
/**
* Instantiates a bugsnag client with a given API key.
*
* @param context the application context
* @param apiKey the api key for your project
* @return the bugsnag client
*/
public static Client startWithApiKey(Context context, String apiKey) {
Client client = Bugsnag.init(context, apiKey);
client.setAutoCaptureSessions(false);
return client;
}
/**
* Instantiates a bugsnag client with a given configuration object.
*
* @param context the application context
* @param config configuration for how bugsnag should behave
* @return the bugsnag client
*/
public static Client startWithConfiguration(Context context, Configuration config) {
config.setAutoCaptureSessions(false);
return Bugsnag.init(context, config);
}
/**
* Instantiates the bugsnag react native module
*/
public BugsnagReactNative(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
libraryVersion = null;
bugsnagAndroidVersion = null;
}
@Override
public String getName() {
return "BugsnagReactNative";
}
@ReactMethod
public void startSession() {
Bugsnag.startSession();
}
@ReactMethod
public void stopSession() {
Bugsnag.stopSession();
}
@ReactMethod
public void resumeSession() {
Bugsnag.resumeSession();
}
/**
* Configures the bugsnag client with configuration options from the JS layer, starting a new
* client if one has not already been created.
*
* @param options the JS configuration object
*/
@ReactMethod
public void startWithOptions(ReadableMap options) {
String apiKey = null;
if (options.hasKey("apiKey")) {
apiKey = options.getString("apiKey");
}
Client client = getClient(apiKey);
libraryVersion = options.getString("version");
bugsnagAndroidVersion = client.getClass().getPackage().getSpecificationVersion();
configureRuntimeOptions(client, options);
logger.info(String.format("Initialized Bugsnag React Native %s/Android %s",
libraryVersion,
bugsnagAndroidVersion));
}
/**
* Leaves a breadcrumb from the JS layer.
*
* @param options the JS breadcrumb
*/
@ReactMethod
public void leaveBreadcrumb(ReadableMap options) {
String name = options.getString("name");
Bugsnag.leaveBreadcrumb(name,
parseBreadcrumbType(options.getString("type")),
readStringMap(options.getMap("metadata")));
}
/**
* Notifies the native client that a JS error occurred. Upon invoking this method, an
* error report will be generated and delivered via the native client.
*
* @param payload information about the JS error
* @param promise a nullable JS promise that is resolved after a report is delivered
*/
@ReactMethod
public void notify(ReadableMap payload, Promise promise) {
if (!payload.hasKey("errorClass")) {
logger.warning("Bugsnag could not notify: No error class");
return;
}
if (!payload.hasKey("stacktrace")) {
logger.warning("Bugsnag could not notify: No stacktrace");
return;
}
final String errorClass = payload.getString("errorClass");
final String errorMessage = payload.getString("errorMessage");
final String rawStacktrace = payload.getString("stacktrace");
logger.info(String.format("Sending exception: %s - %s %s\n",
errorClass, errorMessage, rawStacktrace));
JavaScriptException exc = new JavaScriptException(errorClass,
errorMessage,
rawStacktrace);
DiagnosticsCallback handler = new DiagnosticsCallback(libraryVersion,
bugsnagAndroidVersion,
payload);
Map<String, Object> map = new HashMap<>();
String severity = payload.getString("severity");
String severityReason = payload.getString("severityReason");
map.put("severity", severity);
map.put("severityReason", severityReason);
boolean blocking = payload.hasKey("blocking") && payload.getBoolean("blocking");
Bugsnag.internalClientNotify(exc, map, blocking, handler);
if (promise != null) {
promise.resolve(null);
}
}
/**
* Sets a user from the JS layer.
*
* @param userInfo the JS user
*/
@ReactMethod
public void setUser(ReadableMap userInfo) {
String userId = userInfo.hasKey("id") ? userInfo.getString("id") : null;
String email = userInfo.hasKey("email") ? userInfo.getString("email") : null;
String name = userInfo.hasKey("name") ? userInfo.getString("name") : null;
Bugsnag.setUser(userId, email, name);
}
@ReactMethod
public void clearUser() {
Bugsnag.clearUser();
}
/**
* Convert a typed map into a string Map
*/
private Map<String, String> readStringMap(ReadableMap map) {
Map<String, String> output = new HashMap<>();
ReadableMapKeySetIterator iterator = map.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableMap pair = map.getMap(key);
switch (pair.getString("type")) {
case "boolean":
output.put(key, String.valueOf(pair.getBoolean("value")));
break;
case "number":
output.put(key, String.valueOf(pair.getDouble("value")));
break;
case "string":
output.put(key, pair.getString("value"));
break;
case "map":
output.put(key, String.valueOf(readStringMap(pair.getMap("value"))));
break;
default:
break;
}
}
return output;
}
private Client getClient(String apiKey) {
Client client;
try {
client = Bugsnag.getClient();
} catch (IllegalStateException exception) {
if (apiKey != null) {
client = Bugsnag.init(this.reactContext, apiKey);
} else {
client = Bugsnag.init(this.reactContext);
}
}
return client;
}
private BreadcrumbType parseBreadcrumbType(String value) {
for (BreadcrumbType type : BreadcrumbType.values()) {
if (type.toString().equals(value)) {
return type;
}
}
return BreadcrumbType.MANUAL;
}
private void configureRuntimeOptions(Client client, ReadableMap options) {
client.setIgnoreClasses("com.facebook.react.common.JavascriptException");
Configuration config = client.getConfig();
if (options.hasKey("appVersion")) {
String version = options.getString("appVersion");
if (version != null && version.length() > 0) {
client.setAppVersion(version);
}
}
String notify = null;
String sessions = null;
if (options.hasKey("endpoint")) {
notify = options.getString("endpoint");
}
if (options.hasKey("sessionsEndpoint")) {
sessions = options.getString("sessionsEndpoint");
}
if (notify != null && notify.length() > 0) {
config.setEndpoints(notify, sessions);
} else if (sessions != null && sessions.length() > 0) {
logger.warning("The session tracking endpoint should not be set "
+ "without the error reporting endpoint.");
}
if (options.hasKey("releaseStage")) {
String releaseStage = options.getString("releaseStage");
if (releaseStage != null && releaseStage.length() > 0) {
client.setReleaseStage(releaseStage);
}
}
if (options.hasKey("autoNotify")) {
if (options.getBoolean("autoNotify")) {
client.enableExceptionHandler();
} else {
client.disableExceptionHandler();
}
}
if (options.hasKey("codeBundleId")) {
String codeBundleId = options.getString("codeBundleId");
if (codeBundleId != null && codeBundleId.length() > 0) {
client.addToTab("app", "codeBundleId", codeBundleId);
}
}
if (options.hasKey("notifyReleaseStages")) {
ReadableArray stages = options.getArray("notifyReleaseStages");
if (stages != null && stages.size() > 0) {
String[] releaseStages = new String[stages.size()];
for (int i = 0; i < stages.size(); i++) {
releaseStages[i] = stages.getString(i);
}
client.setNotifyReleaseStages(releaseStages);
}
}
if (options.hasKey("automaticallyCollectBreadcrumbs")) {
boolean autoCapture = options.getBoolean("automaticallyCollectBreadcrumbs");
config.setAutomaticallyCollectBreadcrumbs(autoCapture);
}
// Process session tracking last in case the effects of other options
// should be captured as a part of the session
if (options.hasKey("autoCaptureSessions")) {
boolean autoCapture = options.getBoolean("autoCaptureSessions");
config.setAutoCaptureSessions(autoCapture);
if (autoCapture) {
// The launch event session is skipped because autoCaptureSessions
// was not set when Bugsnag was first initialized. Manually sending a
// session to compensate.
client.resumeSession();
}
}
}
}
|
package org.waterforpeople.mapping.app.web;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointMetricSummaryDto;
import org.waterforpeople.mapping.dao.AccessPointDao;
import org.waterforpeople.mapping.dao.GeoRegionDAO;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.GeoRegion;
import org.waterforpeople.mapping.domain.TechnologyType;
import org.waterforpeople.mapping.helper.AccessPointHelper;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.standards.dao.LOSScoreToStatusMappingDao;
import com.gallatinsystems.standards.dao.LevelOfServiceScoreDao;
import com.gallatinsystems.standards.domain.LOSScoreToStatusMapping;
import com.gallatinsystems.standards.domain.LevelOfServiceScore;
import com.gallatinsystems.standards.domain.Standard.StandardType;
import com.gallatinsystems.surveyal.domain.SurveyalValue;
import com.gallatinsystems.surveyal.domain.SurveyedLocale;
public class KMLGenerator {
private static final String IMAGE_ROOT = "imageroot";
private static final Logger log = Logger.getLogger(KMLGenerator.class
.getName());
private VelocityEngine engine;
public static final String GOOGLE_EARTH_DISPLAY = "googleearth";
// public static final String WATER_POINT_FUNCTIONING_GREEN_ICON_URL =
// PropertyUtil
// .getProperty(IMAGE_ROOT) + "/images/iconGreen36.png";
// public static final String WATER_POINT_FUNCTIONING_YELLOW_ICON_URL =
// PropertyUtil
// .getProperty(IMAGE_ROOT) + "/images/iconYellow36.png";
// public static final String WATER_POINT_FUNCTIONING_RED_ICON_URL =
// PropertyUtil
// .getProperty(IMAGE_ROOT) + "/images/iconRed36.png";
public static final String WATER_POINT_FUNCTIONING_GREEN_ICON_URL = PropertyUtil
.getProperty(IMAGE_ROOT) + "/images/glassGreen32.png";
public static final String WATER_POINT_FUNCTIONING_YELLOW_ICON_URL = PropertyUtil
.getProperty(IMAGE_ROOT) + "/images/glassOrange32.png";
public static final String WATER_POINT_FUNCTIONING_RED_ICON_URL = PropertyUtil
.getProperty(IMAGE_ROOT) + "/images/glassRed32.png";
public static final String WATER_POINT_FUNCTIONING_BLACK_ICON_URL = "http://watermapmonitordev.appspot.com/images/iconBlack36.png";
public static final String PUBLIC_INSTITUTION_FUNCTIONING_GREEN_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseGreen36.png";
public static final String PUBLIC_INSTITUTION_FUNCTIONING_YELLOW_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseYellow36.png";
public static final String PUBLIC_INSTITUTION_FUNCTIONING_RED_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseRed36.png";
public static final String PUBLIC_INSTITUTION_FUNCTIONING_BLACK_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseBlack36.png";
public static final String SCHOOL_INSTITUTION_FUNCTIONING_GREEN_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilGreen36.png";
public static final String SCHOOL_INSTITUTION_FUNCTIONING_YELLOW_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilYellow36.png";
public static final String SCHOOL_INSTITUTION_FUNCTIONING_RED_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilRed36.png";
public static final String SCHOOL_INSTITUTION_FUNCTIONING_BLACK_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilBlack36.png";
public static final Boolean useScore = Boolean.parseBoolean(PropertyUtil
.getProperty("scoreAPFlag"));
public static final String ORGANIZATION_KEY = "organization";
public static final String ORGANIZATION = PropertyUtil
.getProperty("organization");
private static final DateFormat LONG_DATE_FORMAT = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss z");
private static final Map<String, String> ICON_TYPE_MAPPING;
private static final Map<String, String> ICON_COLOR_MAPPING;
private static final String IMAGE_PREFIX = PropertyUtil
.getProperty(IMAGE_ROOT);
private static final String DEFAULT = "DEFAULT";
static {
ICON_TYPE_MAPPING = new HashMap<String, String>();
ICON_TYPE_MAPPING.put("WaterPoint", "glass");
ICON_TYPE_MAPPING.put("PublicInstitution", "house");
ICON_TYPE_MAPPING.put("Household", "house");
ICON_TYPE_MAPPING.put("School", "pencil");
ICON_TYPE_MAPPING.put("Trawler", "glass");
ICON_TYPE_MAPPING.put(DEFAULT, "glass");
ICON_COLOR_MAPPING = new HashMap<String, String>();
ICON_COLOR_MAPPING.put(DEFAULT, "Black36.png");
ICON_COLOR_MAPPING.put("FUNCTIONING_OK", "Green36.png");
ICON_COLOR_MAPPING.put("FUNCTIONING_HIGH", "Green36.png");
ICON_COLOR_MAPPING.put("FUNCTIONING_OK", "Yellow36.png");
ICON_COLOR_MAPPING.put("FUNCTIONING_WITH_PROBLEMS", "Yellow36.png");
ICON_COLOR_MAPPING.put("BROKEN_DOWN", "Black36.png");
ICON_COLOR_MAPPING.put("NO_IMPROVED_SYSTEM", "Black36.png");
}
/**
* forms the url for the placemark image based on the status
*
* @param type
* @param status
* @return
*/
public static String getMarkerImageUrl(String type, String status) {
String url = KMLGenerator.IMAGE_PREFIX + "/images/";
String typePart = KMLGenerator.ICON_TYPE_MAPPING
.get(type != null ? type : KMLGenerator.DEFAULT);
if (typePart == null) {
typePart = KMLGenerator.ICON_TYPE_MAPPING.get(KMLGenerator.DEFAULT);
}
url += typePart;
String statusPart = KMLGenerator.ICON_COLOR_MAPPING
.get(status != null ? status : KMLGenerator.DEFAULT);
if (statusPart == null) {
statusPart = KMLGenerator.ICON_COLOR_MAPPING
.get(KMLGenerator.DEFAULT);
}
url += statusPart;
return url;
}
public static final String useLongDates = PropertyUtil
.getProperty("useLongDates");
public KMLGenerator() {
engine = new VelocityEngine();
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
try {
engine.init();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
}
public static final String defaultPhotoCaption = PropertyUtil
.getProperty("defaultPhotoCaption");
private static final String DYNAMIC_SCORING_FLAG = null;
public String generateRegionDocumentString(String regionVMName) {
String regionKML = generateRegionOutlines(regionVMName);
return regionKML;
}
/**
* merges a hydrated context with a template identified by the templateName
* passed in.
*
* @param context
* @param templateName
* @return
* @throws Exception
*/
private String mergeContext(VelocityContext context, String templateName)
throws Exception {
Template t = engine.getTemplate(templateName);
StringWriter writer = new StringWriter();
t.merge(context, writer);
context = null;
return writer.toString();
}
public String generateDocument(String placemarksVMName) {
return generateDocument(placemarksVMName, Constants.ALL_RESULTS);
}
public String generateDocument(String placemarksVMName, String countryCode) {
try {
VelocityContext context = new VelocityContext();
String placemarks = generatePlacemarks(placemarksVMName,
countryCode);
context.put("folderContents", placemarks);
context.put("regionPlacemark", generateRegionOutlines("Regions.vm"));
return mergeContext(context, "Document.vm");
} catch (Exception ex) {
log.log(Level.SEVERE, "Could create kml", ex);
}
return null;
}
@SuppressWarnings("unused")
private String generateFolderContents(
HashMap<String, ArrayList<String>> contents, String vmName)
throws Exception {
VelocityContext context = new VelocityContext();
StringBuilder techFolders = new StringBuilder();
for (Entry<String, ArrayList<String>> techItem : contents.entrySet()) {
String key = techItem.getKey();
StringBuilder sbFolderPl = new StringBuilder();
for (String placemark : techItem.getValue()) {
sbFolderPl.append(placemark);
}
context.put("techFolderName", key);
context.put("techPlacemarks", sbFolderPl);
techFolders.append(mergeContext(context, "techFolders.vm"));
}
context.put("techFolders", techFolders.toString());
return mergeContext(context, vmName);
}
public void generateCountryOrderedPlacemarks(String vmName,
String countryCode, String technologyType) {
}
public HashMap<String, ArrayList<String>> generateCountrySpecificPlacemarks(
String vmName, String countryCode) {
if (countryCode.equals("MW")) {
HashMap<String, ArrayList<AccessPoint>> techMap = new HashMap<String, ArrayList<AccessPoint>>();
BaseDAO<TechnologyType> techDAO = new BaseDAO<TechnologyType>(
TechnologyType.class);
List<TechnologyType> techTypeList = (List<TechnologyType>) techDAO
.list(Constants.ALL_RESULTS);
AccessPointDao apDao = new AccessPointDao();
List<AccessPoint> waterAPList = apDao.searchAccessPoints(
countryCode, null, null, null, "WATER_POINT", null, null,
null, null, null, null, Constants.ALL_RESULTS);
for (TechnologyType techType : techTypeList) {
// log.info("TechnologyType: " + techType.getName());
ArrayList<AccessPoint> techTypeAPList = new ArrayList<AccessPoint>();
for (AccessPoint item : waterAPList) {
if (techType.getName().toLowerCase()
.equals("unimproved waterpoint")
&& item.getTypeTechnologyString().toLowerCase()
.contains("unimproved waterpoint")) {
techTypeAPList.add(item);
} else if (item.getTypeTechnologyString().equals(
techType.getName())) {
techTypeAPList.add(item);
}
}
techMap.put(techType.getName(), techTypeAPList);
}
List<AccessPoint> sanitationAPList = apDao.searchAccessPoints(
countryCode, null, null, null, "SANITATION_POINT", null,
null, null, null, null, null, Constants.ALL_RESULTS);
HashMap<String, AccessPoint> sanitationMap = new HashMap<String, AccessPoint>();
for (AccessPoint item : sanitationAPList) {
sanitationMap.put(item.getGeocells().toString(), item);
}
sanitationAPList = null;
HashMap<String, ArrayList<String>> techPlacemarksMap = new HashMap<String, ArrayList<String>>();
for (Entry<String, ArrayList<AccessPoint>> item : techMap
.entrySet()) {
String key = item.getKey();
ArrayList<String> placemarks = new ArrayList<String>();
for (AccessPoint waterAP : item.getValue()) {
AccessPoint sanitationAP = sanitationMap.get(waterAP
.getGeocells().toString());
if (sanitationAP != null) {
placemarks.add(buildMainPlacemark(waterAP,
sanitationAP, vmName));
} else {
log.info("No matching sanitation point found for "
+ waterAP.getLatitude() + ":"
+ waterAP.getLongitude() + ":"
+ waterAP.getCommunityName());
}
}
techPlacemarksMap.put(key, placemarks);
}
return techPlacemarksMap;
}
return null;
}
private HashMap<String, String> loadContextBindings(AccessPoint waterAP,
AccessPoint sanitationAP) {
// log.info(waterAP.getCommunityCode());
try {
HashMap<String, String> contextBindingsMap = new HashMap<String, String>();
if (waterAP.getCollectionDate() != null) {
String timestamp = DateFormatUtils.formatUTC(
waterAP.getCollectionDate(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
String formattedDate = DateFormat.getDateInstance(
DateFormat.SHORT).format(waterAP.getCollectionDate());
contextBindingsMap.put("collectionDate", formattedDate);
contextBindingsMap.put("timestamp", timestamp);
String collectionYear = new SimpleDateFormat("yyyy")
.format(waterAP.getCollectionDate());
contextBindingsMap.put("collectionYear", collectionYear);
} else {
// TODO: This block is a problem. We should never have data
// without a collectionDate so this is a hack so it display
// properly until I can sort out what to do with this data.
String timestamp = DateFormatUtils.formatUTC(new Date(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
String formattedDate = DateFormat.getDateInstance(
DateFormat.SHORT).format(new Date());
contextBindingsMap.put("collectionDate", formattedDate);
contextBindingsMap.put("timestamp", timestamp);
String collectionYear = new SimpleDateFormat("yyyy")
.format(new Date());
contextBindingsMap.put("collectionYear", collectionYear);
}
contextBindingsMap.put("communityCode",
encodeNullDefault(waterAP.getCommunityCode(), "Unknown"));
contextBindingsMap.put("communityName",
encodeNullDefault(waterAP.getCommunityName(), "Unknown"));
contextBindingsMap.put(
"typeOfWaterPointTechnology",
encodeNullDefault(waterAP.getTypeTechnologyString(),
"Unknown"));
contextBindingsMap.put(
"constructionDateOfWaterPoint",
encodeNullDefault(waterAP.getConstructionDateYear(),
"Unknown"));
contextBindingsMap.put(
"numberOfHouseholdsUsingWaterPoint",
encodeNullDefault(
waterAP.getNumberOfHouseholdsUsingPoint(),
"Unknown"));
contextBindingsMap.put("costPer20ML",
encodeNullDefault(waterAP.getCostPer(), "Unknown"));
contextBindingsMap.put(
"farthestHouseholdFromWaterPoint",
encodeNullDefault(waterAP.getFarthestHouseholdfromPoint(),
"Unknown"));
contextBindingsMap.put(
"currentManagementStructureOfWaterPoint",
encodeNullDefault(
waterAP.getCurrentManagementStructurePoint(),
"Unknown"));
contextBindingsMap.put("waterSystemStatus",
encodeStatusString(waterAP.getPointStatus()));
contextBindingsMap.put("photoUrl",
encodeNullDefault(waterAP.getPhotoURL(), "Unknown"));
contextBindingsMap
.put("waterPointPhotoCaption",
encodeNullDefault(waterAP.getPointPhotoCaption(),
"Unknown"));
contextBindingsMap.put(
"primarySanitationTechnology",
encodeNullDefault(sanitationAP.getTypeTechnologyString(),
"Unknown"));
contextBindingsMap.put(
"percentageOfHouseholdsWithImprovedSanitation",
encodeNullDefault(
sanitationAP.getNumberOfHouseholdsUsingPoint(),
"Unknown"));
contextBindingsMap.put("photoOfPrimarySanitationtechnology",
encodeNullDefault(sanitationAP.getPhotoURL(), "Unknown"));
contextBindingsMap.put(
"sanitationPhotoCaption",
encodeNullDefault(sanitationAP.getPointPhotoCaption(),
"Unknown"));
contextBindingsMap.put("footer",
encodeNullDefault(waterAP.getFooter(), "Unknown"));
contextBindingsMap.put(
"longitude",
encodeNullDefault(waterAP.getLongitude().toString(),
"Unknown"));
contextBindingsMap.put(
"latitude",
encodeNullDefault(waterAP.getLatitude().toString(),
"Unknown"));
contextBindingsMap.put("altitude",
encodeNullDefault(waterAP.getAltitude().toString(), "0.0"));
contextBindingsMap.put(
"pinStyle",
encodePinStyle(waterAP.getPointType(),
waterAP.getPointStatus()));
return contextBindingsMap;
} catch (NullPointerException nex) {
log.log(Level.SEVERE, "Could not load context bindings", nex);
}
return null;
}
private String buildMainPlacemark(AccessPoint waterAP,
AccessPoint sanitationAP, String vmName) {
HashMap<String, String> contextBindingsMap = loadContextBindings(
waterAP, sanitationAP);
VelocityContext context = new VelocityContext();
for (Map.Entry<String, String> entry : contextBindingsMap.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
StringBuilder sb = new StringBuilder();
String output = null;
try {
output = mergeContext(context, vmName);
} catch (Exception e) {
log.log(Level.SEVERE, "Could not build main placemark", e);
}
sb.append(output);
return sb.toString();
}
private String encodeNullDefault(Object value, String defaultMissingVal) {
try {
if (value != null) {
return value.toString();
} else {
return defaultMissingVal;
}
} catch (Exception ex) {
// log.info("value that generated nex: " + value);
log.log(Level.SEVERE, "Could not encode null default", ex);
}
return null;
}
public String generatePlacemarks(String vmName, String countryCode) {
return generatePlacemarks(vmName, countryCode, GOOGLE_EARTH_DISPLAY);
}
public String generatePlacemarks(String vmName, String countryCode,
String display) {
StringBuilder sb = new StringBuilder();
AccessPointDao apDAO = new AccessPointDao();
List<AccessPoint> entries = null;
if (countryCode.equals(Constants.ALL_RESULTS))
entries = apDAO.list(Constants.ALL_RESULTS);
else
entries = apDAO.searchAccessPoints(countryCode, null, null, null,
null, null, null, null, null, null, null,
Constants.ALL_RESULTS);
// loop through accessPoints and bind to variables
int i = 0;
try {
for (AccessPoint ap : entries) {
if (!ap.getPointType().equals(
AccessPoint.AccessPointType.SANITATION_POINT)) {
try {
VelocityContext context = new VelocityContext();
String pmContents = bindPlacemark(
ap,
display.equalsIgnoreCase(GOOGLE_EARTH_DISPLAY) ? "placemarkGoogleEarth.vm"
: "placemarkExternalMap.vm", display);
if (ap.getCollectionDate() != null) {
String timestamp = DateFormatUtils.formatUTC(ap
.getCollectionDate(),
DateFormatUtils.ISO_DATE_FORMAT
.getPattern());
String formattedDate = DateFormat.getDateInstance(
DateFormat.SHORT).format(
ap.getCollectionDate());
context.put("collectionDate", formattedDate);
context.put("timestamp", timestamp);
String collectionYear = new SimpleDateFormat("yyyy")
.format(ap.getCollectionDate());
context.put("collectionYear", collectionYear);
} else {
String timestamp = DateFormatUtils.formatUTC(
new Date(), DateFormatUtils.ISO_DATE_FORMAT
.getPattern());
String formattedDate = DateFormat.getDateInstance(
DateFormat.SHORT).format(new Date());
context.put("collectionDate", formattedDate);
context.put("timestamp", timestamp);
}
if (ap.getCommunityName() == null) {
context.put("communityName", "Unknown");
} else {
context.put("communityName", ap.getCommunityName());
}
if (ap.getCommunityCode() != null)
context.put("communityCode", ap.getCommunityCode());
else
context.put("communityCode", "Unknown" + new Date());
// Need to check this
if (ap.getPointType() != null) {
if (Boolean.parseBoolean(PropertyUtil
.getProperty(DYNAMIC_SCORING_FLAG))) {
} else {
encodeStatusString(ap, context);
context.put(
"pinStyle",
encodePinStyle(ap.getPointType(),
ap.getPointStatus()));
}
} else {
context.put("pinStyle", "waterpushpinblk");
}
context.put("latitude", ap.getLatitude());
context.put("longitude", ap.getLongitude());
if (ap.getAltitude() == null)
context.put("altitude", 0.0);
else
context.put("altitude", ap.getAltitude());
context.put("balloon", pmContents);
String placemarkStr = mergeContext(context, vmName);
sb.append(placemarkStr);
i++;
} catch (Exception e) {
log.log(Level.INFO, "Error generating placemarks: "
+ ap.getCommunityCode(), e);
}
}
}
} catch (Exception ex) {
log.log(Level.SEVERE, "Bad access point: "
+ entries.get(i + 1).toString());
}
return sb.toString();
}
public String bindPlacemark(SurveyedLocale ap, String vmName, String display)
throws Exception {
if (ap.getCountryCode() == null) {
ap.setCountryCode("Unknown");
}
VelocityContext context = new VelocityContext();
context.put("organization", ORGANIZATION);
if (display != null) {
context.put("display", display);
}
context.put("countryCode", ap.getCountryCode());
if (ap.getLastSurveyedDate() != null) {
String timestamp = DateFormatUtils.formatUTC(
ap.getLastSurveyedDate(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
String formattedDate = null;
if ("true".equals(useLongDates)) {
formattedDate = LONG_DATE_FORMAT.format(ap
.getLastSurveyedDate());
} else {
formattedDate = DateFormat.getDateInstance(DateFormat.SHORT)
.format(ap.getLastSurveyedDate());
}
context.put("collectionDate", formattedDate);
context.put("timestamp", timestamp);
String collectionYear = new SimpleDateFormat("yyyy").format(ap
.getLastSurveyedDate());
context.put("collectionYear", collectionYear);
} else {
String timestamp = DateFormatUtils.formatUTC(
ap.getCreatedDateTime(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
String formattedDate = null;
if ("true".equals(useLongDates)) {
formattedDate = LONG_DATE_FORMAT
.format(ap.getCreatedDateTime());
} else {
formattedDate = DateFormat.getDateInstance(DateFormat.SHORT)
.format(ap.getCreatedDateTime());
}
context.put("collectionDate", formattedDate);
context.put("timestamp", timestamp);
}
if (ap.getIdentifier() != null) {
context.put("identifier", ap.getIdentifier());
} else {
context.put("identifier", "Unknown" + new Date());
}
boolean foundPhoto = false;
boolean foundStatus = false;
if (ap.getSurveyalValues() != null) {
// TODO: handle case where we have multiple values (with different
// dates) for same question/metric
List<SurveyalValue> valuesToBind = new ArrayList<SurveyalValue>(
ap.getSurveyalValues());
for (SurveyalValue val : ap.getSurveyalValues()) {
if (val.getQuestionType() != null) {
if (!"free_text".equalsIgnoreCase(val.getQuestionType())
&& !"option"
.equalsIgnoreCase(val.getQuestionType())) {
valuesToBind.remove(val);
}
}
if (val.getStringValue() == null) {
valuesToBind.remove(val);
} else if (val.getStringValue().trim().toLowerCase()
.endsWith(".jpg")
|| val.getStringValue().trim().toLowerCase()
.endsWith(".jpeg")) {
String urlBase = val.getStringValue();
if (urlBase.contains("/")) {
urlBase = urlBase
.substring(urlBase.lastIndexOf("/") + 1);
}
if (!urlBase.toLowerCase().startsWith("http")) {
if (urlBase.endsWith("/")) {
urlBase = urlBase
.substring(0, urlBase.length() - 1);
}
urlBase = PropertyUtil.getProperty("photo_url_root")
+ urlBase;
}
context.put("photoUrl", urlBase);
foundPhoto = true;
valuesToBind.remove(val);
} else if (ap.getCurrentStatus() == null) {
if (val.getMetricName() != null
&& val.getMetricName().trim().toLowerCase()
.contains("status")) {
context.put("waterSystemStatus", val.getStringValue());
foundStatus = true;
}
}
}
context.put("surveyalValues", valuesToBind);
}
if (ap.getCurrentStatus() != null) {
try {
context.put("waterSystemStatus",
encodeStatusString(AccessPoint.Status.valueOf(ap
.getCurrentStatus())));
} catch (Exception e) {
context.put("waterSystemStatus", "Unknown");
}
} else {
if (!foundStatus) {
context.put("waterSystemStatus", "Unknown");
}
}
// TODO: parameterize the default logo
if (!foundPhoto) {
context.put("photoUrl",
"http://waterforpeople.s3.amazonaws.com/images/wfplogo.jpg");
}
context.put("latitude", ap.getLatitude());
context.put("longitude", ap.getLongitude());
if (ap.getLocaleType() != null) {
context.put("type", ap.getLocaleType());
} else {
context.put("type", "water");
}
String output = mergeContext(context, vmName);
context = null;
return output;
}
public String bindPlacemark(AccessPoint ap, String vmName, String display)
throws Exception {
// if (ap.getCountryCode() != null && !ap.getCountryCode().equals("MW"))
if (display != null
&& display.trim().equalsIgnoreCase(GOOGLE_EARTH_DISPLAY)) {
vmName = "placemarkGoogleEarth.vm";
}
if (ap.getCountryCode() == null)
ap.setCountryCode("Unknown");
if (ap.getCountryCode() != null) {
VelocityContext context = new VelocityContext();
context.put("organization", ORGANIZATION);
if (display != null) {
context.put("display", display);
}
context.put("countryCode", ap.getCountryCode());
if (ap.getCollectionDate() != null) {
String timestamp = DateFormatUtils.formatUTC(
ap.getCollectionDate(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
String formattedDate = DateFormat.getDateInstance(
DateFormat.SHORT).format(ap.getCollectionDate());
context.put("collectionDate", formattedDate);
context.put("timestamp", timestamp);
String collectionYear = new SimpleDateFormat("yyyy").format(ap
.getCollectionDate());
context.put("collectionYear", collectionYear);
} else {
String timestamp = DateFormatUtils.formatUTC(
ap.getCreatedDateTime(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
String formattedDate = DateFormat.getDateInstance(
DateFormat.SHORT).format(ap.getCreatedDateTime());
context.put("collectionDate", formattedDate);
context.put("timestamp", timestamp);
}
if (ap.getCommunityCode() != null)
context.put("communityCode", ap.getCommunityCode());
else
context.put("communityCode", "Unknown" + new Date());
if (ap.getWaterForPeopleProjectFlag() != null) {
context.put("waterForPeopleProject",
encodeBooleanDisplay(ap.getWaterForPeopleProjectFlag()));
} else {
context.put("waterForPeopleProject", "null");
}
if (ap.getCurrentProblem() != null) {
context.put("currentProblem", ap.getCurrentProblem());
} else {
context.put("currentProblem", ap.getCurrentProblem());
}
if (ap.getWaterForPeopleRole() != null) {
context.put("waterForPeopleRole", ap.getWaterForPeopleRole());
} else {
context.put("waterForPeopleRole", "null");
}
if (ap.getPhotoURL() != null && ap.getPhotoURL().trim() != "")
context.put("photoUrl", ap.getPhotoURL());
else
context.put("photoUrl",
"http://waterforpeople.s3.amazonaws.com/images/wfplogo.jpg");
if (ap.getPointType() != null) {
if (ap.getPointType().equals(
AccessPoint.AccessPointType.WATER_POINT)) {
context.put("typeOfPoint", "Water");
context.put("type", "water");
} else if (ap.getPointType().equals(
AccessPointType.SANITATION_POINT)) {
context.put("typeOfPoint", "Sanitation");
context.put("type", "sanitation");
} else if (ap.getPointType().equals(
AccessPointType.PUBLIC_INSTITUTION)) {
context.put("typeOfPoint", "Public Institutions");
context.put("type", "public_institutions");
} else if (ap.getPointType().equals(
AccessPointType.HEALTH_POSTS)) {
context.put("typeOfPoint", "Health Posts");
context.put("type", "health_posts");
} else if (ap.getPointType().equals(AccessPointType.SCHOOL)) {
context.put("typeOfPoint", "School");
context.put("type", "school");
}
} else {
context.put("typeOfPoint", "Water");
context.put("type", "water");
}
if (ap.getTypeTechnologyString() == null) {
context.put("primaryTypeTechnology", "Unknown");
} else {
context.put("primaryTypeTechnology",
ap.getTypeTechnologyString());
}
if (ap.getHasSystemBeenDown1DayFlag() == null) {
context.put("down1DayFlag", "Unknown");
} else {
context.put("down1DayFlag",
encodeBooleanDisplay(ap.getHasSystemBeenDown1DayFlag()));
}
if (ap.getInstitutionName() == null) {
context.put("institutionName", "Unknown");
} else {
context.put("institutionName", ap.getInstitutionName());
}
if (ap.getExtimatedPopulation() != null) {
context.put("estimatedPopulation", ap.getExtimatedPopulation());
} else {
context.put("estimatedPopulation", "null");
}
if (ap.getConstructionDateYear() == null
|| ap.getConstructionDateYear().trim().equals("")) {
context.put("constructionDateOfWaterPoint", "Unknown");
} else {
String constructionDateYear = ap.getConstructionDateYear();
if (constructionDateYear.contains(".0")) {
constructionDateYear = constructionDateYear.replace(".0",
"");
}
context.put("constructionDateOfWaterPoint",
constructionDateYear);
}
if (ap.getNumberOfHouseholdsUsingPoint() != null) {
context.put("numberOfHouseholdsUsingWaterPoint",
ap.getNumberOfHouseholdsUsingPoint());
} else {
context.put("numberOfHouseholdsUsingWaterPoint", "null");
}
if (ap.getCostPer() == null) {
context.put("costPer", "N/A");
} else {
context.put("costPer", ap.getCostPer());
}
if (ap.getFarthestHouseholdfromPoint() == null
|| ap.getFarthestHouseholdfromPoint().trim().equals("")) {
context.put("farthestHouseholdfromWaterPoint", "N/A");
} else {
context.put("farthestHouseholdfromWaterPoint",
ap.getFarthestHouseholdfromPoint());
}
if (ap.getCurrentManagementStructurePoint() == null) {
context.put("currMgmtStructure", "N/A");
} else {
context.put("currMgmtStructure",
ap.getCurrentManagementStructurePoint());
}
if (ap.getPointPhotoCaption() == null
|| ap.getPointPhotoCaption().trim().equals("")) {
context.put("waterPointPhotoCaption", defaultPhotoCaption);
} else {
context.put("waterPointPhotoCaption", ap.getPointPhotoCaption());
}
if (ap.getCommunityName() == null) {
context.put("communityName", "Unknown");
} else {
context.put("communityName", ap.getCommunityName());
}
if (ap.getHeader() == null) {
context.put("header", "Water For People");
} else {
context.put("header", ap.getHeader());
}
if (ap.getFooter() == null) {
context.put("footer", "Water For People");
} else {
context.put("footer", ap.getFooter());
}
if (ap.getPhotoName() == null) {
context.put("photoName", "Water For People");
} else {
context.put("photoName", ap.getPhotoName());
}
// if (ap.getCountryCode() == "RW") {
if (ap.getMeetGovtQualityStandardFlag() == null) {
context.put("meetGovtQualityStandardFlag", "N/A");
} else {
context.put("meetGovtQualityStandardFlag",
encodeBooleanDisplay(ap
.getMeetGovtQualityStandardFlag()));
}
// } else {
// context.put("meetGovtQualityStandardFlag", "unknown");
if (ap.getMeetGovtQuantityStandardFlag() == null) {
context.put("meetGovtQuantityStandardFlag", "N/A");
} else {
context.put("meetGovtQuantityStandardFlag",
encodeBooleanDisplay(ap
.getMeetGovtQuantityStandardFlag()));
}
if (ap.getWhoRepairsPoint() == null) {
context.put("whoRepairsPoint", "N/A");
} else {
context.put("whoRepairsPoint", ap.getWhoRepairsPoint());
}
if (ap.getSecondaryTechnologyString() == null) {
context.put("secondaryTypeTechnology", "N/A");
} else {
context.put("secondaryTypeTechnology",
ap.getSecondaryTechnologyString());
}
if (ap.getProvideAdequateQuantity() == null) {
context.put("provideAdequateQuantity", "N/A");
} else {
context.put("provideAdequateQuantity",
encodeBooleanDisplay(ap.getProvideAdequateQuantity()));
}
if (ap.getBalloonTitle() == null) {
context.put("title", "Water For People");
} else {
context.put("title", ap.getBalloonTitle());
}
if (ap.getProvideAdequateQuantity() == null) {
context.put("provideAdequateQuantity", "N/A");
} else {
context.put("provideAdequateQuantity",
encodeBooleanDisplay(ap.getProvideAdequateQuantity()));
}
if (ap.getQualityDescription() != null) {
context.put("qualityDescription", ap.getQualityDescription());
}
if (ap.getQuantityDescription() != null) {
context.put("quantityDescription", ap.getQuantityDescription());
}
if (ap.getSub1() != null) {
context.put("sub1", ap.getSub1());
}
if (ap.getSub2() != null) {
context.put("sub2", ap.getSub2());
}
if (ap.getSub3() != null) {
context.put("sub3", ap.getSub3());
}
if (ap.getSub4() != null) {
context.put("sub4", ap.getSub4());
}
if (ap.getSub5() != null) {
context.put("sub5", ap.getSub5());
}
if (ap.getSub6() != null) {
context.put("sub6", ap.getSub6());
}
if (ap.getAccessPointCode() != null) {
context.put("accessPointCode", ap.getAccessPointCode());
}
if (ap.getAccessPointUsage() != null) {
context.put("accessPointUsage", ap.getAccessPointUsage());
}
if (ap.getDescription() != null)
context.put("description", ap.getDescription());
else
context.put("description", "Unknown");
// Need to check this
if (ap.getPointType() != null) {
if (Boolean.parseBoolean(PropertyUtil
.getProperty(DYNAMIC_SCORING_FLAG))) {
HashMap<String,String> combinedScore = fetchLevelOfServiceScoreStatus(ap);
context.put("losPinStyle", combinedScore.get(StandardType.WaterPointLevelOfService));
context.put("sustainabilityStyle", combinedScore.get(StandardType.WaterPointSustainability));
} else {
encodeStatusString(ap, context);
context.put(
"pinStyle",
encodePinStyle(ap.getPointType(),
ap.getPointStatus()));
}
} else {
context.put("pinStyle", "waterpushpinblk");
}
String output = mergeContext(context, vmName);
context = null;
return output;
}
return null;
}
private HashMap<String, String> fetchLevelOfServiceScoreStatus(
AccessPoint ap) {
HashMap<String,String> losStyles = new HashMap<String,String>();
LevelOfServiceScoreDao losScoreDao = new LevelOfServiceScoreDao();
List<LevelOfServiceScore> losList = losScoreDao
.listByAccessPoint(ap.getKey());
LOSScoreToStatusMappingDao losScoreToStatusMappingDao = new LOSScoreToStatusMappingDao();
for (LevelOfServiceScore losItem : losList) {
LOSScoreToStatusMapping losScoreToStatusMapping = losScoreToStatusMappingDao.findByLOSScoreTypeAndScore(losItem.getScoreType(), losItem.getScore());
losStyles.put(losScoreToStatusMapping.getLevelOfServiceScoreType().toString(), losScoreToStatusMapping.getColor().toString());
}
return losStyles;
}
public String generateRegionOutlines(String vmName) {
StringBuilder sb = new StringBuilder();
GeoRegionDAO grDAO = new GeoRegionDAO();
List<GeoRegion> grList = grDAO.list();
try {
if (grList != null && grList.size() > 0) {
String currUUID = grList.get(0).getUuid();
VelocityContext context = new VelocityContext();
StringBuilder sbCoor = new StringBuilder();
// loop through GeoRegions and bind to variables
for (int i = 0; i < grList.size(); i++) {
GeoRegion gr = grList.get(i);
if (currUUID.equals(gr.getUuid())) {
sbCoor.append(gr.getLongitude() + ","
+ gr.getLatitiude() + "," + 0 + "\n");
} else {
currUUID = gr.getUuid();
context.put("coordinateString", sbCoor.toString());
sb.append(mergeContext(context, vmName));
context = new VelocityContext();
sbCoor = new StringBuilder();
sbCoor.append(gr.getLongitude() + ","
+ gr.getLatitiude() + "," + 0 + "\n");
}
}
context.put("coordinateString", sbCoor.toString());
sb.append(mergeContext(context, vmName));
return sb.toString();
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error generating region outlines", e);
}
return "";
}
private String encodeBooleanDisplay(Boolean value) {
if (value) {
return "Yes";
} else {
return "No";
}
}
public static String encodePinStyle(AccessPointType type,
AccessPoint.Status status) {
String prefix = "water";
if (AccessPointType.SANITATION_POINT == type) {
prefix = "sani";
} else if (AccessPointType.SCHOOL == type) {
prefix = "schwater";
} else if (AccessPointType.PUBLIC_INSTITUTION == type
|| AccessPointType.HEALTH_POSTS == type) {
prefix = "pubwater";
}
if (AccessPoint.Status.FUNCTIONING_HIGH == status) {
return prefix + "pushpingreen";
} else if (AccessPoint.Status.FUNCTIONING_OK == status
|| AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS == status) {
return prefix + "pushpinyellow";
} else if (AccessPoint.Status.BROKEN_DOWN == status) {
return prefix + "pushpinred";
} else if (AccessPoint.Status.NO_IMPROVED_SYSTEM == status) {
return prefix + "pushpinblk";
} else {
return prefix + "pushpinblk";
}
}
public static String encodePinStyle(String type, String status) {
String prefix = "water";
if (type != null) {
if ("SanitationPoint".equalsIgnoreCase(type)) {
prefix = "sani";
} else if ("School".equalsIgnoreCase(type)) {
prefix = "schwater";
} else if ("PublicInstitution".equalsIgnoreCase(type)) {
prefix = "pubwater";
}
}
if ("FUNCTIONING_HIGH".equalsIgnoreCase(status)) {
return prefix + "pushpingreen";
} else if ("FUNCTIONING_OK".equalsIgnoreCase(status)
|| "FUNCTIONING_WITH_PROBLEMS".equalsIgnoreCase(status)) {
return prefix + "pushpinyellow";
} else if ("BROKEN_DOWN".equalsIgnoreCase(status)) {
return prefix + "pushpinred";
} else if ("NO_IMPROVED_SYSTEM".equalsIgnoreCase(status)) {
return prefix + "pushpinblk";
} else {
return prefix + "pushpinblk";
}
}
private String encodeStatusString(AccessPoint ap, VelocityContext context) {
AccessPoint.Status status = ap.getPointStatus();
if (ap.getCollectionDate() == null
|| ap.getCollectionDate().before(new Date("01/01/2011"))
|| !useScore) {
if (status != null) {
if (AccessPoint.Status.FUNCTIONING_HIGH == status) {
context.put("waterSystemStatus",
"Meets Government Standards");
return "System Functioning and Meets Government Standards";
} else if (AccessPoint.Status.FUNCTIONING_OK == status
|| AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS == status) {
context.put("waterSystemStatus",
"Functioning but with Problems");
return "Functioning but with Problems";
} else if (AccessPoint.Status.BROKEN_DOWN == status) {
context.put("waterSystemStatus", "Broken-down system");
return "Broken-down system";
} else if (AccessPoint.Status.NO_IMPROVED_SYSTEM == status) {
context.put("waterSystemStatus", "No Improved System");
return "No Improved System";
} else {
context.put("waterSystemStatus", "Unknown");
return "Unknown";
}
} else {
context.put("waterSystemStatus", "Unknown");
return "Unknown";
}
} else {
String statusString = null;
try {
statusString = encodeStatusUsingScore(ap);
} catch (Exception ex) {
log.log(Level.INFO, "Couldn't score ap: " + ap.toString()
+ " " + ex);
}
if (statusString == null) {
statusString = "Unknown";
}
context.put("waterSystemStatus", statusString);
// will remove soon not necessary now that APs are getting scored on
// save
AccessPointDao apDao = new AccessPointDao();
apDao.save(ap);
return statusString;
}
}
private String encodeStatusString(AccessPoint.Status status) {
if (status == null) {
return "Unknown";
}
if (status.equals(AccessPoint.Status.FUNCTIONING_HIGH)) {
return "System Functioning and Meets Government Standards";
} else if (status.equals(AccessPoint.Status.FUNCTIONING_OK)
|| status.equals(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS)) {
return "Functioning but with Problems";
} else if (status.equals(AccessPoint.Status.BROKEN_DOWN)) {
return "Broken-down system";
} else if (status.equals(AccessPoint.Status.NO_IMPROVED_SYSTEM)) {
return "No Improved System";
} else {
return "Unknown";
}
}
public String encodeStatusUsingScore(AccessPoint ap)
throws InvocationTargetException, NoSuchMethodException {
Integer score = AccessPointHelper.scoreAccessPoint(ap).getScore();
Integer score2 = new AccessPointHelper().scoreAccessPointDynamic(ap)
.getScore();
if (score == 0) {
return "No Improved System";
} else if (score >= 1 && score <= 2) {
return "Basic Level Service";
} else if (score >= 3 && score <= 4) {
return "Intermediate Level Service";
} else if (score >= 5) {
return "High Level Service";
} else {
return "Unknown";
}
}
public String bindSummaryPlacemark(AccessPointMetricSummaryDto apsDto,
String vmName) throws Exception {
VelocityContext context = new VelocityContext();
StringBuilder sb = new StringBuilder();
context.put("organization", ORGANIZATION);
if (apsDto.getParentSubName() != null) {
context.put("subPath", apsDto.getParentSubName()
.replace("/", " | "));
}
context.put("subValue", apsDto.getSubValue());
context.put("waterPointCount", apsDto.getCount());
context.put("type", apsDto.getMetricValue());
sb.append(mergeContext(context, vmName));
return sb.toString();
}
}
|
package edu.duke.cabig.c3pr.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.ParticipantDao;
import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.domain.Address;
import edu.duke.cabig.c3pr.domain.ContactMechanism;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.Identifier;
import edu.duke.cabig.c3pr.domain.Participant;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.utils.ConfigurationProperty;
import edu.duke.cabig.c3pr.utils.Lov;
import edu.duke.cabig.c3pr.utils.StringUtils;
import edu.duke.cabig.c3pr.utils.web.propertyeditors.CustomDaoEditor;
import edu.duke.cabig.c3pr.web.participant.ParticipantDetailsTab;
import edu.duke.cabig.c3pr.web.participant.ParticipantAddressAndContactInfoTab;
import edu.duke.cabig.c3pr.web.participant.ParticipantSummaryTab;
import edu.duke.cabig.c3pr.utils.web.propertyeditors.ObjectGraphBasedEditor;
import edu.duke.cabig.c3pr.web.beans.DefaultObjectPropertyReader;
import gov.nih.nci.cabig.ctms.web.tabs.AbstractTabbedFlowFormController;
import gov.nih.nci.cabig.ctms.web.tabs.AutomaticSaveFlowFormController;
import gov.nih.nci.cabig.ctms.web.tabs.Flow;
import gov.nih.nci.cabig.ctms.web.tabs.Tab;
/**
* @author Ramakrishna
*
*/
public class EditParticipantController<C extends Participant> extends
AutomaticSaveFlowFormController<C, Participant, ParticipantDao> {
private static Log log = LogFactory.getLog(EditParticipantController.class);
private ParticipantDao participantDao;
private HealthcareSiteDao healthcareSiteDao;
protected ConfigurationProperty configurationProperty;
public EditParticipantController() {
setCommandClass(Participant.class);
Flow<C> flow = new Flow<C>("Edit Subject");
layoutTabs(flow);
setFlow(flow);
setBindOnNewForm(true);
}
protected void layoutTabs(Flow flow) {
flow.addTab(new ParticipantDetailsTab());
flow.addTab(new ParticipantAddressAndContactInfoTab());
flow.addTab(new ParticipantSummaryTab());
}
@Override
protected ParticipantDao getDao() {
return participantDao;
}
@Override
protected Participant getPrimaryDomainObject(C command) {
return command;
}
/**
* Override this in sub controller if summary is needed
*
* @return
*/
protected boolean isSummaryEnabled() {
return false;
}
@Override
protected Map<String, Object> referenceData(
HttpServletRequest httpServletRequest, int page) throws Exception {
// Currently the static data is a hack, once DB design is approved for
// an LOV this will be
// replaced with LOVDao to get the static data from individual tables
Map<String, Object> refdata = new HashMap<String, Object>();
Map<String, List<Lov>> configMap = configurationProperty.getMap();
if (("update")
.equals((httpServletRequest.getParameter("_updateaction"))))
switch (page) {
case 0:
refdata.put("updateMessageRefData", configMap.get(
"editParticipantMessages").get(0));
break;
case 1:
refdata.put("updateMessageRefData", configMap.get(
"editParticipantMessages").get(1));
break;
default:
}
return refdata;
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
*/
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
Participant participant = null;
if (request.getParameter("participantId") != null) {
System.out.println(" Request URl is:"
+ request.getRequestURL().toString());
participant = participantDao.getById(Integer.parseInt(request
.getParameter("participantId")), true);
System.out.println(" Participant's ID is:" + participant.getId());
}
boolean contactMechanismEmailPresent = false, contactMechanismPhonePresent = false, contactMechanismFaxPresent = false;
for (ContactMechanism contactMechanism : participant
.getContactMechanisms()) {
if (contactMechanism.getType().equals("Email"))
contactMechanismEmailPresent = true;
if (contactMechanism.getType().equals("Phone"))
contactMechanismPhonePresent = true;
if (contactMechanism.getType().equals("Fax"))
contactMechanismFaxPresent = true;
}
if (!contactMechanismEmailPresent) {
ContactMechanism contactMechanismEmail = new ContactMechanism();
contactMechanismEmail.setType("Email");
participant.getContactMechanisms().add(0, contactMechanismEmail);
}
if (!contactMechanismPhonePresent) {
ContactMechanism contactMechanismPhone = new ContactMechanism();
contactMechanismPhone.setType("Phone");
participant.getContactMechanisms().add(1, contactMechanismPhone);
}
if (!contactMechanismFaxPresent) {
ContactMechanism contactMechanismFax = new ContactMechanism();
contactMechanismFax.setType("Fax");
participant.getContactMechanisms().add(2, contactMechanismFax);
}
return participant;
}
protected void initBinder(HttpServletRequest req,
ServletRequestDataBinder binder) throws Exception {
super.initBinder(req, binder);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
new SimpleDateFormat("MM/dd/yyyy"), true));
binder.registerCustomEditor(HealthcareSite.class, new CustomDaoEditor(
healthcareSiteDao));
}
@Override
protected Object currentFormObject(HttpServletRequest request, Object sessionFormObject) throws Exception {
if (sessionFormObject != null) {
getDao().reassociate((Participant) sessionFormObject);
}
return sessionFormObject;
}
@Override
protected void postProcessPage(HttpServletRequest request, Object Command,
Errors errors, int page) {
Participant participant = (Participant) Command;
if ("update".equals(request.getParameter("_action"))) {
try {
log.debug(" -- Updating Subject--");
participantDao.save(participant);
} catch (RuntimeException e) {
log.debug("--Error while updating Subject
e.printStackTrace();
}
}
}
@Override
protected void onBind(HttpServletRequest request, Object command,
BindException errors) throws Exception {
// TODO Auto-generated method stub
super.onBind(request, command, errors);
handleRowDeletion(request, command);
}
public void handleRowDeletion(HttpServletRequest request, Object command)
throws Exception {
Enumeration enumeration = request.getParameterNames();
Hashtable<String, List<Integer>> table = new Hashtable<String, List<Integer>>();
while (enumeration.hasMoreElements()) {
String param = (String) enumeration.nextElement();
if (param.startsWith("_deletedRow-")) {
String[] params = param.split("-");
if (table.get(params[1]) == null)
table.put(params[1], new ArrayList<Integer>());
table.get(params[1]).add(new Integer(params[2]));
}
}
deleteRows(command, table);
}
public void deleteRows(Object command,
Hashtable<String, List<Integer>> table) throws Exception {
Enumeration<String> e = table.keys();
while (e.hasMoreElements()) {
String path = e.nextElement();
List col = (List) new DefaultObjectPropertyReader(command, path)
.getPropertyValueFromPath();
List<Integer> rowNums = table.get(path);
List temp = new ArrayList();
for (int i = 0; i < col.size(); i++) {
if (!rowNums.contains(new Integer(i)))
temp.add(col.get(i));
}
col.removeAll(col);
col.addAll(temp);
}
}
@Override
protected ModelAndView processFinish(HttpServletRequest request,
HttpServletResponse response, Object oCommand, BindException errors)
throws Exception {
Participant participant = (Participant) oCommand;
Iterator<ContactMechanism> cMIterator = participant
.getContactMechanisms().iterator();
StringUtils strUtil = new StringUtils();
while (cMIterator.hasNext()) {
ContactMechanism contactMechanism = cMIterator.next();
if (strUtil.isBlank(contactMechanism.getValue()))
cMIterator.remove();
}
participantDao.save(participant);
ModelAndView modelAndView = new ModelAndView(new RedirectView(
"searchparticipant.do"));
return modelAndView;
}
public HealthcareSiteDao getHealthcareSiteDao() {
return healthcareSiteDao;
}
public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) {
this.healthcareSiteDao = healthcareSiteDao;
}
public ParticipantDao getParticipantDao() {
return participantDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public ConfigurationProperty getConfigurationProperty() {
return configurationProperty;
}
public void setConfigurationProperty(
ConfigurationProperty configurationProperty) {
this.configurationProperty = configurationProperty;
}
}
|
package org.thingml.testjar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.thingml.testjar.lang.TargetedLanguage;
/**
*
* @author sintef
*/
public class CustomTest extends TestCase {
public List<Map.Entry<File, TargetedLanguage>> thingmlsrcs = new ArrayList<>();
public List<Map.Entry<File, TargetedLanguage>> targetedsrcs = new ArrayList<>();
public File testDir;
public File runExec;
public int nbSteps = 0;
public boolean sync = false;
public CustomTest (File testProperties, File tmpDir, List<TargetedLanguage> langs, File compilerJar) {
this.status = 0;
this.srcTestCase = testProperties;
this.isLastStepASuccess = true;
this.testDir = new File(tmpDir, testProperties.getName().split("\\.")[0]);
this.testDir.mkdir();
this.log = "";
this.compilerJar = compilerJar;
Properties prop = new Properties();
InputStream input = null;
String rawDepList;
try {
input = new FileInputStream(testProperties);
// load a properties file
prop.load(input);
String logF = prop.getProperty("log", testProperties.getName().split("\\.")[0] + ".log");
this.logFile = new File(testDir, logF);
// get the property value and print it out
rawDepList = prop.getProperty("depList");
String[] depList = rawDepList.split(",");
for(String str: depList) {
System.out.println("-> " + str.trim());
File srcFile = new File(testProperties.getParentFile(), prop.getProperty(str.trim() + "_src"));
TargetedLanguage l = TestHelper.getLang(langs, prop.getProperty(str.trim() + "_compiler"));
if(l != null)
this.thingmlsrcs.add(new HashMap.SimpleEntry<File, TargetedLanguage>(srcFile, l));
}
if(prop.getProperty("run") != null) {
this.runExec = new File(testProperties.getParentFile(), prop.getProperty("run"));
if(prop.getProperty("runMono") != null) {
if(prop.getProperty("runMono").compareToIgnoreCase("true") == 0)
this.sync = true;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
if(!thingmlsrcs.isEmpty()) {
this.ongoingCmd = thingmlsrcs.get(0).getValue().generateTargeted(thingmlsrcs.get(0).getKey(), this.testDir, this.compilerJar);
this.nbSteps = thingmlsrcs.size() * 2 + 1;
this.targetedsrcs.add(
new HashMap.SimpleEntry<File, TargetedLanguage>(
new File(
this.testDir,
thingmlsrcs.get(0).getKey().getName().split("\\.")[0]),
thingmlsrcs.get(0).getValue()));
}
for(Map.Entry<File, TargetedLanguage> e: this.thingmlsrcs) {
System.out.println(" -e: " + e.getKey().getName() + " | " + e.getValue().compilerID);
}
}
@Override
public void collectResults() {
log += "\n\n************************************************* ";
log += "\n\n[Cmd] ";
for(String str : ongoingCmd.cmd) {
log += str + " ";
}
log += "\n\n[stdout] ";
log += ongoingCmd.stdlog;
log += "\n\n[sterr] ";
log += ongoingCmd.errlog;
this.isLastStepASuccess = this.ongoingCmd.isSuccess;
if(this.ongoingCmd.isSuccess) {
this.status++;
System.out.println("s:" + this.status + " thingmlsrcs:" + this.thingmlsrcs.size() + " targetedsrcs:" + this.targetedsrcs.size());
if (this.status < this.thingmlsrcs.size()) {
this.ongoingCmd = thingmlsrcs.get(this.status).getValue().generateTargeted(thingmlsrcs.get(this.status).getKey(), this.testDir, this.compilerJar);
this.targetedsrcs.add(
new HashMap.SimpleEntry<File, TargetedLanguage>(
new File(
this.testDir,
thingmlsrcs.get(this.status).getKey().getName().split("\\.")[0]),
thingmlsrcs.get(this.status).getValue()));
} else {
if ((this.status - this.thingmlsrcs.size()) < this.targetedsrcs.size()) {
this.ongoingCmd = targetedsrcs.get(this.status - this.thingmlsrcs.size()).getValue().compileTargeted(targetedsrcs.get(this.status - this.thingmlsrcs.size()).getKey());
} else {
String[] runCmd = new String[1];
runCmd[0] = this.runExec.getAbsolutePath();
if(this.sync)
this.ongoingCmd = new SynchronizedCommand(runCmd, ".+", null, "Error at c execution", testDir);
else
this.ongoingCmd = new Command(runCmd, ".+", null, "Error at c execution", testDir);
}
}
}
writeLogFile();
}
}
|
//@@author A0138848M
package seedu.oneline.model.task;
import static org.junit.Assert.*;
import java.util.Calendar;
import java.util.Locale;
import seedu.oneline.commons.exceptions.IllegalValueException;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class TaskTimeTest {
Calendar now;
Calendar yesterday;
Calendar tomorrow;
int thisDay;
int thisMonth;
int thisYear;
@Before
public void setUp(){
now = Calendar.getInstance();
yesterday = Calendar.getInstance();
yesterday.add(Calendar.DATE, -1);
tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, -1);
thisDay = now.get(Calendar.DAY_OF_MONTH);
thisMonth = now.get(Calendar.MONTH);
thisYear = now.get(Calendar.YEAR);
}
@Rule
public ExpectedException thrown = ExpectedException.none();
private void IllegalValueExceptionThrown(String inputDateTime, String errorMessage) throws Exception{
thrown.expect(IllegalValueException.class);
thrown.expectMessage(errorMessage);
new TaskTime(inputDateTime);
}
// Tests for invalid datetime inputs to TaskTime constructor
/**
* Invalid equivalence partitions for datetime: null, other strings
*/
@Test
public void constructor_nullDateTime_assertionThrown() {
thrown.expect(AssertionError.class);
try {
new TaskTime(null);
} catch (IllegalValueException e){
assert false;
}
}
@Test
public void constructor_unsupportedDateTimeFormats_assertionThrown() throws Exception {
IllegalValueExceptionThrown("day after", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
IllegalValueExceptionThrown("clearly not a time format", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
IllegalValueExceptionThrown("T u e s d a y", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
}
// Tests for valid datetime inputs
/**
* Valid equivalence partitions for datetime:
* - day month and year specified
* - only day and month specified
* - only day specified
* - relative date specified
* - empty string
*/
// test cases for date, month and year input
@Test
public void constructor_emptyDateTime_isAccepted() {
try {
TaskTime t = new TaskTime("");
assert t.getDate() == null;
} catch (Exception e) {
assert false;
}
}
@Test
public void constructor_dateMonthYear_supportsDocumentedFormats() {
String[] validFormats = new String[]{
"5 October 2016",
"5 Oct 16",
"Oct 5 16",
"10/5/16",
"10/05/16",
"oCt 5 16"};
try {
for (String t : validFormats) {
TaskTime tTime = new TaskTime(t);
Calendar tCal = DateUtils.toCalendar(tTime.getDate());
assertTrue(tCal.get(Calendar.DAY_OF_MONTH) == 5);
assertTrue(tCal.get(Calendar.MONTH) == Calendar.OCTOBER);
assertTrue(tCal.get(Calendar.YEAR) == 2016);
}
} catch (Exception e) {
assert false;
}
}
// test cases for only date and month input
/**
* Boundary cases for fields with only date and month input
* - date and month has passed in current year
* - date and month has not passed in current year
* - date and month is the current day
*/
@Test
public void constructor_dateMonth_supportsDocumentedFormats() {
String[] validFormats = new String[]{
"5 October",
"5 Oct",
"10/5",
"5 ocT"};
try {
for (String t : validFormats) {
TaskTime tTime = new TaskTime(t);
Calendar tCal = DateUtils.toCalendar(tTime.getDate());
assertTrue(tCal.get(Calendar.DAY_OF_MONTH) == 5);
assertTrue(tCal.get(Calendar.MONTH) == Calendar.OCTOBER);
// checks if date refers to previous year if day has passed
assertTrue(tCal.get(Calendar.YEAR) == thisYear);
}
} catch (Exception e) {
assert false;
}
}
/**
* Tests whether inputting a date and month that has passed will result
* in current year's value in task time object
*/
@Test
public void constructor_dateMonthPast_setsCorrectYear() {
// construct a string that represents MM/DD
// where MM/DD is the month and date of yesterday
String yesterdayString = Integer.toString(yesterday.get(Calendar.DAY_OF_MONTH))
+ " " + Integer.toString(yesterday.get(Calendar.MONTH));
try {
TaskTime tTime = new TaskTime(yesterdayString);
Calendar tCal = DateUtils.toCalendar(tTime.getDate());
assertTrue(tCal.get(Calendar.YEAR) == now.get(Calendar.YEAR));
} catch (Exception e) {
assert false;
}
}
/**
* Tests whether inputting today's date and month causes
* the year stored in TaskTime to remain the same as today's year
*/
@Test
public void constructor_dateMonthToday__setsCorrectYear() {
String todayString = Integer.toString(thisMonth)
+ " " + Integer.toString(thisDay);
try {
TaskTime tTime = new TaskTime(todayString);
Calendar tCal = DateUtils.toCalendar(tTime.getDate());
assertTrue(tCal.get(Calendar.YEAR) == thisYear);
} catch (Exception e) {
assert false;
}
}
/**
* Tests whether inputting tomorrow's date and month causes
* the year stored in TaskTime to remain the same as tomorrow's year
*/
@Test
public void constructor_dateMonthFuture_setsCorrectYear() {
// construct a string that represents MM/DD
// where MM/DD is the month and date of tomorrow
String tomorrowString = Integer.toString(tomorrow.get(Calendar.DAY_OF_MONTH))
+ " " + Integer.toString(tomorrow.get(Calendar.MONTH));
try {
TaskTime tTime = new TaskTime(tomorrowString);
Calendar tCal = DateUtils.toCalendar(tTime.getDate());
assertTrue(tCal.get(Calendar.YEAR) == tomorrow.get(Calendar.YEAR));
} catch (Exception e) {
assert false;
}
}
// Tests for day specified only
/**
* Boundary cases for fields with only day input
* - day has passed from today
* - day has not passed from today
* - day is today
*/
@Test
public void constructor_day_supportsDocumentedFormats() {
String[] validFormats = new String[]{
"Monday",
"this mon",
"MoNday"};
try {
for (String t : validFormats) {
Calendar tCal = new TaskTime(t).getCalendar();
assertTrue(tCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY);
}
} catch (Exception e) {
assert false;
}
}
/**
* Tests whether inputting a day that has passed will result in
* nearest upcoming day being stored in tasktime
*/
@Test
public void constructor_day_resultsInNextUpcomingDay() {
Calendar[] testDays = new Calendar[]{
yesterday, now, tomorrow
};
try {
for (Calendar d : testDays) {
String t = d.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
TaskTime tTime = new TaskTime(t);
Calendar tCal = tTime.getCalendar();
assertTrue(withinSevenDays(d, tCal));
}
} catch (Exception e) {
assert false;
}
}
/**
* Returns true if the two dates are between 1 to 7 days apart (both inclusive)
* @param d1
* @param d2
* @return true if difference between the two dates is 7
*/
private boolean withinSevenDays(Calendar d1, Calendar d2) {
Calendar nightOfd1 = (Calendar) d1.clone();
nightOfd1.set(Calendar.HOUR, 23);
nightOfd1.set(Calendar.MINUTE, 59);
Calendar sevenDaysAfterd1 = (Calendar) nightOfd1.clone();
sevenDaysAfterd1.add(Calendar.DAY_OF_MONTH, 7);
return nightOfd1.before(d2) && d2.before(sevenDaysAfterd1);
}
// test cases for relative day entries (next DAY, today, tomorrow)
@Test
public void constructor_relativeDay_supportsDocumentedFormats() {
try {
Calendar tCal = new TaskTime("next mon").getCalendar();
assertTrue(tCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY);
} catch (IllegalValueException e) {
assert false;
}
}
/**
* Employs exhaustive testing for all valid days to make sure that
* the day referenced by "next DAY" is
* the DAY >= this coming Sunday and <= the nearest Sunday after this coming Sunday
*/
@Test
public void constructor_relativeDay_pointsToNearestDayAfterSunday() {
Calendar thisSunday = (Calendar) now.clone(); // this past sunday (may include today)
thisSunday.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
thisSunday.set(Calendar.HOUR_OF_DAY,0);
thisSunday.set(Calendar.MINUTE,0);
thisSunday.set(Calendar.SECOND,0);
thisSunday.add(Calendar.DATE,7);
Calendar nextSunday = (Calendar) thisSunday.clone();
nextSunday.add(Calendar.DATE,7);
String[] days = new String[]{
"next mon",
"next tue",
"next wed",
"next thu",
"next fri",
"next sat",
"next sun"
};
try {
for (String day : days){
Calendar tCal = new TaskTime(day).getCalendar();
assertTrue(tCal.after(thisSunday) || tCal.equals(thisSunday));
assertTrue(tCal.before(nextSunday));
}
} catch (IllegalValueException e) {
assert false;
}
}
}
|
package eu.livotov.labs.android.robotools.geo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
public class RTGoogleMaps
{
public static boolean intiMap(GoogleMap map)
{
return intiMap(map, null);
}
public static boolean intiMap(GoogleMap map, Activity activity)
{
if (activity != null && !isGoogleMapsAvailable(activity))
{
return false;
}
map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(true);
map.getUiSettings().setRotateGesturesEnabled(true);
map.getUiSettings().setAllGesturesEnabled(true);
map.getUiSettings().setTiltGesturesEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setZoomGesturesEnabled(true);
map.getUiSettings().setCompassEnabled(true);
if (activity != null)
{
try
{
MapsInitializer.initialize(activity);
} catch (GooglePlayServicesNotAvailableException e)
{
return false;
}
}
return true;
}
public static boolean intiMapForInlinePreview(GoogleMap map)
{
return intiMapForInlinePreview(map, null);
}
public static boolean intiMapForInlinePreview(GoogleMap map, Activity activity)
{
if (activity != null && !isGoogleMapsAvailable(activity))
{
return false;
}
map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setRotateGesturesEnabled(false);
map.getUiSettings().setAllGesturesEnabled(false);
map.getUiSettings().setTiltGesturesEnabled(false);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setZoomGesturesEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setScrollGesturesEnabled(false);
if (activity != null)
{
try
{
MapsInitializer.initialize(activity);
} catch (GooglePlayServicesNotAvailableException e)
{
return false;
}
}
return true;
}
public static void toggleSatelliteMode(GoogleMap map, boolean satellite)
{
if (map == null)
{
return;
}
map.setMapType(satellite ? GoogleMap.MAP_TYPE_SATELLITE : GoogleMap.MAP_TYPE_NORMAL);
}
public static boolean isSatelliteMode(GoogleMap map)
{
if (map == null)
{
return false;
}
return map.getMapType() == GoogleMap.MAP_TYPE_SATELLITE;
}
public static void moveMapTo(GoogleMap map, double lat, double lon, float zoom, boolean animate)
{
if (map == null)
{
return;
}
CameraUpdate position = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), zoom == 0.0 ? 14.0f : zoom);
if (animate)
{
map.animateCamera(position);
} else
{
map.moveCamera(position);
}
}
public static boolean isGoogleMapsAvailable(Context ctx)
{
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(ctx) == ConnectionResult.SUCCESS && checkGmsServiceInstalled(ctx);
}
private static boolean checkGmsServiceInstalled(final Context ctx)
{
try
{
ApplicationInfo info = ctx.getPackageManager().getApplicationInfo("com.google.android.gms", 0);
return info != null;
} catch (PackageManager.NameNotFoundException e)
{
}
return false;
}
public static void installGoogleMapsIfRequired(final Activity activity)
{
int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
if (code != ConnectionResult.SUCCESS)
{
Dialog d = GooglePlayServicesUtil.getErrorDialog(code, activity, 987);
if (d != null)
{
d.show();
}
} else if (!checkGmsServiceInstalled(activity))
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder
.setTitle("Google Play Services Not Installed")
.setMessage("In order to use Google Maps in this application, you must install Google Maps and Google Play Services applications to your device.\n\nWould you like to go to Goole Play (tm) to install them now ?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
try
{
// Try the new HTTP scheme first (I assume that is the official way now given that google uses it).
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.gms"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setPackage("com.android.vending");
activity.startActivity(intent);
} catch (ActivityNotFoundException e)
{
// Ok that didn't work, try the market method.
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.gms"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setPackage("com.android.vending");
activity.startActivity(intent);
} catch (ActivityNotFoundException f)
{
// Ok, weird. Maybe they don't have any market app. Just show the website.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.gms"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
})
.create().show();
}
}
}
|
package uk.nhs.ciao.cda.builder;
import java.util.Date;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import uk.nhs.interoperability.payloads.CodedValue;
import uk.nhs.interoperability.payloads.DateValue;
import uk.nhs.interoperability.payloads.commontypes.Address;
import uk.nhs.interoperability.payloads.commontypes.ConsentID;
import uk.nhs.interoperability.payloads.commontypes.OrgID;
import uk.nhs.interoperability.payloads.commontypes.PatientID;
import uk.nhs.interoperability.payloads.commontypes.PersonID;
import uk.nhs.interoperability.payloads.commontypes.PersonName;
import uk.nhs.interoperability.payloads.commontypes.RoleID;
import uk.nhs.interoperability.payloads.commontypes.Telecom;
import uk.nhs.interoperability.payloads.noncodedcdav2.ClinicalDocument;
import uk.nhs.interoperability.payloads.noncodedcdav2.PrimaryRecipient;
import uk.nhs.interoperability.payloads.templates.AuthorPersonUniversal;
import uk.nhs.interoperability.payloads.templates.Consent;
import uk.nhs.interoperability.payloads.templates.CustodianOrganizationUniversal;
import uk.nhs.interoperability.payloads.templates.LanguageCommunication;
import uk.nhs.interoperability.payloads.templates.PatientUniversal;
import uk.nhs.interoperability.payloads.templates.RecipientPersonUniversal;
import uk.nhs.interoperability.payloads.util.CDAUUID;
import uk.nhs.interoperability.payloads.util.FileLoader;
import uk.nhs.interoperability.payloads.vocabularies.generated.DocumentConsentSnCT;
import uk.nhs.interoperability.payloads.vocabularies.generated.Documenttype;
import uk.nhs.interoperability.payloads.vocabularies.generated.HumanLanguage;
import uk.nhs.interoperability.payloads.vocabularies.generated.JobRoleName;
import uk.nhs.interoperability.payloads.vocabularies.generated.Sex;
import uk.nhs.interoperability.payloads.vocabularies.generated.x_BasicConfidentialityKind;
import uk.nhs.interoperability.payloads.vocabularies.internal.AddressType;
import uk.nhs.interoperability.payloads.vocabularies.internal.AttachmentType;
import uk.nhs.interoperability.payloads.vocabularies.internal.DatePrecision;
import uk.nhs.interoperability.payloads.vocabularies.internal.OrgIDType;
import uk.nhs.interoperability.payloads.vocabularies.internal.PatientIDType;
import uk.nhs.interoperability.payloads.vocabularies.internal.PersonIDType;
import uk.nhs.interoperability.payloads.vocabularies.internal.TelecomUseType;
public class CDADocExample {
public static void main(String[] args) {
ClinicalDocument template = createCommonFields();
// Non XML Body
template.setNonXMLBodyType(AttachmentType.Base64.code);
template.setNonXMLBodyMediaType("text/xml");
String data = FileLoader.loadFile(CDADocExample.class.getResourceAsStream("/attachment.txt"));
// Using the standard Java 6 base64 encoder
String base64data = Base64Utils.encodeToString(data.getBytes());
template.setNonXMLBodyText(base64data);
// Serialise and dump to log
LoggerFactory.getLogger(CDADocExample.class).info("Serialised ClinicalDocument:\n" + template.serialise());
}
public static ClinicalDocument createCommonFields() {
ClinicalDocument template = new ClinicalDocument();
template.setDocumentId(CDAUUID.generateUUIDString());
template.setDocumentTitle("Report");
template.setDocumentType(Documenttype._Report);
template.setEffectiveTime(new DateValue(new Date(), DatePrecision.Minutes));
template.setConfidentialityCode(x_BasicConfidentialityKind._V);
template.setDocumentSetId(CDAUUID.generateUUIDString());
template.setDocumentVersionNumber("1");
// Patient
template.setPatient(createPatient()); // From PDS
// Author
template.setTimeAuthored(new DateValue(new Date(), DatePrecision.Minutes)); // Take from file metadata?
template.setAuthor(createAuthor()); // From static JSON?
// Custodian
template.setCustodianOrganisation(createCustodian()); // From static JSON?
// Recipients
template.addPrimaryRecipients(new PrimaryRecipient(createRecipient())); // From PDS
// Authorisation
template.setAuthorizingConsent(createConsent());
return template;
}
public static PatientUniversal createPatient() {
PatientUniversal template = new PatientUniversal();
template.addPatientID(new PatientID()
.setPatientID("K12345")
.setAssigningOrganisation("V396A:Medway PCT")
.setPatientIDType(PatientIDType.LocalID.code));
template.addPatientID(new PatientID()
.setPatientID("993254128")
.setPatientIDType(PatientIDType.UnverifiedNHSNumber.code));
template.addAddress(new Address()
.addAddressLine("17, County Court")
.addAddressLine("Woodtown")
.addAddressLine("Medway")
.setPostcode("ME5 FS3")
.setAddressUse(AddressType.Home.code));
template.addAddress(new Address()
.addAddressLine("Hightown Retirement Home")
.addAddressLine("2, Brancaster Road")
.addAddressLine("Medway")
.addAddressLine("Kent")
.setPostcode("ME5 FL5")
.setAddressUse(AddressType.PhysicalVisit.code));
template.addTelephoneNumber(new Telecom()
.setTelecom("tel:01634775667")
.setTelecomType(TelecomUseType.HomeAddress.code));
template.addTelephoneNumber(new Telecom()
.setTelecom("tel:01634451628")
.setTelecomType(TelecomUseType.VacationHome.code));
template.addTelephoneNumber(new Telecom()
.setTelecom("mailto:mark.smith@emailfree.co.uk")
.setTelecomType(TelecomUseType.HomeAddress.code));
template.addPatientName(new PersonName()
.setTitle("Mr")
.addGivenName("Mark")
.setFamilyName("Smith"));
template.setSex(Sex._Male);
template.setBirthTime(new DateValue("19490101"));
// Language
LanguageCommunication language = new LanguageCommunication();
language.setLanguage(HumanLanguage._en.code);
template.addLanguages(language);
// Organisation - Registered GP:
template.setRegisteredGPOrgId(new OrgID()
.setID("V396F")
.setType(OrgIDType.ODSOrgID.code));
template.setRegisteredGPOrgName("Medway Medical Practice");
template.addRegisteredGPTelephone(new Telecom()
.setTelecom("tel:01634111222")
.setTelecomType(TelecomUseType.WorkPlace.code));
template.setRegisteredGPAddress(new Address()
.addAddressLine("Springer Street")
.addAddressLine("Medway")
.setPostcode("ME5 5TY")
.setAddressUse(AddressType.WorkPlace.code));
return template;
}
public static AuthorPersonUniversal createAuthor() {
AuthorPersonUniversal template = new AuthorPersonUniversal();
template.addId(new PersonID()
.setType(PersonIDType.LocalPersonID.code)
.setID("101")
.setAssigningOrganisation("5L399:Medway NHS Foundation Trust"));
// In the sample XML the SDSJobRoleName vocab is used (which is an empty vocab). We will use it's OID here:
template.setJobRoleName(new CodedValue("OOH02","Nurse Practitioner","2.16.840.1.113883.2.1.3.2.4.17.196"));
template.setName(new PersonName()
.addGivenName("Mary")
.setFamilyName("Jones"));
template.setOrganisationId(new OrgID()
.setID("5L399")
.setType(OrgIDType.ODSOrgID.code));
template.setOrganisationName("Medway NHS Foundation Trust");
return template;
}
public static CustodianOrganizationUniversal createCustodian() {
CustodianOrganizationUniversal template = new CustodianOrganizationUniversal();
template.setId(new OrgID(OrgIDType.ODSOrgID.code, "5L3"));
template.setName("Medway NHS Foundation Trust");
return template;
}
public static RecipientPersonUniversal createRecipient() {
RecipientPersonUniversal template = new RecipientPersonUniversal();
template.addId(new RoleID()
.setID("1234512345")
.setAssigningOrganisation("V396A:Medway PCT"));
template.addTelephoneNumber(new Telecom()
.setTelecom("mailto:t.hall@emailfree.co.uk"));
template.setJobRoleName(JobRoleName._SpecialistNursePractitioner);
template.setName(new PersonName()
.setTitle("Mr")
.setFamilyName("Hall")
.addGivenName("Terence"));
template.setOrgId(new OrgID()
.setID("V396A")
.setType(OrgIDType.ODSOrgID.code));
template.setOrgName("Medway PCT");
return template;
}
public static Consent createConsent() {
Consent template = new Consent();
template.addID(new ConsentID(CDAUUID.generateUUIDString()));
template.setConsentCode(DocumentConsentSnCT._Consentgiventosharepatientdatawithspecifiedthirdparty);
return template;
}
}
|
package net.jselby.escapists.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFontCache;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import net.jselby.escapists.EscapistsRuntime;
import net.jselby.escapists.PlatformUtils;
import org.mini2Dx.core.game.BasicGame;
import org.mini2Dx.core.graphics.Graphics;
import org.mini2Dx.core.graphics.Sprite;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class EscapistsGame extends BasicGame {
public static final String GAME_IDENTIFIER = "net.jselby.escapists";
private static double UPDATE_INTERVAL = 1000d / 45d;
private Sprite loadingLogo;
private BitmapFont loadingFont;
private BitmapFontCache loadingFontCache;
private float loadingTextWidth;
private String loadingText = "Loading...";
private Application app;
private Scene currentFrame;
private AudioManager audio;
private PlatformUtils utils;
private int sceneIndex;
private int nextScene = -1;
public Map<Integer, Number> globalInts;
public Map<Integer, String> globalStrings;
public ArrayList<String> mods;
private boolean pauseError = false;
private long lastFrame;
private double diff;
private long tpsSwitch;
private int lastTPS;
private int tps;
private short[] mouseClicked = new short[3];
public EscapistsGame(PlatformUtils utils) {
this.utils = utils;
}
@Override
public void initialise() {
globalInts = new HashMap<Integer, Number>();
globalStrings = new HashMap<Integer, String>();
mods = new ArrayList<String>();
audio = new AudioManager();
loadingLogo = new Sprite(new Texture(Gdx.files.internal("logo.png")));
// Load the initial font, if possible
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/Escapists.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.minFilter = Texture.TextureFilter.Nearest;
parameter.magFilter = Texture.TextureFilter.MipMapLinearNearest;
parameter.size = height / 10;
parameter.genMipMaps = false;
parameter.flip = true;
loadingFont = generator.generateFont(parameter); // font size 12 pixels
generator.dispose();
loadingFontCache = loadingFont.newFontCache();
loadingTextWidth = loadingFontCache.addText(loadingText, 0, 0).width;
// Add our default mod
mods.add(":Leaderboards\n@170: WorldInteraction.withObjects(546 /*hover*/).SetY((((Expressions.YMouse()/11) | 0)*11)+2);");
// Start up the loading thread
Thread loadingThread = new Thread(new Runnable() {
@Override
public void run() {
try {
EscapistsRuntime runtime = new EscapistsRuntime();
if (!runtime.start(EscapistsGame.this)) {
return;
}
app = runtime.getApplication();
try {
// Let the GFX thread catch up
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
EscapistsGame.this.app = app;
if (EscapistsRuntime.DEBUG) System.out.println("Callback from app, all assets prepared.");
try {
app.init(EscapistsGame.this);
UPDATE_INTERVAL = 1000d / ((double) app.getTargetFPS());
loadScene(0); // 2 = title screen, 6 = game
} catch (IOException e) {
e.printStackTrace();
}
loadingFont.dispose();
loadingFont = null;
loadingLogo = null;
System.gc();
}
});
} catch (IOException e) {
e.printStackTrace();
getPlatformUtils().showFatalMessageBox("Fatal Error", e.getLocalizedMessage());
}
}
});
loadingThread.setName("Asset Loading Thread");
loadingThread.start();
}
private void loadFrame(Scene scene) {
currentFrame = scene;
System.out.println("Launching frame: " + currentFrame.getName().trim());
scene.init();
}
public int getSceneIndex() {
return sceneIndex;
}
public void loadScene(int id) {
nextScene = id;
}
@Override
public void update(float delta) {
audio.tick();
if (!pauseError && nextScene != -1) {
// Load the next scene
sceneIndex = nextScene;
loadFrame(app.frames.get(nextScene));
lastFrame = System.currentTimeMillis();
tpsSwitch = lastFrame;
tps = 0;
diff = 0;
nextScene = -1;
}
if (currentFrame == null) {
return;
}
if (pauseError) {
for (Layer layer : currentFrame.getLayers()) {
if (!layer.isVisible()) { // "IsShow" flag
continue;
}
layer.tick(this);
}
return;
}
// Attempt to target 45fps
long start = System.currentTimeMillis();
diff += start - lastFrame;
lastFrame = start;
while(System.currentTimeMillis() - start < 10.00d && diff >= UPDATE_INTERVAL) {
// Parse input
for (int i = 0; i <= 2; i++) {
if (Gdx.input.isButtonPressed(i)) {
if (mouseClicked[i] > 0) {
mouseClicked[i] = 2;
} else {
mouseClicked[i] = 1;
}
} else {
mouseClicked[i] = 0;
}
}
currentFrame.tick();
tps++;
diff -= UPDATE_INTERVAL;
}
if (diff >= UPDATE_INTERVAL) {
System.err.println("Cannot keep up! Having to call tick() too many times per frame.");
diff = 0;
}
if (System.currentTimeMillis() - tpsSwitch >= 1000) {
tpsSwitch = System.currentTimeMillis() + System.currentTimeMillis() - tpsSwitch - 1000;
lastTPS = tps;
tps = 0;
}
// Update objects independently (animations, etc)
for (Layer layer : currentFrame.getLayers()) {
if (!layer.isVisible()) { // "IsShow" flag
continue;
}
layer.tick(this);
}
getPlatformUtils().tick();
}
@Override
public void interpolate(float alpha) {
}
@Override
public void render(Graphics g) {
if (pauseError) {
return;
}
BitmapFont baseFont = g.getFont();
if (currentFrame == null) {
// Display loading logo
g.drawSprite(loadingLogo,
g.getCurrentWidth() / 2 - loadingLogo.getWidth() / 2,
g.getCurrentHeight() / 2 - loadingLogo.getHeight() / 2 - 100);
g.setFont(loadingFont);
g.setColor(Color.WHITE);
g.drawString(loadingText,
g.getCurrentWidth() / 2 - loadingTextWidth / 2,
g.getCurrentHeight() / 2 + loadingLogo.getHeight() / 2 + 10);
g.setFont(baseFont);
} else {
g.setColor(currentFrame.getBackground());
g.fillRect(0, 0, g.getCurrentWidth(), g.getCurrentHeight());
g.scale(g.getCurrentWidth() / ((float) app.getWindowWidth()),
g.getCurrentHeight() / ((float) app.getWindowHeight()));
float scaleX = g.getScaleX();
float scaleY = g.getScaleY();
currentFrame.draw(this, g);
g.scale(1f / g.getScaleX(), 1f / g.getScaleY());
g.setFont(baseFont);
g.setColor(Color.WHITE);
int mouseX = getMouseX();
int mouseY = getMouseY();
if (EscapistsRuntime.DEBUG) {
g.drawString("Mouse X: " + mouseX + ", Mouse Y: " + mouseY, 5, 35);
g.drawString("scaleX: " + scaleX + ", scaleY: " + scaleY, 5, 50);
g.drawString("Scene: " + currentFrame.getName(), 5, 65);
g.drawString("Instance count: " + currentFrame.getObjects().size(), 5, 80);
g.drawString("Event Handler implementation: " + currentFrame.eventTicker.getClass().getName(), 5, 95);
String layers = "";
Layer[] layersInScene = currentFrame.getLayers();
for (int i = 0; i < layersInScene.length; i++) {
Layer layer = layersInScene[i];
if (layer.isVisible()) {
if (layers.length() > 0) {
layers += ", ";
}
layers += i + " (" + layer.getName() + ")";
}
}
g.drawString("Visible layers: [" + layers + "]", 5, 110);
g.drawString("Active groups: [" + currentFrame.getActiveGroups() + "]", 5, 125);
}
}
if (EscapistsRuntime.DEBUG) {
int usedMem = (int) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024;
g.drawString("Escapists Runtime v" + EscapistsRuntime.VERSION + " on " +
Gdx.app.getType().name(), 5, 5);
g.drawString("FPS: " + Gdx.graphics.getFramesPerSecond() + ", TPS: " + lastTPS + ", Mem: "
+ usedMem + " MB", 5, 20);
}
}
public int getMouseX() {
return (int) (((float) Gdx.input.getX())
/ (((float) getWidth())
/ ((float) EscapistsRuntime.getRuntime().getApplication().getWindowWidth())));
}
public int getMouseY() {
return (int) (((float) Gdx.input.getY())
/ (((float) getHeight())
/ ((float) EscapistsRuntime.getRuntime().getApplication().getWindowHeight())));
}
public boolean isButtonClicked(int buttonId) {
return mouseClicked[buttonId] == 1;
}
public void setLoadingMessage(final String message) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
if (currentFrame != null) {
return;
}
// Recalculate message dimensions
loadingText = message;
loadingTextWidth = loadingFontCache.addText(loadingText, 0, 0).width;
}
});
}
public void fatalPrompt(final String msg) {
pauseError = true;
utils.showFatalMessageBox("Error", msg);
}
public void exit() {
utils.exit();
}
public PlatformUtils getPlatformUtils() {
return utils;
}
public void addMod(String name, String contents) {
mods.add(contents);
}
public AudioManager getAudio() {
return audio;
}
}
|
package edu.ucsf.lava.core.importer.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import edu.ucsf.lava.core.file.model.ImportFile;
import edu.ucsf.lava.core.model.EntityBase;
import edu.ucsf.lava.core.model.EntityManager;
public class ImportLog extends EntityBase {
public static EntityManager MANAGER = new EntityBase.Manager(ImportLog.class);
public static String ERROR_MSG = "ERROR";
public static String WARNING_MSG = "WARNING";
public static String INFO_MSG = "INFO";
public static String DEBUG_MSG = "DEBUG";
public static String CREATED_MSG = "CREATED";
private Timestamp importTimestamp;
private String importedBy;
private ImportFile dataFile;
private ImportDefinition definition;
private Integer totalRecords;
// record imported (generally means row inserted, though populating an "empty" record could
// qualify as an import instead of an update
private Integer imported;
// update to existing data, mutually exclusive with imported
private Integer updated;
// record already existed so no import or update
private Integer alreadyExist;
// record not imported due to an error
private Integer errors;
// record imported or updated, but with a warning
private Integer warnings;
private String notes; // entered by user when doing the import
private List<ImportLogMessage> messages = new ArrayList<ImportLogMessage>(); // warnings, errors
public ImportLog(){
super();
this.setAudited(false);
//this.setAuditEntityType("ImportLog");
this.totalRecords = 0;
this.imported = 0;
this.updated = 0;
this.alreadyExist = 0;
this.errors = 0;
this.warnings = 0;
this.importTimestamp = new Timestamp(new Date().getTime());
}
public Object[] getAssociationsToInitialize(String method) {
return new Object[]{this.definition};
}
public Timestamp getImportTimestamp() {
return importTimestamp;
}
public void setImportTimestamp(Timestamp importTimestamp) {
this.importTimestamp = importTimestamp;
}
public String getImportedBy() {
return importedBy;
}
public void setImportedBy(String importedBy) {
this.importedBy = importedBy;
}
public ImportFile getDataFile() {
return dataFile;
}
public void setDataFile(ImportFile dataFile) {
this.dataFile = dataFile;
}
public ImportDefinition getDefinition() {
return definition;
}
public void setDefinition(ImportDefinition definition) {
this.definition = definition;
}
public Integer getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(Integer totalRecords) {
this.totalRecords = totalRecords;
}
public Integer getImported() {
return imported;
}
public void setImported(Integer imported) {
this.imported = imported;
}
public Integer getAlreadyExist() {
return alreadyExist;
}
public Integer getUpdated() {
return updated;
}
public void setUpdated(Integer updated) {
this.updated = updated;
}
public void setAlreadyExist(Integer alreadyExist) {
this.alreadyExist = alreadyExist;
}
public Integer getErrors() {
return errors;
}
public void setErrors(Integer errors) {
this.errors = errors;
}
public Integer getWarnings() {
return warnings;
}
public void setWarnings(Integer warnings) {
this.warnings = warnings;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public List<ImportLogMessage> getMessages() {
return messages;
}
public void setMessages(List<ImportLogMessage> messages) {
this.messages = messages;
}
public void addMessage(String type, Integer lineNum, String msg) {
ImportLogMessage logMessage = new ImportLogMessage(type, lineNum, msg);
this.messages.add(logMessage);
}
public void addDebugMessage(Integer lineNum, String msg) {
this.addMessage(DEBUG_MSG, lineNum, msg);
}
public void addErrorMessage(Integer lineNum, String msg) {
this.addMessage(ERROR_MSG, lineNum, msg);
}
public void addWarningMessage(Integer lineNum, String msg) {
this.addMessage(WARNING_MSG, lineNum, msg);
}
public void addInfoMessage(Integer lineNum, String msg) {
this.addMessage(INFO_MSG, lineNum, msg);
}
public void addCreatedMessage(Integer lineNum, String msg) {
this.addMessage(CREATED_MSG, lineNum, msg);
}
public void incTotalRecords() {
this.totalRecords++;
}
public void incImported() {
this.imported++;
}
public void incUpdated() {
this.updated++;
}
public void incAlreadyExist() {
this.alreadyExist++;
}
public void incErrors() {
this.errors++;
}
public void incWarnings() {
this.warnings++;
}
public String getSummaryBlock() {
StringBuffer sb = new StringBuffer("Total=").append(this.getTotalRecords()).append(", ");
sb.append("Imported=").append(this.getImported()).append(", ");
sb.append("Updated=").append(this.getUpdated()).append("\n");
sb.append("Already Exists=").append(this.getAlreadyExist()).append(", ");
sb.append("Errors=").append(this.getErrors()).append(", ");
sb.append("Warnings=").append(this.getWarnings());
return sb.toString();
}
public static class ImportLogMessage implements Serializable {
private String type;
private Integer lineNum;
private String message;
public ImportLogMessage(){
super();
}
public ImportLogMessage(String type, Integer lineNum, String message) {
this.type = type;
this.lineNum = lineNum;
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getLineNum() {
return lineNum;
}
public void setLineNum(Integer lineNum) {
this.lineNum = lineNum;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
|
package org.joda.time;
import java.util.Locale;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* This class is a Junit unit test for DateTime.
*
* @author Stephen Colebourne
*/
public class TestDateTime_Properties extends TestCase {
// Test in 2002/03 as time zones are more well known
// (before the late 90's they were all over the place)
private static final DateTimeZone PARIS = DateTimeZone.getInstance("Europe/Paris");
private static final DateTimeZone LONDON = DateTimeZone.getInstance("Europe/London");
long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365;
long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365;
// 2002-06-09
private long TEST_TIME_NOW =
(y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
// 2002-04-05 Fri
private long TEST_TIME1 =
(y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 12L * DateTimeConstants.MILLIS_PER_HOUR
+ 24L * DateTimeConstants.MILLIS_PER_MINUTE;
// 2003-05-06 Tue
private long TEST_TIME2 =
(y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 14L * DateTimeConstants.MILLIS_PER_HOUR
+ 28L * DateTimeConstants.MILLIS_PER_MINUTE;
private DateTimeZone zone = null;
private Locale locale = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestDateTime_Properties.class);
}
public TestDateTime_Properties(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
zone = DateTimeZone.getDefault();
locale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
Locale.setDefault(Locale.UK);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(zone);
Locale.setDefault(locale);
zone = null;
}
public void testTest() {
assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString());
assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString());
assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString());
}
public void testPropertyGetEra() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().era(), test.era().getField());
assertEquals("era", test.era().getName());
assertEquals("Property[era]", test.era().toString());
assertSame(test, test.era().getDateTime());
assertEquals(1, test.era().get());
assertEquals("AD", test.era().getAsText());
assertEquals("ap. J.-C.", test.era().getAsText(Locale.FRENCH));
assertEquals("AD", test.era().getAsShortText());
assertEquals("ap. J.-C.", test.era().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().eras(), test.era().getDurationField());
assertEquals(null, test.era().getRangeDurationField());
assertEquals(2, test.era().getMaximumTextLength(null));
assertEquals(9, test.era().getMaximumTextLength(Locale.FRENCH));
assertEquals(2, test.era().getMaximumShortTextLength(null));
assertEquals(9, test.era().getMaximumShortTextLength(Locale.FRENCH));
}
public void testPropertyGetYearOfEra() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().yearOfEra(), test.yearOfEra().getField());
assertEquals("yearOfEra", test.yearOfEra().getName());
assertEquals("Property[yearOfEra]", test.yearOfEra().toString());
assertSame(test, test.yearOfEra().getDateTime());
assertEquals(2004, test.yearOfEra().get());
assertEquals("2004", test.yearOfEra().getAsText());
assertEquals("2004", test.yearOfEra().getAsText(Locale.FRENCH));
assertEquals("2004", test.yearOfEra().getAsShortText());
assertEquals("2004", test.yearOfEra().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().years(), test.yearOfEra().getDurationField());
assertEquals(null, test.yearOfEra().getRangeDurationField());
assertEquals(9, test.yearOfEra().getMaximumTextLength(null));
assertEquals(9, test.yearOfEra().getMaximumShortTextLength(null));
}
public void testPropertyGetCenturyOfEra() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().centuryOfEra(), test.centuryOfEra().getField());
assertEquals("centuryOfEra", test.centuryOfEra().getName());
assertEquals("Property[centuryOfEra]", test.centuryOfEra().toString());
assertSame(test, test.centuryOfEra().getDateTime());
assertEquals(20, test.centuryOfEra().get());
assertEquals("20", test.centuryOfEra().getAsText());
assertEquals("20", test.centuryOfEra().getAsText(Locale.FRENCH));
assertEquals("20", test.centuryOfEra().getAsShortText());
assertEquals("20", test.centuryOfEra().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().centuries(), test.centuryOfEra().getDurationField());
assertEquals(null, test.centuryOfEra().getRangeDurationField());
assertEquals(7, test.centuryOfEra().getMaximumTextLength(null));
assertEquals(7, test.centuryOfEra().getMaximumShortTextLength(null));
}
public void testPropertyGetYearOfCentury() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().yearOfCentury(), test.yearOfCentury().getField());
assertEquals("yearOfCentury", test.yearOfCentury().getName());
assertEquals("Property[yearOfCentury]", test.yearOfCentury().toString());
assertSame(test, test.yearOfCentury().getDateTime());
assertEquals(4, test.yearOfCentury().get());
assertEquals("4", test.yearOfCentury().getAsText());
assertEquals("4", test.yearOfCentury().getAsText(Locale.FRENCH));
assertEquals("4", test.yearOfCentury().getAsShortText());
assertEquals("4", test.yearOfCentury().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().years(), test.yearOfCentury().getDurationField());
assertEquals(test.getChronology().centuries(), test.yearOfCentury().getRangeDurationField());
assertEquals(2, test.yearOfCentury().getMaximumTextLength(null));
assertEquals(2, test.yearOfCentury().getMaximumShortTextLength(null));
}
public void testPropertyGetWeekyear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().weekyear(), test.weekyear().getField());
assertEquals("weekyear", test.weekyear().getName());
assertEquals("Property[weekyear]", test.weekyear().toString());
assertSame(test, test.weekyear().getDateTime());
assertEquals(2004, test.weekyear().get());
assertEquals("2004", test.weekyear().getAsText());
assertEquals("2004", test.weekyear().getAsText(Locale.FRENCH));
assertEquals("2004", test.weekyear().getAsShortText());
assertEquals("2004", test.weekyear().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().weekyears(), test.weekyear().getDurationField());
assertEquals(null, test.weekyear().getRangeDurationField());
assertEquals(9, test.weekyear().getMaximumTextLength(null));
assertEquals(9, test.weekyear().getMaximumShortTextLength(null));
}
public void testPropertyGetYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().year(), test.year().getField());
assertEquals("year", test.year().getName());
assertEquals("Property[year]", test.year().toString());
assertSame(test, test.year().getDateTime());
assertEquals(2004, test.year().get());
assertEquals("2004", test.year().getAsText());
assertEquals("2004", test.year().getAsText(Locale.FRENCH));
assertEquals("2004", test.year().getAsShortText());
assertEquals("2004", test.year().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().years(), test.year().getDurationField());
assertEquals(null, test.year().getRangeDurationField());
assertEquals(9, test.year().getMaximumTextLength(null));
assertEquals(9, test.year().getMaximumShortTextLength(null));
assertEquals(-292275054, test.year().getMinimumValue());
assertEquals(-292275054, test.year().getMinimumValueOverall());
assertEquals(292277023, test.year().getMaximumValue());
assertEquals(292277023, test.year().getMaximumValueOverall());
}
public void testPropertyLeapYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertEquals(true, test.year().isLeap());
assertEquals(1, test.year().getLeapAmount());
assertEquals(test.getChronology().days(), test.year().getLeapDurationField());
test = new DateTime(2003, 6, 9, 0, 0, 0, 0);
assertEquals(false, test.year().isLeap());
assertEquals(0, test.year().getLeapAmount());
assertEquals(test.getChronology().days(), test.year().getLeapDurationField());
}
public void testPropertyAddYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.year().addToCopy(9);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2013-06-09T00:00:00.000+01:00", copy.toString());
copy = test.year().addToCopy(0);
assertEquals("2004-06-09T00:00:00.000+01:00", copy.toString());
copy = test.year().addToCopy(292277023 - 2004);
assertEquals(292277023, copy.getYear());
try {
test.year().addToCopy(292277023 - 2004 + 1);
fail();
} catch (IllegalArgumentException ex) {}
copy = test.year().addToCopy(-2004);
assertEquals(0, copy.getYear());
copy = test.year().addToCopy(-2005);
assertEquals(-1, copy.getYear());
try {
test.year().addToCopy(-292275054 - 2004 - 1);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyAddWrapFieldYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.year().addWrapFieldToCopy(9);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2013-06-09T00:00:00.000+01:00", copy.toString());
copy = test.year().addWrapFieldToCopy(0);
assertEquals(2004, copy.getYear());
copy = test.year().addWrapFieldToCopy(292277023 - 2004 + 1);
assertEquals(-292275054, copy.getYear());
copy = test.year().addWrapFieldToCopy(-292275054 - 2004 - 1);
assertEquals(292277023, copy.getYear());
}
public void testPropertySetYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.year().setCopy(1960);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("1960-06-09T00:00:00.000+01:00", copy.toString());
}
public void testPropertySetTextYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.year().setCopy("1960");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("1960-06-09T00:00:00.000+01:00", copy.toString());
}
public void testPropertyCompareToYear() {
DateTime test1 = new DateTime(TEST_TIME1);
DateTime test2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.year().compareTo(test2) < 0);
assertEquals(true, test2.year().compareTo(test1) > 0);
assertEquals(true, test1.year().compareTo(test1) == 0);
try {
test1.year().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyCompareToYear2() {
DateTime test1 = new DateTime(2004, 6, 9, 0, 0, 0, 0);
YearMonthDay ymd1 = new YearMonthDay(2003, 6, 9);
YearMonthDay ymd2 = new YearMonthDay(2004, 6, 9);
YearMonthDay ymd3 = new YearMonthDay(2005, 6, 9);
assertEquals(true, test1.year().compareTo(ymd1) > 0);
assertEquals(true, test1.year().compareTo(ymd2) == 0);
assertEquals(true, test1.year().compareTo(ymd3) < 0);
try {
test1.year().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyEqualsHashCodeYear() {
DateTime test1 = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertEquals(true, test1.year().equals(test1.year()));
assertEquals(true, test1.year().equals(new DateTime(2004, 6, 9, 0, 0, 0, 0).year()));
assertEquals(false, test1.year().equals(new DateTime(2004, 6, 9, 0, 0, 0, 0).monthOfYear()));
assertEquals(false, test1.year().equals(new DateTime(2004, 6, 9, 0, 0, 0, 0, Chronology.getCoptic()).year()));
assertEquals(true, test1.year().hashCode() == test1.year().hashCode());
assertEquals(true, test1.year().hashCode() == new DateTime(2004, 6, 9, 0, 0, 0, 0).year().hashCode());
assertEquals(false, test1.year().hashCode() == new DateTime(2004, 6, 9, 0, 0, 0, 0).monthOfYear().hashCode());
assertEquals(false, test1.year().hashCode() == new DateTime(2004, 6, 9, 0, 0, 0, 0, Chronology.getCoptic()).year().hashCode());
}
public void testPropertyGetMonthOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField());
assertEquals("monthOfYear", test.monthOfYear().getName());
assertEquals("Property[monthOfYear]", test.monthOfYear().toString());
assertSame(test, test.monthOfYear().getDateTime());
assertEquals(6, test.monthOfYear().get());
assertEquals("June", test.monthOfYear().getAsText());
assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH));
assertEquals("Jun", test.monthOfYear().getAsShortText());
assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField());
assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField());
assertEquals(9, test.monthOfYear().getMaximumTextLength(null));
assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null));
test = new DateTime(2004, 7, 9, 0, 0, 0, 0);
assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH));
assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH));
assertEquals(1, test.monthOfYear().getMinimumValue());
assertEquals(1, test.monthOfYear().getMinimumValueOverall());
assertEquals(12, test.monthOfYear().getMaximumValue());
assertEquals(12, test.monthOfYear().getMaximumValueOverall());
assertEquals(1, test.monthOfYear().getMinimumValue());
assertEquals(1, test.monthOfYear().getMinimumValueOverall());
assertEquals(12, test.monthOfYear().getMaximumValue());
assertEquals(12, test.monthOfYear().getMaximumValueOverall());
}
public void testPropertyLeapMonthOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertEquals(false, test.monthOfYear().isLeap());
assertEquals(0, test.monthOfYear().getLeapAmount());
assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField());
test = new DateTime(2004, 2, 9, 0, 0, 0, 0);
assertEquals(true, test.monthOfYear().isLeap());
assertEquals(1, test.monthOfYear().getLeapAmount());
assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField());
test = new DateTime(2003, 6, 9, 0, 0, 0, 0);
assertEquals(false, test.monthOfYear().isLeap());
assertEquals(0, test.monthOfYear().getLeapAmount());
assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField());
test = new DateTime(2003, 2, 9, 0, 0, 0, 0);
assertEquals(false, test.monthOfYear().isLeap());
assertEquals(0, test.monthOfYear().getLeapAmount());
assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField());
}
public void testPropertyAddMonthOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.monthOfYear().addToCopy(6);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-12-09T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().addToCopy(7);
assertEquals("2005-01-09T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().addToCopy(-5);
assertEquals("2004-01-09T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().addToCopy(-6);
assertEquals("2003-12-09T00:00:00.000Z", copy.toString());
test = new DateTime(2004, 1, 31, 0, 0, 0, 0);
copy = test.monthOfYear().addToCopy(1);
assertEquals("2004-01-31T00:00:00.000Z", test.toString());
assertEquals("2004-02-29T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().addToCopy(2);
assertEquals("2004-03-31T00:00:00.000+01:00", copy.toString());
copy = test.monthOfYear().addToCopy(3);
assertEquals("2004-04-30T00:00:00.000+01:00", copy.toString());
test = new DateTime(2003, 1, 31, 0, 0, 0, 0);
copy = test.monthOfYear().addToCopy(1);
assertEquals("2003-02-28T00:00:00.000Z", copy.toString());
}
public void testPropertyAddWrapFieldMonthOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.monthOfYear().addWrapFieldToCopy(4);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-10-09T00:00:00.000+01:00", copy.toString());
copy = test.monthOfYear().addWrapFieldToCopy(8);
assertEquals("2004-02-09T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().addWrapFieldToCopy(-8);
assertEquals("2004-10-09T00:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 1, 31, 0, 0, 0, 0);
copy = test.monthOfYear().addWrapFieldToCopy(1);
assertEquals("2004-01-31T00:00:00.000Z", test.toString());
assertEquals("2004-02-29T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().addWrapFieldToCopy(2);
assertEquals("2004-03-31T00:00:00.000+01:00", copy.toString());
copy = test.monthOfYear().addWrapFieldToCopy(3);
assertEquals("2004-04-30T00:00:00.000+01:00", copy.toString());
test = new DateTime(2005, 1, 31, 0, 0, 0, 0);
copy = test.monthOfYear().addWrapFieldToCopy(1);
assertEquals("2005-01-31T00:00:00.000Z", test.toString());
assertEquals("2005-02-28T00:00:00.000Z", copy.toString());
}
public void testPropertySetMonthOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.monthOfYear().setCopy(12);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-12-09T00:00:00.000Z", copy.toString());
test = new DateTime(2004, 1, 31, 0, 0, 0, 0);
copy = test.monthOfYear().setCopy(2);
assertEquals("2004-02-29T00:00:00.000Z", copy.toString());
try {
test.monthOfYear().setCopy(13);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.monthOfYear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertySetTextMonthOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.monthOfYear().setCopy("12");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-12-09T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().setCopy("December");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-12-09T00:00:00.000Z", copy.toString());
copy = test.monthOfYear().setCopy("Dec");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-12-09T00:00:00.000Z", copy.toString());
}
public void testPropertyCompareToMonthOfYear() {
DateTime test1 = new DateTime(TEST_TIME1);
DateTime test2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.monthOfYear().compareTo(test2) < 0);
assertEquals(true, test2.monthOfYear().compareTo(test1) > 0);
assertEquals(true, test1.monthOfYear().compareTo(test1) == 0);
try {
test1.monthOfYear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0);
assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0);
assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0);
try {
test1.monthOfYear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyGetDayOfMonth() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField());
assertEquals("dayOfMonth", test.dayOfMonth().getName());
assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString());
assertSame(test, test.dayOfMonth().getDateTime());
assertEquals(9, test.dayOfMonth().get());
assertEquals("9", test.dayOfMonth().getAsText());
assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH));
assertEquals("9", test.dayOfMonth().getAsShortText());
assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField());
assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField());
assertEquals(2, test.dayOfMonth().getMaximumTextLength(null));
assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null));
assertEquals(1, test.dayOfMonth().getMinimumValue());
assertEquals(1, test.dayOfMonth().getMinimumValueOverall());
assertEquals(30, test.dayOfMonth().getMaximumValue());
assertEquals(31, test.dayOfMonth().getMaximumValueOverall());
assertEquals(false, test.dayOfMonth().isLeap());
assertEquals(0, test.dayOfMonth().getLeapAmount());
assertEquals(null, test.dayOfMonth().getLeapDurationField());
}
public void testPropertyGetMaxMinValuesDayOfMonth() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertEquals(1, test.dayOfMonth().getMinimumValue());
assertEquals(1, test.dayOfMonth().getMinimumValueOverall());
assertEquals(30, test.dayOfMonth().getMaximumValue());
assertEquals(31, test.dayOfMonth().getMaximumValueOverall());
test = new DateTime(2004, 7, 9, 0, 0, 0, 0);
assertEquals(31, test.dayOfMonth().getMaximumValue());
test = new DateTime(2004, 2, 9, 0, 0, 0, 0);
assertEquals(29, test.dayOfMonth().getMaximumValue());
test = new DateTime(2003, 2, 9, 0, 0, 0, 0);
assertEquals(28, test.dayOfMonth().getMaximumValue());
}
public void testPropertyAddDayOfMonth() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfMonth().addToCopy(9);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-18T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(21);
assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(22);
assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(22 + 30);
assertEquals("2004-07-31T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(22 + 31);
assertEquals("2004-08-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31);
assertEquals("2004-12-31T00:00:00.000Z", copy.toString());
copy = test.dayOfMonth().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31);
assertEquals("2005-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfMonth().addToCopy(-8);
assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(-9);
assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addToCopy(-8 - 31 - 30 - 31 - 29 - 31);
assertEquals("2004-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfMonth().addToCopy(-9 - 31 - 30 - 31 - 29 - 31);
assertEquals("2003-12-31T00:00:00.000Z", copy.toString());
}
public void testPropertyAddWrapFieldDayOfMonth() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfMonth().addWrapFieldToCopy(21);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addWrapFieldToCopy(22);
assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addWrapFieldToCopy(-12);
assertEquals("2004-06-27T00:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 7, 9, 0, 0, 0, 0);
copy = test.dayOfMonth().addWrapFieldToCopy(21);
assertEquals("2004-07-30T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addWrapFieldToCopy(22);
assertEquals("2004-07-31T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addWrapFieldToCopy(23);
assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfMonth().addWrapFieldToCopy(-12);
assertEquals("2004-07-28T00:00:00.000+01:00", copy.toString());
}
public void testPropertySetDayOfMonth() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfMonth().setCopy(12);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-12T00:00:00.000+01:00", copy.toString());
try {
test.dayOfMonth().setCopy(31);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.dayOfMonth().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertySetTextDayOfMonth() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfMonth().setCopy("12");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-12T00:00:00.000+01:00", copy.toString());
}
public void testPropertyCompareToDayOfMonth() {
DateTime test1 = new DateTime(TEST_TIME1);
DateTime test2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0);
assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0);
assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0);
try {
test1.dayOfMonth().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0);
assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0);
assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0);
try {
test1.dayOfMonth().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyGetDayOfYear() {
// 31+29+31+30+31+9 = 161
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().dayOfYear(), test.dayOfYear().getField());
assertEquals("dayOfYear", test.dayOfYear().getName());
assertEquals("Property[dayOfYear]", test.dayOfYear().toString());
assertSame(test, test.dayOfYear().getDateTime());
assertEquals(161, test.dayOfYear().get());
assertEquals("161", test.dayOfYear().getAsText());
assertEquals("161", test.dayOfYear().getAsText(Locale.FRENCH));
assertEquals("161", test.dayOfYear().getAsShortText());
assertEquals("161", test.dayOfYear().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().days(), test.dayOfYear().getDurationField());
assertEquals(test.getChronology().years(), test.dayOfYear().getRangeDurationField());
assertEquals(3, test.dayOfYear().getMaximumTextLength(null));
assertEquals(3, test.dayOfYear().getMaximumShortTextLength(null));
assertEquals(false, test.dayOfYear().isLeap());
assertEquals(0, test.dayOfYear().getLeapAmount());
assertEquals(null, test.dayOfYear().getLeapDurationField());
}
public void testPropertyGetMaxMinValuesDayOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertEquals(1, test.dayOfYear().getMinimumValue());
assertEquals(1, test.dayOfYear().getMinimumValueOverall());
assertEquals(366, test.dayOfYear().getMaximumValue());
assertEquals(366, test.dayOfYear().getMaximumValueOverall());
test = new DateTime(2002, 6, 9, 0, 0, 0, 0);
assertEquals(365, test.dayOfYear().getMaximumValue());
assertEquals(366, test.dayOfYear().getMaximumValueOverall());
}
public void testPropertyAddDayOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfYear().addToCopy(9);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-18T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addToCopy(21);
assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addToCopy(22);
assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31);
assertEquals("2004-12-31T00:00:00.000Z", copy.toString());
copy = test.dayOfYear().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31);
assertEquals("2005-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfYear().addToCopy(-8);
assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addToCopy(-9);
assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addToCopy(-8 - 31 - 30 - 31 - 29 - 31);
assertEquals("2004-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfYear().addToCopy(-9 - 31 - 30 - 31 - 29 - 31);
assertEquals("2003-12-31T00:00:00.000Z", copy.toString());
}
public void testPropertyAddWrapFieldDayOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfYear().addWrapFieldToCopy(21);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addWrapFieldToCopy(22);
assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addWrapFieldToCopy(-12);
assertEquals("2004-05-28T00:00:00.000+01:00", copy.toString());
copy = test.dayOfYear().addWrapFieldToCopy(205);
assertEquals("2004-12-31T00:00:00.000Z", copy.toString());
copy = test.dayOfYear().addWrapFieldToCopy(206);
assertEquals("2004-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfYear().addWrapFieldToCopy(-160);
assertEquals("2004-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfYear().addWrapFieldToCopy(-161);
assertEquals("2004-12-31T00:00:00.000Z", copy.toString());
}
public void testPropertySetDayOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfYear().setCopy(12);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-01-12T00:00:00.000Z", copy.toString());
try {
test.dayOfYear().setCopy(367);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.dayOfYear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertySetTextDayOfYear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfYear().setCopy("12");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-01-12T00:00:00.000Z", copy.toString());
}
public void testPropertyCompareToDayOfYear() {
DateTime test1 = new DateTime(TEST_TIME1);
DateTime test2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.dayOfYear().compareTo(test2) < 0);
assertEquals(true, test2.dayOfYear().compareTo(test1) > 0);
assertEquals(true, test1.dayOfYear().compareTo(test1) == 0);
try {
test1.dayOfYear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.dayOfYear().compareTo(dt2) < 0);
assertEquals(true, test2.dayOfYear().compareTo(dt1) > 0);
assertEquals(true, test1.dayOfYear().compareTo(dt1) == 0);
try {
test1.dayOfYear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyGetWeekOfWeekyear() {
// 2002-01-01 = Thu
// 2002-12-31 = Thu (+364 days)
// 2003-12-30 = Thu (+364 days)
// 2004-01-03 = Mon W1
// 2004-01-31 = Mon (+28 days) W5
// 2004-02-28 = Mon (+28 days) W9
// 2004-03-27 = Mon (+28 days) W13
// 2004-04-24 = Mon (+28 days) W17
// 2004-05-23 = Mon (+28 days) W21
// 2004-06-05 = Mon (+14 days) W23
// 2004-06-09 = Fri
// 2004-12-25 = Mon W52
// 2005-01-01 = Mon W1
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().weekOfWeekyear(), test.weekOfWeekyear().getField());
assertEquals("weekOfWeekyear", test.weekOfWeekyear().getName());
assertEquals("Property[weekOfWeekyear]", test.weekOfWeekyear().toString());
assertSame(test, test.weekOfWeekyear().getDateTime());
assertEquals(24, test.weekOfWeekyear().get());
assertEquals("24", test.weekOfWeekyear().getAsText());
assertEquals("24", test.weekOfWeekyear().getAsText(Locale.FRENCH));
assertEquals("24", test.weekOfWeekyear().getAsShortText());
assertEquals("24", test.weekOfWeekyear().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().weeks(), test.weekOfWeekyear().getDurationField());
assertEquals(test.getChronology().weekyears(), test.weekOfWeekyear().getRangeDurationField());
assertEquals(2, test.weekOfWeekyear().getMaximumTextLength(null));
assertEquals(2, test.weekOfWeekyear().getMaximumShortTextLength(null));
assertEquals(false, test.weekOfWeekyear().isLeap());
assertEquals(0, test.weekOfWeekyear().getLeapAmount());
assertEquals(null, test.weekOfWeekyear().getLeapDurationField());
}
public void testPropertyGetMaxMinValuesWeekOfWeekyear() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertEquals(1, test.weekOfWeekyear().getMinimumValue());
assertEquals(1, test.weekOfWeekyear().getMinimumValueOverall());
assertEquals(53, test.weekOfWeekyear().getMaximumValue());
assertEquals(53, test.weekOfWeekyear().getMaximumValueOverall());
test = new DateTime(2005, 6, 9, 0, 0, 0, 0);
assertEquals(52, test.weekOfWeekyear().getMaximumValue());
assertEquals(53, test.weekOfWeekyear().getMaximumValueOverall());
}
public void testPropertyAddWeekOfWeekyear() {
DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0);
DateTime copy = test.weekOfWeekyear().addToCopy(1);
assertEquals("2004-06-07T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-14T00:00:00.000+01:00", copy.toString());
copy = test.weekOfWeekyear().addToCopy(29);
assertEquals("2004-12-27T00:00:00.000Z", copy.toString());
copy = test.weekOfWeekyear().addToCopy(30);
assertEquals("2005-01-03T00:00:00.000Z", copy.toString());
copy = test.weekOfWeekyear().addToCopy(-22);
assertEquals("2004-01-05T00:00:00.000Z", copy.toString());
copy = test.weekOfWeekyear().addToCopy(-23);
assertEquals("2003-12-29T00:00:00.000Z", copy.toString());
}
public void testPropertyAddWrapFieldWeekOfWeekyear() {
DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0);
DateTime copy = test.weekOfWeekyear().addWrapFieldToCopy(1);
assertEquals("2004-06-07T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-14T00:00:00.000+01:00", copy.toString());
copy = test.weekOfWeekyear().addWrapFieldToCopy(29);
assertEquals("2004-12-27T00:00:00.000Z", copy.toString());
copy = test.weekOfWeekyear().addWrapFieldToCopy(30);
assertEquals("2003-12-29T00:00:00.000Z", copy.toString());
copy = test.weekOfWeekyear().addWrapFieldToCopy(-23);
assertEquals("2003-12-29T00:00:00.000Z", copy.toString());
}
public void testPropertySetWeekOfWeekyear() {
DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0);
DateTime copy = test.weekOfWeekyear().setCopy(4);
assertEquals("2004-06-07T00:00:00.000+01:00", test.toString());
assertEquals("2004-01-19T00:00:00.000Z", copy.toString());
try {
test.weekOfWeekyear().setCopy(54);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.weekOfWeekyear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertySetTextWeekOfWeekyear() {
DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0);
DateTime copy = test.weekOfWeekyear().setCopy("4");
assertEquals("2004-06-07T00:00:00.000+01:00", test.toString());
assertEquals("2004-01-19T00:00:00.000Z", copy.toString());
}
public void testPropertyCompareToWeekOfWeekyear() {
DateTime test1 = new DateTime(TEST_TIME1);
DateTime test2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.weekOfWeekyear().compareTo(test2) < 0);
assertEquals(true, test2.weekOfWeekyear().compareTo(test1) > 0);
assertEquals(true, test1.weekOfWeekyear().compareTo(test1) == 0);
try {
test1.weekOfWeekyear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.weekOfWeekyear().compareTo(dt2) < 0);
assertEquals(true, test2.weekOfWeekyear().compareTo(dt1) > 0);
assertEquals(true, test1.weekOfWeekyear().compareTo(dt1) == 0);
try {
test1.weekOfWeekyear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyGetDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
assertSame(test.getChronology().dayOfWeek(), test.dayOfWeek().getField());
assertEquals("dayOfWeek", test.dayOfWeek().getName());
assertEquals("Property[dayOfWeek]", test.dayOfWeek().toString());
assertSame(test, test.dayOfWeek().getDateTime());
assertEquals(3, test.dayOfWeek().get());
assertEquals("Wednesday", test.dayOfWeek().getAsText());
assertEquals("mercredi", test.dayOfWeek().getAsText(Locale.FRENCH));
assertEquals("Wed", test.dayOfWeek().getAsShortText());
assertEquals("mer.", test.dayOfWeek().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().days(), test.dayOfWeek().getDurationField());
assertEquals(test.getChronology().weeks(), test.dayOfWeek().getRangeDurationField());
assertEquals(9, test.dayOfWeek().getMaximumTextLength(null));
assertEquals(8, test.dayOfWeek().getMaximumTextLength(Locale.FRENCH));
assertEquals(3, test.dayOfWeek().getMaximumShortTextLength(null));
assertEquals(4, test.dayOfWeek().getMaximumShortTextLength(Locale.FRENCH));
assertEquals(1, test.dayOfWeek().getMinimumValue());
assertEquals(1, test.dayOfWeek().getMinimumValueOverall());
assertEquals(7, test.dayOfWeek().getMaximumValue());
assertEquals(7, test.dayOfWeek().getMaximumValueOverall());
assertEquals(false, test.dayOfWeek().isLeap());
assertEquals(0, test.dayOfWeek().getLeapAmount());
assertEquals(null, test.dayOfWeek().getLeapDurationField());
}
public void testPropertyAddDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfWeek().addToCopy(1);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addToCopy(21);
assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addToCopy(22);
assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31);
assertEquals("2004-12-31T00:00:00.000Z", copy.toString());
copy = test.dayOfWeek().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31);
assertEquals("2005-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfWeek().addToCopy(-8);
assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addToCopy(-9);
assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addToCopy(-8 - 31 - 30 - 31 - 29 - 31);
assertEquals("2004-01-01T00:00:00.000Z", copy.toString());
copy = test.dayOfWeek().addToCopy(-9 - 31 - 30 - 31 - 29 - 31);
assertEquals("2003-12-31T00:00:00.000Z", copy.toString());
}
public void testPropertyAddLongDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfWeek().addToCopy(1L);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString());
}
public void testPropertyAddWrapFieldDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); // Wed
DateTime copy = test.dayOfWeek().addWrapFieldToCopy(1);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addWrapFieldToCopy(5);
assertEquals("2004-06-07T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().addWrapFieldToCopy(-10);
assertEquals("2004-06-13T00:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 2, 0, 0, 0, 0);
copy = test.dayOfWeek().addWrapFieldToCopy(5);
assertEquals("2004-06-02T00:00:00.000+01:00", test.toString());
assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString());
}
public void testPropertySetDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfWeek().setCopy(4);
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString());
try {
test.dayOfWeek().setCopy(8);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.dayOfWeek().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertySetTextDayOfWeek() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
DateTime copy = test.dayOfWeek().setCopy("4");
assertEquals("2004-06-09T00:00:00.000+01:00", test.toString());
assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().setCopy("Mon");
assertEquals("2004-06-07T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().setCopy("Tuesday");
assertEquals("2004-06-08T00:00:00.000+01:00", copy.toString());
copy = test.dayOfWeek().setCopy("lundi", Locale.FRENCH);
assertEquals("2004-06-07T00:00:00.000+01:00", copy.toString());
}
public void testPropertyCompareToDayOfWeek() {
DateTime test1 = new DateTime(TEST_TIME1);
DateTime test2 = new DateTime(TEST_TIME2);
assertEquals(true, test2.dayOfWeek().compareTo(test1) < 0);
assertEquals(true, test1.dayOfWeek().compareTo(test2) > 0);
assertEquals(true, test1.dayOfWeek().compareTo(test1) == 0);
try {
test1.dayOfWeek().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test2.dayOfWeek().compareTo(dt1) < 0);
assertEquals(true, test1.dayOfWeek().compareTo(dt2) > 0);
assertEquals(true, test1.dayOfWeek().compareTo(dt1) == 0);
try {
test1.dayOfWeek().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertyGetHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().hourOfDay(), test.hourOfDay().getField());
assertEquals("hourOfDay", test.hourOfDay().getName());
assertEquals("Property[hourOfDay]", test.hourOfDay().toString());
assertSame(test, test.hourOfDay().getDateTime());
assertEquals(13, test.hourOfDay().get());
assertEquals("13", test.hourOfDay().getAsText());
assertEquals("13", test.hourOfDay().getAsText(Locale.FRENCH));
assertEquals("13", test.hourOfDay().getAsShortText());
assertEquals("13", test.hourOfDay().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().hours(), test.hourOfDay().getDurationField());
assertEquals(test.getChronology().days(), test.hourOfDay().getRangeDurationField());
assertEquals(2, test.hourOfDay().getMaximumTextLength(null));
assertEquals(2, test.hourOfDay().getMaximumShortTextLength(null));
}
public void testPropertyGetDifferenceHourOfDay() {
DateTime test1 = new DateTime(2004, 6, 9, 13, 30, 0, 0);
DateTime test2 = new DateTime(2004, 6, 9, 15, 30, 0, 0);
assertEquals(-2, test1.hourOfDay().getDifference(test2));
assertEquals(2, test2.hourOfDay().getDifference(test1));
assertEquals(-2L, test1.hourOfDay().getDifferenceAsLong(test2));
assertEquals(2L, test2.hourOfDay().getDifferenceAsLong(test1));
DateTime test = new DateTime(TEST_TIME_NOW + (13L * DateTimeConstants.MILLIS_PER_HOUR));
assertEquals(13, test.hourOfDay().getDifference(null));
assertEquals(13L, test.hourOfDay().getDifferenceAsLong(null));
}
public void testPropertyRoundFloorHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0);
DateTime copy = test.hourOfDay().roundFloorCopy();
assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString());
}
public void testPropertyRoundCeilingHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0);
DateTime copy = test.hourOfDay().roundCeilingCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
}
public void testPropertyRoundHalfFloorHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0);
DateTime copy = test.hourOfDay().roundHalfFloorCopy();
assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 13, 30, 0, 1);
copy = test.hourOfDay().roundHalfFloorCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 13, 29, 59, 999);
copy = test.hourOfDay().roundHalfFloorCopy();
assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString());
}
public void testPropertyRoundHalfCeilingHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0);
DateTime copy = test.hourOfDay().roundHalfCeilingCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 13, 30, 0, 1);
copy = test.hourOfDay().roundHalfCeilingCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 13, 29, 59, 999);
copy = test.hourOfDay().roundHalfCeilingCopy();
assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString());
}
public void testPropertyRoundHalfEvenHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0);
DateTime copy = test.hourOfDay().roundHalfEvenCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 14, 30, 0, 0);
copy = test.hourOfDay().roundHalfEvenCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 13, 30, 0, 1);
copy = test.hourOfDay().roundHalfEvenCopy();
assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString());
test = new DateTime(2004, 6, 9, 13, 29, 59, 999);
copy = test.hourOfDay().roundHalfEvenCopy();
assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString());
}
public void testPropertyRemainderHourOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0);
assertEquals(30L * DateTimeConstants.MILLIS_PER_MINUTE, test.hourOfDay().remainder());
}
public void testPropertyGetMinuteOfHour() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().minuteOfHour(), test.minuteOfHour().getField());
assertEquals("minuteOfHour", test.minuteOfHour().getName());
assertEquals("Property[minuteOfHour]", test.minuteOfHour().toString());
assertSame(test, test.minuteOfHour().getDateTime());
assertEquals(23, test.minuteOfHour().get());
assertEquals("23", test.minuteOfHour().getAsText());
assertEquals("23", test.minuteOfHour().getAsText(Locale.FRENCH));
assertEquals("23", test.minuteOfHour().getAsShortText());
assertEquals("23", test.minuteOfHour().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().minutes(), test.minuteOfHour().getDurationField());
assertEquals(test.getChronology().hours(), test.minuteOfHour().getRangeDurationField());
assertEquals(2, test.minuteOfHour().getMaximumTextLength(null));
assertEquals(2, test.minuteOfHour().getMaximumShortTextLength(null));
}
public void testPropertyGetMinuteOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().minuteOfDay(), test.minuteOfDay().getField());
assertEquals("minuteOfDay", test.minuteOfDay().getName());
assertEquals("Property[minuteOfDay]", test.minuteOfDay().toString());
assertSame(test, test.minuteOfDay().getDateTime());
assertEquals(803, test.minuteOfDay().get());
assertEquals("803", test.minuteOfDay().getAsText());
assertEquals("803", test.minuteOfDay().getAsText(Locale.FRENCH));
assertEquals("803", test.minuteOfDay().getAsShortText());
assertEquals("803", test.minuteOfDay().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().minutes(), test.minuteOfDay().getDurationField());
assertEquals(test.getChronology().days(), test.minuteOfDay().getRangeDurationField());
assertEquals(4, test.minuteOfDay().getMaximumTextLength(null));
assertEquals(4, test.minuteOfDay().getMaximumShortTextLength(null));
}
public void testPropertyGetSecondOfMinute() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().secondOfMinute(), test.secondOfMinute().getField());
assertEquals("secondOfMinute", test.secondOfMinute().getName());
assertEquals("Property[secondOfMinute]", test.secondOfMinute().toString());
assertSame(test, test.secondOfMinute().getDateTime());
assertEquals(43, test.secondOfMinute().get());
assertEquals("43", test.secondOfMinute().getAsText());
assertEquals("43", test.secondOfMinute().getAsText(Locale.FRENCH));
assertEquals("43", test.secondOfMinute().getAsShortText());
assertEquals("43", test.secondOfMinute().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().seconds(), test.secondOfMinute().getDurationField());
assertEquals(test.getChronology().minutes(), test.secondOfMinute().getRangeDurationField());
assertEquals(2, test.secondOfMinute().getMaximumTextLength(null));
assertEquals(2, test.secondOfMinute().getMaximumShortTextLength(null));
}
public void testPropertyGetSecondOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().secondOfDay(), test.secondOfDay().getField());
assertEquals("secondOfDay", test.secondOfDay().getName());
assertEquals("Property[secondOfDay]", test.secondOfDay().toString());
assertSame(test, test.secondOfDay().getDateTime());
assertEquals(48223, test.secondOfDay().get());
assertEquals("48223", test.secondOfDay().getAsText());
assertEquals("48223", test.secondOfDay().getAsText(Locale.FRENCH));
assertEquals("48223", test.secondOfDay().getAsShortText());
assertEquals("48223", test.secondOfDay().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().seconds(), test.secondOfDay().getDurationField());
assertEquals(test.getChronology().days(), test.secondOfDay().getRangeDurationField());
assertEquals(5, test.secondOfDay().getMaximumTextLength(null));
assertEquals(5, test.secondOfDay().getMaximumShortTextLength(null));
}
public void testPropertyGetMillisOfSecond() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().millisOfSecond(), test.millisOfSecond().getField());
assertEquals("millisOfSecond", test.millisOfSecond().getName());
assertEquals("Property[millisOfSecond]", test.millisOfSecond().toString());
assertSame(test, test.millisOfSecond().getDateTime());
assertEquals(53, test.millisOfSecond().get());
assertEquals("53", test.millisOfSecond().getAsText());
assertEquals("53", test.millisOfSecond().getAsText(Locale.FRENCH));
assertEquals("53", test.millisOfSecond().getAsShortText());
assertEquals("53", test.millisOfSecond().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().millis(), test.millisOfSecond().getDurationField());
assertEquals(test.getChronology().seconds(), test.millisOfSecond().getRangeDurationField());
assertEquals(3, test.millisOfSecond().getMaximumTextLength(null));
assertEquals(3, test.millisOfSecond().getMaximumShortTextLength(null));
}
public void testPropertyGetMillisOfDay() {
DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53);
assertSame(test.getChronology().millisOfDay(), test.millisOfDay().getField());
assertEquals("millisOfDay", test.millisOfDay().getName());
assertEquals("Property[millisOfDay]", test.millisOfDay().toString());
assertSame(test, test.millisOfDay().getDateTime());
assertEquals(48223053, test.millisOfDay().get());
assertEquals("48223053", test.millisOfDay().getAsText());
assertEquals("48223053", test.millisOfDay().getAsText(Locale.FRENCH));
assertEquals("48223053", test.millisOfDay().getAsShortText());
assertEquals("48223053", test.millisOfDay().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().millis(), test.millisOfDay().getDurationField());
assertEquals(test.getChronology().days(), test.millisOfDay().getRangeDurationField());
assertEquals(8, test.millisOfDay().getMaximumTextLength(null));
assertEquals(8, test.millisOfDay().getMaximumShortTextLength(null));
}
}
|
package org.bouncycastle.asn1.x509;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
/**
* The KeyPurposeId object.
* <pre>
* KeyPurposeId ::= OBJECT IDENTIFIER
*
* id-kp ::= OBJECT IDENTIFIER { iso(1) identified-organization(3)
* dod(6) internet(1) security(5) mechanisms(5) pkix(7) 3}
*
* </pre>
* To create a new KeyPurposeId where none of the below suit, use
* <pre>
* ASN1ObjectIdentifier newKeyPurposeIdOID = new ASN1ObjectIdentifier("1.3.6.1...");
*
* KeyPurposeId newKeyPurposeId = KeyPurposeId.getInstance(newKeyPurposeIdOID);
* </pre>
*/
public class KeyPurposeId
extends ASN1Object
{
private static final ASN1ObjectIdentifier id_kp = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.3");
/**
* { 2 5 29 37 0 }
*/
public static final KeyPurposeId anyExtendedKeyUsage = new KeyPurposeId(Extension.extendedKeyUsage.branch("0"));
/**
* { id-kp 1 }
*/
public static final KeyPurposeId id_kp_serverAuth = new KeyPurposeId(id_kp.branch("1"));
/**
* { id-kp 2 }
*/
public static final KeyPurposeId id_kp_clientAuth = new KeyPurposeId(id_kp.branch("2"));
/**
* { id-kp 3 }
*/
public static final KeyPurposeId id_kp_codeSigning = new KeyPurposeId(id_kp.branch("3"));
/**
* { id-kp 4 }
*/
public static final KeyPurposeId id_kp_emailProtection = new KeyPurposeId(id_kp.branch("4"));
/**
* Usage deprecated by RFC4945 - was { id-kp 5 }
*/
public static final KeyPurposeId id_kp_ipsecEndSystem = new KeyPurposeId(id_kp.branch("5"));
/**
* Usage deprecated by RFC4945 - was { id-kp 6 }
*/
public static final KeyPurposeId id_kp_ipsecTunnel = new KeyPurposeId(id_kp.branch("6"));
/**
* Usage deprecated by RFC4945 - was { idkp 7 }
*/
public static final KeyPurposeId id_kp_ipsecUser = new KeyPurposeId(id_kp.branch("7"));
/**
* { id-kp 8 }
*/
public static final KeyPurposeId id_kp_timeStamping = new KeyPurposeId(id_kp.branch("8"));
/**
* { id-kp 9 }
*/
public static final KeyPurposeId id_kp_OCSPSigning = new KeyPurposeId(id_kp.branch("9"));
/**
* { id-kp 10 }
*/
public static final KeyPurposeId id_kp_dvcs = new KeyPurposeId(id_kp.branch("10"));
/**
* { id-kp 11 }
*/
public static final KeyPurposeId id_kp_sbgpCertAAServerAuth = new KeyPurposeId(id_kp.branch("11"));
/**
* { id-kp 12 }
*/
public static final KeyPurposeId id_kp_scvp_responder = new KeyPurposeId(id_kp.branch("12"));
/**
* { id-kp 13 }
*/
public static final KeyPurposeId id_kp_eapOverPPP = new KeyPurposeId(id_kp.branch("13"));
/**
* { id-kp 14 }
*/
public static final KeyPurposeId id_kp_eapOverLAN = new KeyPurposeId(id_kp.branch("14"));
/**
* { id-kp 15 }
*/
public static final KeyPurposeId id_kp_scvpServer = new KeyPurposeId(id_kp.branch("15"));
/**
* { id-kp 16 }
*/
public static final KeyPurposeId id_kp_scvpClient = new KeyPurposeId(id_kp.branch("16"));
/**
* { id-kp 17 }
*/
public static final KeyPurposeId id_kp_ipsecIKE = new KeyPurposeId(id_kp.branch("17"));
/**
* { id-kp 18 }
*/
public static final KeyPurposeId id_kp_capwapAC = new KeyPurposeId(id_kp.branch("18"));
/**
* { id-kp 19 }
*/
public static final KeyPurposeId id_kp_capwapWTP = new KeyPurposeId(id_kp.branch("19"));
// microsoft key purpose ids
/**
* { 1 3 6 1 4 1 311 20 2 2 }
*/
public static final KeyPurposeId id_kp_smartcardlogon = new KeyPurposeId(new ASN1ObjectIdentifier("1.3.6.1.4.1.311.20.2.2"));
private ASN1ObjectIdentifier id;
private KeyPurposeId(ASN1ObjectIdentifier id)
{
this.id = id;
}
/**
* @deprecated use getInstance and an OID or one of the constants above.
* @param id string representation of an OID.
*/
public KeyPurposeId(String id)
{
this(new ASN1ObjectIdentifier(id));
}
public static KeyPurposeId getInstance(Object o)
{
if (o instanceof KeyPurposeId)
{
return (KeyPurposeId)o;
}
else if (o != null)
{
return new KeyPurposeId(ASN1ObjectIdentifier.getInstance(o));
}
return null;
}
public ASN1ObjectIdentifier toOID()
{
return id;
}
public ASN1Primitive toASN1Primitive()
{
return id;
}
public String getId()
{
return id.getId();
}
public String toString()
{
return id.toString();
}
}
|
package alma.TMCDB.maci;
@SuppressWarnings("serial")
public class Manager implements java.io.Serializable {
//static private final String newline = System.getProperty("line.separator");
@SuppressWarnings("unused")
private int ManagerId;
@SuppressWarnings("unused")
private int ConfigurationId;
// comma separated array
private String Startup = "";
private String ServiceComponents = "Log,LogFactory,NotifyEventChannelFactory,ArchivingChannel,LoggingChannel,InterfaceRepository,CDB,ACSLogSvc,PDB";
private LoggingConfig LoggingConfig;
private double Timeout = 50.0;
private double ClientPingInterval = 60;
private double AdministratorPingInterval = 45;
private double ContainerPingInterval = 30;
private double DeadlockTimeout = 180.0;
private int ServerThreads = 10;
// deperecated
private String Execute = "";
private String CommandLine = "";
private double HeartbeatTimeout = 2.0;
private int CacheSize = 10;
private int MinCachePriority = 0;
private int MaxCachePriority = 31;
private String CentralizedLogger = "Log";
/**
* Default Constructor for Manager. Setter methods must be used to insert data.
*/
public Manager () {
}
/**
* @return the administratorPingInterval
*/
public double getAdministratorPingInterval() {
return AdministratorPingInterval;
}
/**
* @param administratorPingInterval the administratorPingInterval to set
*/
public void setAdministratorPingInterval(double administratorPingInterval) {
AdministratorPingInterval = administratorPingInterval;
}
/**
* @return the clientPingInterval
*/
public double getClientPingInterval() {
return ClientPingInterval;
}
/**
* @param clientPingInterval the clientPingInterval to set
*/
public void setClientPingInterval(double clientPingInterval) {
ClientPingInterval = clientPingInterval;
}
/**
* @return the commandLine
*/
public String getCommandLine() {
return CommandLine;
}
/**
* @param commandLine the commandLine to set
*/
public void setCommandLine(String commandLine) {
CommandLine = commandLine;
}
/**
* @return the containerPingInterval
*/
public double getContainerPingInterval() {
return ContainerPingInterval;
}
/**
* @param containerPingInterval the containerPingInterval to set
*/
public void setContainerPingInterval(double containerPingInterval) {
ContainerPingInterval = containerPingInterval;
}
/**
* @return the deadlockTimeout
*/
public double getDeadlockTimeout() {
return DeadlockTimeout;
}
/**
* @param deadlockTimeout the deadlockTimeout to set
*/
public void setDeadlockTimeout(double deadlockTimeout) {
DeadlockTimeout = deadlockTimeout;
}
/**
* @return the execute
*/
public String getExecute() {
return Execute;
}
/**
* @param execute the execute to set
*/
public void setExecute(String execute) {
Execute = execute;
}
/**
* @return the heartbeatTimeout
*/
public double getHeartbeatTimeout() {
return HeartbeatTimeout;
}
/**
* @param heartbeatTimeout the heartbeatTimeout to set
*/
public void setHeartbeatTimeout(double heartbeatTimeout) {
HeartbeatTimeout = heartbeatTimeout;
}
/**
* @return the loggingConfig
*/
public LoggingConfig getLoggingConfig() {
return LoggingConfig;
}
/**
* @param loggingConfig the loggingConfig to set
*/
public void setLoggingConfig(LoggingConfig loggingConfig) {
LoggingConfig = loggingConfig;
}
/**
* @return the serverThreads
*/
public int getServerThreads() {
return ServerThreads;
}
/**
* @param serverThreads the serverThreads to set
*/
public void setServerThreads(int serverThreads) {
ServerThreads = serverThreads;
}
/**
* @return the serviceComponents
*/
public String getServiceComponents() {
if (ServiceComponents == null) return ""; // Oracle empty/NULL string workaround
return ServiceComponents;
}
/**
* @param serviceComponents the serviceComponents to set
*/
public void setServiceComponents(String serviceComponents) {
ServiceComponents = serviceComponents;
}
/**
* @return the startup
*/
public String getStartup() {
if (Startup == null) return ""; // Oracle empty/NULL string workaround
return Startup;
}
/**
* @param startup the startup to set
*/
public void setStartup(String startup) {
Startup = startup;
}
/**
* @return the timeout
*/
public double getTimeout() {
return Timeout;
}
/**
* @param timeout the timeout to set
*/
public void setTimeout(double timeout) {
Timeout = timeout;
}
/**
* @return the cacheSize
*/
public int getCacheSize() {
return CacheSize;
}
/**
* @param cacheSize the cacheSize to set
*/
public void setCacheSize(int cacheSize) {
CacheSize = cacheSize;
}
/**
* @return the centralizedLogger
*/
public String getCentralizedLogger() {
return CentralizedLogger;
}
/**
* @param centralizedLogger the centralizedLogger to set
*/
public void setCentralizedLogger(String centralizedLogger) {
CentralizedLogger = centralizedLogger;
}
/**
* @return the maxCachePriority
*/
public int getMaxCachePriority() {
return MaxCachePriority;
}
/**
* @param maxCachePriority the maxCachePriority to set
*/
public void setMaxCachePriority(int maxCachePriority) {
MaxCachePriority = maxCachePriority;
}
/**
* @return the minCachePriority
*/
public int getMinCachePriority() {
return MinCachePriority;
}
/**
* @param minCachePriority the minCachePriority to set
*/
public void setMinCachePriority(int minCachePriority) {
MinCachePriority = minCachePriority;
}
}
|
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.jdesktop.swingx.decorator.AlternateRowHighlighter;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.ConditionalHighlighter;
import org.jdesktop.swingx.decorator.Filter;
import org.jdesktop.swingx.decorator.FilterPipeline;
import org.jdesktop.swingx.decorator.HierarchicalColumnHighlighter;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterPipeline;
import org.jdesktop.swingx.decorator.PatternFilter;
import org.jdesktop.swingx.decorator.PatternHighlighter;
import org.jdesktop.swingx.decorator.ShuttleSorter;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;
import org.jdesktop.swingx.treetable.TreeTableModel;
import org.jdesktop.swingx.util.ComponentTreeTableModel;
/**
* @author Jeanette Winzenburg
*/
public class JXTreeTableVisualCheck extends JXTreeTableUnitTest {
private static final Logger LOG = Logger
.getLogger(JXTreeTableVisualCheck.class.getName());
public static void main(String[] args) {
// NOTE JW: this property has be set "very early" in the application life-cycle
// it's immutable once read from the UIManager (into a final static field!!)
System.setProperty("sun.swing.enableImprovedDragGesture", "true" );
setSystemLF(true);
JXTreeTableVisualCheck test = new JXTreeTableVisualCheck();
try {
// test.runInteractiveTests();
// test.runInteractiveTests("interactive.*Highligh.*");
// test.runInteractiveTests("interactive.*SortingFilter.*");
test.runInteractiveTests("interactive.*Node.*");
// test.runInteractiveTests("interactive.*Edit.*");
} catch (Exception ex) {
}
}
/**
* visualize editing of the hierarchical column, both
* in a tree and a treeTable
*
*/
public void interactiveTreeTableModelEditing() {
final TreeTableModel model = new ComponentTreeTableModel(new JXFrame());
final JXTreeTable table = new JXTreeTable(model);
JTree tree = new JTree(model) {
@Override
public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof Component) {
return ((Component) value).getName();
}
return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
}
};
tree.setEditable(true);
final JXFrame frame = wrapWithScrollingInFrame(table, tree, "Editing: compare treetable and tree");
Action toggleComponentOrientation = new AbstractAction("toggle orientation") {
public void actionPerformed(ActionEvent e) {
ComponentOrientation current = frame.getComponentOrientation();
if (current == ComponentOrientation.LEFT_TO_RIGHT) {
frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
} else {
frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
}
}
};
addAction(frame, toggleComponentOrientation);
frame.setVisible(true);
}
/**
* Issue #247-swingx: update probs with insert node.
* The insert under a collapsed node fires a dataChanged on the table
* which results in the usual total "memory" loss (f.i. selection)
* to reproduce: run example, select root's child in both the tree and the
* treetable (left and right view), press the insert button, treetable looses
* selection, tree doesn't (the latter is the correct behaviour)
*
* couldn't reproduce the reported loss of expansion state. Hmmm..
*
*/
public void interactiveTestInsertUnderCollapsedNode() {
final DefaultMutableTreeNode root = new DefaultMutableTreeNode();
final InsertTreeTableModel model = new InsertTreeTableModel(root);
DefaultMutableTreeNode childA = model.addChild(root);
final DefaultMutableTreeNode childB = model.addChild(childA);
model.addChild(childB);
DefaultMutableTreeNode secondRootChild = model.addChild(root);
model.addChild(secondRootChild);
JXTree tree = new JXTree(model);
final JXTreeTable treeTable = new JXTreeTable(model);
treeTable.setRootVisible(true);
JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "insert problem - root collapsed");
Action insertAction = new AbstractAction("insert node") {
public void actionPerformed(ActionEvent e) {
model.addChild(childB);
}
};
addAction(frame, insertAction);
frame.setVisible(true);
}
/**
* Issue #246-swingx: update probs with insert node.
*
* The reported issue is an asymmetry in updating the parent: it's done
* only if not expanded. With the arguments of #82-swingx, parent's
* appearance might be effected by child changes if expanded as well.
*
* Here's a test for insert: the crazy renderer removes the icon if
* childCount exceeds a limit. Select a node, insert a child, expand the node
* and keep inserting children. Interestingly the parent is
* always updated in the treeTable, but not in the tree
*
*
*/
public void interactiveTestInsertNodeAndChangedParentRendering() {
final DefaultMutableTreeNode root = new DefaultMutableTreeNode();
final InsertTreeTableModel model = new InsertTreeTableModel(root);
final DefaultMutableTreeNode leaf = model.addChild(root);
JXTree tree = new JXTree(model);
final JXTreeTable treeTable = new JXTreeTable(model);
TreeCellRenderer renderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
row, hasFocus);
TreePath path = tree.getPathForRow(row);
if (path != null) {
Object node = path.getLastPathComponent();
if ((node != null) && (tree.getModel().getChildCount(node) > 3)) {
setIcon(null);
}
}
return comp;
}
};
tree.setCellRenderer(renderer);
treeTable.setTreeCellRenderer(renderer);
treeTable.setRootVisible(true);
JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "update expanded parent on insert");
Action insertAction = new AbstractAction("insert node") {
public void actionPerformed(ActionEvent e) {
int selected = treeTable.getSelectedRow();
if (selected < 0 ) return;
TreePath path = treeTable.getPathForRow(selected);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
model.addChild(parent);
}
};
addAction(frame, insertAction);
frame.setVisible(true);
}
/**
* Issue #224-swingx: TreeTableEditor not bidi compliant.
*
* the textfield for editing is at the wrong position in RToL.
*/
public void interactiveRToLTreeTableEditor() {
final TreeTableModel model = new ComponentTreeTableModel(new JXFrame());
final JXTreeTable table = new JXTreeTable(model);
final JXFrame frame = wrapWithScrollingInFrame(table, "Editor: position follows Component orientation");
Action toggleComponentOrientation = new AbstractAction("toggle orientation") {
public void actionPerformed(ActionEvent e) {
ComponentOrientation current = frame.getComponentOrientation();
if (current == ComponentOrientation.LEFT_TO_RIGHT) {
frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
} else {
frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
}
}
};
addAction(frame, toggleComponentOrientation);
frame.setVisible(true);
}
/**
* Issue #223-swingx: TreeTableEditor not bidi compliant.
*
* the textfield for editing is at the wrong position in RToL.
*/
public void interactiveTreeTableEditorIcons() {
final TreeTableModel model = new ComponentTreeTableModel(new JXFrame());
final JXTreeTable table = new JXTreeTable(model);
final JScrollPane pane = new JScrollPane(table);
JXFrame frame = wrapWithScrollingInFrame(pane, "Editor: icons showing");
frame.setVisible(true);
}
/**
* Issue #82-swingx: update probs with insert node.
*
* Adapted from example code in report.
*
*/
public void interactiveTestInsertNode() {
final DefaultMutableTreeNode root = new DefaultMutableTreeNode();
final InsertTreeTableModel model = new InsertTreeTableModel(root);
final DefaultMutableTreeNode leaf = model.addChild(root);
JXTree tree = new JXTree(model);
final JXTreeTable treeTable = new JXTreeTable(model);
JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "update on insert");
Action insertAction = new AbstractAction("insert node") {
public void actionPerformed(ActionEvent e) {
int selected = treeTable.getSelectedRow();
if (selected < 0 ) return;
TreePath path = treeTable.getPathForRow(selected);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
model.addChild(parent);
}
};
addAction(frame, insertAction);
frame.setVisible(true);
}
/**
* see effect of switching treeTableModel.
* Problem when toggling back to FileSystemModel: hierarchical
* column does not show filenames, need to click into table first.
* JW: fixed. The issue was updating of the conversionMethod
* field - needed to be done before calling super.setModel().
*
*/
public void interactiveTestSetModel() {
final JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setColumnControlVisible(true);
JXFrame frame = wrapWithScrollingInFrame(treeTable, "toggle model");
frame.setVisible(true);
final TreeTableModel model = new ComponentTreeTableModel(frame);
Action action = new AbstractAction("Toggle model") {
public void actionPerformed(ActionEvent e) {
TreeTableModel myModel = treeTable.getTreeTableModel();
treeTable.setTreeTableModel(myModel == model ? treeTableModel : model);
}
};
addAction(frame, action);
}
/**
* Issue #168-jdnc: dnd enabled breaks node collapse/expand.
*/
public void interactiveToggleDnDEnabled() {
final JXTreeTable treeTable = new JXTreeTable(treeTableModel) {
/**
* testing dirty little hack mentioned in the forum
* discussion about the issue: fake a mousePressed if drag enabled.
* The usability is slightly impaired because the expand/collapse
* is effectively triggered on released only (drag system intercepts
* and consumes all other).
*
* @param row
* @param column
* @param e
* @return
*/
// @Override
// public boolean editCellAt(int row, int column, EventObject e) {
// if (getDragEnabled() && e instanceof MouseEvent) {
// MouseEvent me = (MouseEvent) e;
// LOG.info("original mouseEvent " + e);
// e = new MouseEvent((Component)me.getSource(),
// MouseEvent.MOUSE_PRESSED,
// me.getWhen(),
// me.getModifiers(),
// me.getX(),
// me.getY(),
// me.getClickCount(),
// me.isPopupTrigger());
// return super.editCellAt(row, column, e);
};
treeTable.setColumnControlVisible(true);
final JXTree tree = new JXTree(treeTableModel);
JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "toggle dragEnabled (starting with false)");
frame.setVisible(true);
Action action = new AbstractAction("Toggle dnd") {
public void actionPerformed(ActionEvent e) {
boolean dragEnabled = !treeTable.getDragEnabled();
treeTable.setDragEnabled(dragEnabled);
tree.setDragEnabled(dragEnabled);
}
};
addAction(frame, action);
}
public void interactiveTestFocusedCellBackground() {
JXTreeTable xtable = new JXTreeTable(treeTableModel);
xtable.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
JFrame frame = wrapWithScrollingInFrame(xtable, "Unselected focused background");
frame.setVisible(true);
}
/**
* Issue #226: no per-cell tooltips in TreeColumn.
*/
public void interactiveTestToolTips() {
JXTreeTable tree = new JXTreeTable(treeTableModel);
// JW: don't use this idiom - Stackoverflow...
// multiple delegation - need to solve or discourage
tree.setTreeCellRenderer(createRenderer());
tree.setDefaultRenderer(Object.class, createTableRenderer(tree.getDefaultRenderer(Object.class)));
JFrame frame = wrapWithScrollingInFrame(tree, "tooltips");
frame.setVisible(true);
}
private TableCellRenderer createTableRenderer(final TableCellRenderer delegate) {
TableCellRenderer l = new TableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component result = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
((JComponent) result).setToolTipText(String.valueOf(value));
return result;
}
};
return l;
}
private TreeCellRenderer createRenderer() {
final TreeCellRenderer delegate = new DefaultTreeCellRenderer();
TreeCellRenderer renderer = new TreeCellRenderer() {
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component result = delegate.getTreeCellRendererComponent(tree, value,
selected, expanded, leaf, row, hasFocus);
((JComponent) result).setToolTipText(String.valueOf(tree.getPathForRow(row)));
return result;
}
};
return renderer;
}
/**
* reported: boolean not showing - not reproducible
*
*/
public void interactiveTestBooleanRenderer() {
final JXTreeTable treeTable = new JXTreeTable(new MyTreeTableModel());
treeTable.setRootVisible(true);
JFrame frame = wrapWithScrollingInFrame(treeTable, "boolean renderers");
frame.setVisible(true);
}
private class MyTreeTableModel extends DefaultTreeTableModel {
public MyTreeTableModel() {
final DefaultMutableTreeNode root =
new DefaultMutableTreeNode("Root");
root.add(new DefaultMutableTreeNode("A"));
root.add(new DefaultMutableTreeNode("B"));
this.setRoot(root);
}
public int getColumnCount() {
return 2;
}
public Class getColumnClass(int column) {
if (column == 1) {
return Boolean.class;
}
return super.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return true;
}
public boolean isCellEditable(Object value, int column) {
return true;
}
public Object getValueAt(Object o, int column) {
if (column == 0) {
return o.toString();
}
return new Boolean(true);
}
}
public void interactiveTestCompareTreeProperties() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setShowsRootHandles(false);
treeTable.setRootVisible(false);
JXTreeTable other = new JXTreeTable(treeTableModel);
other.setRootVisible(true);
other.setShowsRootHandles(false);
JFrame frame = wrapWithScrollingInFrame(treeTable, other, "compare rootVisible");
frame.setVisible(true);
}
/**
* setting tree properties: tree not updated correctly.
*/
public void interactiveTestTreeProperties() {
final JXTreeTable treeTable = new JXTreeTable(treeTableModel);
Action toggleHandles = new AbstractAction("Toggle Handles") {
public void actionPerformed(ActionEvent e) {
treeTable.setShowsRootHandles(!treeTable.getShowsRootHandles());
}
};
Action toggleRoot = new AbstractAction("Toggle Root") {
public void actionPerformed(ActionEvent e) {
treeTable.setRootVisible(!treeTable.isRootVisible());
}
};
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
JXFrame frame = wrapWithScrollingInFrame(treeTable,
"Toggle Tree properties ");
addAction(frame, toggleRoot);
addAction(frame, toggleHandles);
frame.setVisible(true);
}
/**
* Issue #242: CCE when setting icons.
*/
public void interactiveTestTreeIcons() {
final JXTreeTable treeTable = new JXTreeTable(treeTableModel);
Icon downIcon = new ImageIcon(getClass().getResource("resources/images/" + "wellbottom.gif"));
// DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
// renderer.setClosedIcon(downIcon);
// treeTable.setTreeCellRenderer(renderer);
treeTable.setClosedIcon(downIcon);
// Action toggleHandles = new AbstractAction("Toggle Handles") {
// public void actionPerformed(ActionEvent e) {
// treeTable.setShowsRootHandles(!treeTable.getShowsRootHandles());
// Action toggleRoot = new AbstractAction("Toggle Root") {
// public void actionPerformed(ActionEvent e) {
// treeTable.setRootVisible(!treeTable.isRootVisible());
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
JFrame frame = wrapWithScrollingInFrame(treeTable,
"Toggle Tree icons ");
// addAction(frame, toggleRoot);
// addAction(frame, toggleHandles);
frame.setVisible(true);
}
/** issue #148
* did not work on LFs which normally respect lineStyle
* winLF does not respect it anyway...
*/
public void interactiveTestFilterHighlightAndLineStyle() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
// issue #148
// did not work on LFs which normally respect lineStyle
// winLF does not respect it anyway...
treeTable.putClientProperty("JTree.lineStyle", "Angled");
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
// add a bunch of highlighters directly
treeTable.addHighlighter(AlternateRowHighlighter.quickSilver);
treeTable.addHighlighter(new HierarchicalColumnHighlighter());
treeTable.addHighlighter(new PatternHighlighter(null, Color.red, "^s",
Pattern.CASE_INSENSITIVE, 0, -1));
// alternative: set a pipeline containing the bunch of highlighters
// treeTable.setHighlighters(new HighlighterPipeline(new Highlighter[] {
// AlternateRowHighlighter.quickSilver,
// new HierarchicalColumnHighlighter(),
// new PatternHighlighter(null, Color.red, "^s",
// Pattern.CASE_INSENSITIVE, 0, -1), }));
JFrame frame = wrapWithScrollingInFrame(treeTable,
"QuickSilver-, Column-, PatternHighligher and LineStyle");
frame.setVisible(true);
}
/**
* Issue #204: weird filtering.
*
*/
public void interactiveTestFilters() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.putClientProperty("JTree.lineStyle", "Angled");
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
treeTable.setFilters(new FilterPipeline(new Filter[] {
new PatternFilter( "^d",
Pattern.CASE_INSENSITIVE, 0), }));
JFrame frame = wrapWithScrollingInFrame(treeTable,
"PatternFilter");
frame.setVisible(true);
}
/**
* Issue #??: weird sorting.
*
*/
public void interactiveTestSortingFilters() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
treeTable.setFilters(new FilterPipeline(new Filter[] {
new ShuttleSorter(1, false), }));
JFrame frame = wrapWithScrollingInFrame(treeTable,
"SortingFilter");
frame.setVisible(true);
}
public void interactiveTestHighlightAndRowHeight() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
treeTable.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.linePrinter,
new HierarchicalColumnHighlighter(), }));
JFrame frame = wrapWithScrollingInFrame(treeTable,
"LinePrinter-, ColumnHighlighter and RowHeight");
frame.setVisible(true);
}
public void interactiveTestAlternateRowHighlighter() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.addHighlighter(AlternateRowHighlighter.classicLinePrinter);
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
JFrame frame = wrapWithScrollingInFrame(treeTable,
"ClassicLinePrinter and RowHeight");
frame.setVisible(true);
}
public void interactiveTestBackgroundHighlighter() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setHighlighters(new HighlighterPipeline(new Highlighter[] {
AlternateRowHighlighter.notePadBackground,
new HierarchicalColumnHighlighter(), }));
treeTable.setBackground(new Color(0xFF, 0xFF, 0xCC)); // notepad
treeTable.setGridColor(Color.cyan.darker());
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
treeTable.setShowHorizontalLines(true);
JFrame frame = wrapWithScrollingInFrame(treeTable,
"NotePadBackground- HierarchicalColumnHighlighter and horiz lines");
frame.setVisible(true);
}
public void interactiveTestLedgerBackground() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger
treeTable.setGridColor(Color.cyan.darker());
treeTable.setRowHeight(22);
treeTable.setRowMargin(1);
treeTable.setShowHorizontalLines(true);
JFrame frame = wrapWithScrollingInFrame(treeTable, "LedgerBackground");
frame.setVisible(true);
}
public void interactiveTestHierarchicalColumnHighlight() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.addHighlighter(new HierarchicalColumnHighlighter());
JFrame frame = wrapWithScrollingInFrame(treeTable,
"HierarchicalColumnHigh");
frame.setVisible(true);
}
public void interactiveTestIntercellSpacing1() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setIntercellSpacing(new Dimension(1, 1));
treeTable.setShowGrid(true);
JFrame frame = wrapWithScrollingInFrame(treeTable, "Intercellspacing 1");
frame.setVisible(true);
}
public void interactiveTestIntercellSpacing2() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setIntercellSpacing(new Dimension(2, 2));
treeTable.setShowGrid(true);
JFrame frame = wrapWithScrollingInFrame(treeTable, "Intercellspacing 2");
frame.setVisible(true);
}
public void interactiveTestIntercellSpacing3() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setIntercellSpacing(new Dimension(3, 3));
treeTable.setShowGrid(true);
JFrame frame = wrapWithScrollingInFrame(treeTable, "Intercellspacing 3");
frame.setVisible(true);
}
public void interactiveTestHighlighterRowHeight() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.addHighlighter(new Highlighter(Color.orange, null));
treeTable.setIntercellSpacing(new Dimension(15, 15));
treeTable.setRowHeight(48);
JFrame frame = wrapWithScrollingInFrame(treeTable,
"Orange, big rowheight");
frame.setVisible(true);
}
public void interactiveTestHighlighters() {
JXTreeTable treeTable = new JXTreeTable(treeTableModel);
treeTable.setIntercellSpacing(new Dimension(15, 15));
treeTable.setRowHeight(48);
// not supported in JXTreeTable
// treeTable.setRowHeight(0, 96);
treeTable.setShowGrid(true);
// set a bunch of highlighters as a pipeline
treeTable.setHighlighters(new HighlighterPipeline(
new Highlighter[] {
new Highlighter(Color.orange, null),
new HierarchicalColumnHighlighter(),
new PatternHighlighter(null, Color.red,
"D", 0, 0, 0),
}));
Highlighter conditional = new ConditionalHighlighter(Color.BLUE, Color.WHITE, 0, 0) {
protected boolean test(ComponentAdapter adapter) {
return adapter.hasFocus();
}
};
// add the conditional highlighter later
treeTable.addHighlighter(conditional);
JFrame frame = wrapWithScrollingInFrame(treeTable, "Highlighters: conditional, orange, hierarchy, pattern D");
frame.setVisible(true);
}
}
|
// Administrator of the National Aeronautics and Space Administration
// This software is distributed under the NASA Open Source Agreement
// (NOSA), version 1.3. The NOSA has been approved by the Open Source
// Initiative. See the file NOSA-1.3-JPF at the top of the distribution
// directory tree for the complete NOSA document.
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
package gov.nasa.jpf.test.mc.data;
import gov.nasa.jpf.jvm.Verify;
import gov.nasa.jpf.util.test.TestJPF;
import org.junit.Test;
public class PerturbatorTest extends TestJPF {
int data = 42;
public static void main(String[] args) {
runTestsOfThisClass(args);
}
@Test
public void testIntFieldPerturbation() {
if (!isJPFRun()){
Verify.resetCounter(0);
}
if (verifyNoPropertyViolation("+listener=.listener.Perturbator",
"+perturb.fields=data",
"+perturb.data.class=.perturb.IntOverUnder",
"+perturb.data.field=gov.nasa.jpf.test.mc.data.PerturbatorTest.data",
"+perturb.data.delta=1")){
System.out.println("instance field perturbation test");
int d = data;
System.out.print("d = ");
System.out.println(d);
Verify.incrementCounter(0);
switch (Verify.getCounter(0)){
case 1: assert d == 43; break;
case 2: assert d == 42; break;
case 3: assert d == 41; break;
default:
assert false : "wrong counter value: " + Verify.getCounter(0);
}
} else {
assert Verify.getCounter(0) == 3;
}
}
@Test
public void testFieldPerturbationLocation() {
if (!isJPFRun()){
Verify.resetCounter(0);
}
if (verifyNoPropertyViolation("+listener=.listener.Perturbator",
"+perturb.fields=data",
"+perturb.data.class=.perturb.IntOverUnder",
"+perturb.data.field=gov.nasa.jpf.test.mc.data.PerturbatorTest.data",
"+perturb.data.location=PerturbatorTest.java:87",
"+perturb.data.delta=1")){
System.out.println("instance field location perturbation test");
int x = data; // this should not be perturbed
System.out.print("x = ");
System.out.println(x);
int d = data; // this should be
System.out.print("d = ");
System.out.println(d);
Verify.incrementCounter(0);
} else {
assert Verify.getCounter(0) == 3;
}
}
}
|
package org.voovan.network;
import org.voovan.Global;
import org.voovan.network.tcp.TcpServerSocket;
import org.voovan.network.udp.UdpServerSocket;
import org.voovan.network.udp.UdpSession;
import org.voovan.network.tcp.TcpSocket;
import org.voovan.network.udp.UdpSocket;
import org.voovan.tools.*;
import org.voovan.tools.buffer.ByteBufferChannel;
import org.voovan.tools.collection.ArraySet;
import org.voovan.tools.event.EventRunner;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
public class SocketSelector implements Closeable {
private EventRunner eventRunner;
protected Selector selector;
protected boolean isCheckTimeout;
protected ArraySet<SelectionKey> selectedKeys = new ArraySet<SelectionKey>(65536);
protected AtomicBoolean selecting = new AtomicBoolean(false);
private boolean useSelectNow = false;
/**
*
* @param eventRunner
* @param isCheckTimeout
* @throws IOException IO
*/
public SocketSelector(EventRunner eventRunner, boolean isCheckTimeout) throws IOException {
this.selector = SelectorProvider.provider().openSelector();
this.eventRunner = eventRunner;
this.isCheckTimeout = isCheckTimeout;
try {
TReflect.setFieldValue(selector, NioUtil.selectedKeysField, selectedKeys);
TReflect.setFieldValue(selector, NioUtil.publicSelectedKeysField, selectedKeys);
} catch (ReflectiveOperationException e) {
Logger.error(e);
}
addIoEvent();
if(Global.IS_DEBUG_MODE) {
Global.getHashWheelTimer().addTask(new HashWheelTask() {
@Override
public void run() {
System.out.print(eventRunner.getThread().getName() + " " + selector.keys().size() + " = " + eventRunner.getEventQueue().size());
int ioTaskCount = 0;
int eventTaskCount = 0;
int registerTaskCount = 0;
for (EventRunner.EventTask eventTask : eventRunner.getEventQueue()) {
if (eventTask.getPriority() == 4)
ioTaskCount++;
if (eventTask.getPriority() == 5)
eventTaskCount++;
if (eventTask.getPriority() == 6)
registerTaskCount++;
}
System.out.println(" (IO=" + ioTaskCount + ", Event=" + eventTaskCount + " ,register=" + registerTaskCount + ")");
}
}, 1);
}
}
public EventRunner getEventRunner() {
return eventRunner;
}
/**
* SocketContext
* @param socketContext SocketContext
* @param ops
* @return true:, false:
*/
public boolean register(SocketContext socketContext, int ops){
if(ops==0) {
IoSession session = socketContext.getSession();
session.setSocketSelector(this);
} else {
addEvent(6, () -> {
try {
SelectionKey selectionKey = socketContext.socketChannel().register(selector, ops, socketContext);
if (socketContext.connectModel != ConnectModel.LISTENER) {
IoSession session = socketContext.getSession();
session.setSelectionKey(selectionKey);
session.setSocketSelector(this);
if (!session.isSSLMode()) {
EventTrigger.fireConnect(session);
} else {
// SSL
if (socketContext.connectModel == ConnectModel.CLIENT) {
session.getSSLParser().doHandShake();
}
}
}
socketContext.setRegister(true);
} catch (ClosedChannelException e) {
Logger.error("Register " + socketContext + " to selector error", e);
}
});
// select
if (selecting.get()) {
selector.wakeup();
}
}
return true;
}
/**
* SocketContext
* @param selectionKey SocketContext
*/
public void unRegister(SelectionKey selectionKey) {
try {
selectionKey.channel().close();
} catch (IOException e) {
Logger.error(e);
}
if (selectionKey.isValid()) {
selectionKey.interestOps(0);
}
selectionKey.cancel();
// select , cancel selectNow
if (selecting.get()) {
selector.wakeup();
}
SocketContext socketContext = (SocketContext) selectionKey.attachment();
if(socketContext!=null && socketContext.isRegister() && selectionKey.channel().isRegistered()) {
socketContext.setRegister(false);
selectionKey.attach(null);
socketContext.getSession().getReadByteBufferChannel().release();
socketContext.getSession().getSendByteBufferChannel().release();
if (socketContext.getSession().isSSLMode()) {
socketContext.getSession().getSSLParser().release();
}
EventTrigger.fireDisconnect(socketContext.getSession());
}
}
/**
*
* @return
*/
private boolean inEventRunner(){
return eventRunner.getThread() == Thread.currentThread();
}
public void addIoEvent(){
eventRunner.addEvent(4, () -> {
select();
addIoEvent();
});
}
/**
*
* @param priority , , 1-3 , 4:IO , 5:EventProcess , 6: Socket /, 7-10
* @param runnable
*/
public void addEvent(int priority, Runnable runnable){
if(runnable==null) {
throw new NullPointerException("add Event's second paramater must be not null");
}
if(selector.isOpen()) {
eventRunner.addEvent(priority, () -> {
try {
runnable.run();
} catch (Exception e) {
Logger.error("addChoseEvent error:", e);
}
});
}
}
int JvmEpollBugFlag = 0;
/**
*
* @return true: NIO , false: NIO
*/
public boolean select() {
boolean ret = false;
try {
if (selector != null && selector.isOpen()) {
//, socket key
processSelect();
// selectNow, select
if (!selectedKeys.isEmpty()) {
ret = processSelectionKeys();
useSelectNow = true;
} else {
useSelectNow = false;
}
}
} catch (IOException e){
Logger.error("NioSelector error: ", e);
}
return ret;
}
/**
*
* @throws IOException IO
*/
private void processSelect() throws IOException {
if(useSelectNow){
selector.selectNow();
} else {
try {
checkReadTimeout();
selecting.compareAndSet(false, true);
selector.select(SocketContext.SELECT_INTERVAL);
selecting.compareAndSet(true, false);
} catch (IOException e) {
Logger.error(e);
}
}
}
public void checkReadTimeout(){
if(isCheckTimeout) {
for (SelectionKey selectionKey : selector.keys()) {
SocketContext socketContext = (SocketContext) selectionKey.attachment();
if (socketContext!=null && socketContext.connectModel != ConnectModel.LISTENER) {
boolean bufferDataEmpty = socketContext.getSession().getReadByteBufferChannel().isEmpty() && socketContext.getSession().getSendByteBufferChannel().isEmpty();
if(socketContext.isTimeOut() && bufferDataEmpty) {
socketContext.close();
EventTrigger.fireException(socketContext.getSession(), new TimeoutException("Socket Read timeout"));
} else if(!bufferDataEmpty) {
socketContext.updateLastTime();
}
}
}
}
}
/**
* Key
* @return true: NIO , false: NIO
* @throws IOException IO
*/
private boolean processSelectionKeys() throws IOException {
boolean ret = false;
for (int i = 0; i< selectedKeys.size(); i++) {
SelectionKey selectedKey = selectedKeys.getAndRemove(i);
if (selectedKey.isValid()) {
// socket
SelectableChannel channel = selectedKey.channel();
SocketContext socketContext = (SocketContext) selectedKey.attachment();
if (channel.isOpen() && selectedKey.isValid()) {
// , onRead onAccept
// Server
if((selectedKey.readyOps() & SelectionKey.OP_ACCEPT) != 0) {
SocketChannel socketChannel = ((ServerSocketChannel) channel).accept();
tcpAccept((TcpServerSocket) socketContext, socketChannel);
}
if ((selectedKey.readyOps() & SelectionKey.OP_READ) != 0) {
socketContext.updateLastTime();
readFromChannel(socketContext, channel);
}
}
ret = true;
}
}
selectedKeys.reset();
return ret;
}
public void close() {
try {
selector.close();
} catch (IOException e) {
Logger.error("close selector error");
}
}
/**
*
* @param socketContext SocketContext
* @param selectableChannel SelectableChannel
* @return , -1:
*/
public int readFromChannel(SocketContext socketContext, SelectableChannel selectableChannel){
try {
if (selectableChannel instanceof SocketChannel) {
return tcpReadFromChannel((TcpSocket) socketContext, (SocketChannel) selectableChannel);
} else if (selectableChannel instanceof DatagramChannel) {
return udpReadFromChannel((SocketContext<DatagramChannel, UdpSession>) socketContext, (DatagramChannel) selectableChannel);
} else {
return -1;
}
} catch(Exception e){
return dealException(socketContext, e);
}
}
/**
*
* @param socketContext SocketContext
* @param buffer
* @return , -1:
*/
public int writeToChannel(SocketContext socketContext, ByteBuffer buffer){
try {
if(isCheckTimeout) {
socketContext.updateLastTime();
}
if (socketContext.getConnectType() == ConnectType.TCP) {
return tcpWriteToChannel((TcpSocket) socketContext, buffer);
} else if (socketContext.getConnectType() == ConnectType.UDP) {
return udpWriteToChannel((UdpSocket) socketContext, buffer);
} else {
return -1;
}
} catch(Exception e) {
return dealException(socketContext, e);
} finally {
socketContext.getSession().getSendByteBufferChannel().clear();
}
}
/**
* Tcp
* @param socketContext SocketContext
* @param socketChannel Socketchannel
*/
public void tcpAccept(TcpServerSocket socketContext, SocketChannel socketChannel) {
TcpSocket socket = new TcpSocket(socketContext, socketChannel);
EventTrigger.fireAccept(socket.getSession());
}
/**
* TCP
* @param socketContext TcpSocket
* @param socketChannel Socketchannel
* @return , -1:
* @throws IOException IO
*/
public int tcpReadFromChannel(TcpSocket socketContext, SocketChannel socketChannel) throws IOException {
IoSession session = socketContext.getSession();
ByteBufferChannel byteBufferChannel = session.isSSLMode()
? session.getSSLParser().getSSlByteBufferChannel()
: session.getReadByteBufferChannel();
if(byteBufferChannel.available() == 0) {
byteBufferChannel.reallocate(byteBufferChannel.capacity() + 4 * 1024);
}
int readSize = -1;
if(!byteBufferChannel.isReleased()) {
ByteBuffer byteBuffer = byteBufferChannel.getByteBuffer();
byteBuffer.position(byteBuffer.limit());
byteBuffer.limit(byteBuffer.capacity());
readSize = socketChannel.read(byteBuffer);
byteBuffer.flip();
byteBufferChannel.compact();
}
readSize = loadAndPrepare(socketContext.getSession(), readSize);
return readSize;
}
/**
* TCP
* @param socketContext TcpSocket
* @param buffer
* @return , -1:
* @throws IOException IO
*/
public int tcpWriteToChannel(TcpSocket socketContext, ByteBuffer buffer) throws IOException {
int totalSendByte = 0;
long start = System.currentTimeMillis();
if (buffer != null) {
try {
while (buffer.remaining() != 0) {
int sendSize = socketContext.socketChannel().write(buffer);
if (sendSize == 0) {
if (System.currentTimeMillis() - start >= socketContext.getSendTimeout()) {
Logger.error("SocketSelector tcpWriteToChannel timeout", new TimeoutException());
socketContext.close();
return -1;
}
} else if (sendSize < 0) {
socketContext.close();
return -1;
} else {
start = System.currentTimeMillis();
totalSendByte += sendSize;
}
}
} catch (NotYetConnectedException e) {
socketContext.close();
return -1;
}
}
return totalSendByte;
}
/**
* UDP
* @param socketContext UdpServerSocket
* @param datagramChannel DatagramChannel
* @param address
* @return UdpSocket
* @throws IOException IO
*/
public UdpSocket udpAccept(UdpServerSocket socketContext, DatagramChannel datagramChannel, SocketAddress address) throws IOException {
UdpSocket udpSocket = new UdpSocket(socketContext, datagramChannel, (InetSocketAddress) address);
udpSocket.acceptStart();
return udpSocket;
}
/**
* UDP
* @param socketContext SocketContext
* @param datagramChannel DatagramChannel
* @return , -1:
* @throws IOException IO
*/
public int udpReadFromChannel(SocketContext<DatagramChannel, UdpSession> socketContext, DatagramChannel datagramChannel) throws IOException {
if (!datagramChannel.isConnected()) {
socketContext = (UdpSocket) udpAccept((UdpServerSocket) socketContext, datagramChannel, null);
}
UdpSession session = socketContext.getSession();
ByteBufferChannel byteBufferChannel = session.getReadByteBufferChannel();
ByteBuffer byteBuffer = byteBufferChannel.getByteBuffer();
if(byteBufferChannel.available() == 0) {
byteBufferChannel.reallocate(byteBufferChannel.capacity() + 4 * 1024);
}
int readSize = -1;
if(!byteBufferChannel.isReleased()) {
byteBuffer.position(byteBuffer.limit());
byteBuffer.limit(byteBuffer.capacity());
if (!datagramChannel.isConnected()) {
SocketAddress socketAddress = datagramChannel.receive(byteBuffer);
session.setInetSocketAddress((InetSocketAddress) socketAddress);
readSize = byteBuffer.position();
} else {
readSize = datagramChannel.read(byteBuffer);
}
byteBuffer.flip();
byteBufferChannel.compact();
}
readSize = loadAndPrepare(socketContext.getSession(), readSize);
return readSize;
}
/**
* UDP
* @param socketContext UdpSocket
* @param buffer
* @return , -1:
* @throws IOException IO
*/
public int udpWriteToChannel(UdpSocket socketContext, ByteBuffer buffer) throws IOException {
DatagramChannel datagramChannel = socketContext.socketChannel();
UdpSession session = socketContext.getSession();
int totalSendByte = 0;
long start = System.currentTimeMillis();
if (buffer != null) {
try {
while (buffer.remaining() != 0) {
int sendSize = 0;
if (datagramChannel.isConnected()) {
sendSize = datagramChannel.write(buffer);
} else {
sendSize = datagramChannel.send(buffer, session.getInetSocketAddress());
}
if (sendSize == 0) {
TEnv.sleep(1);
if (System.currentTimeMillis() - start >= socketContext.getSendTimeout()) {
Logger.error("SocketSelector udpWriteToChannel timeout, Socket will be close");
socketContext.close();
return -1;
}
} else if (sendSize < 0) {
socketContext.close();
return -1;
} else {
start = System.currentTimeMillis();
totalSendByte += sendSize;
}
}
} catch (NotYetConnectedException e) {
socketContext.close();
return -1;
}
}
return totalSendByte;
}
/**
*
* @param session IoSession
* @param readSize
* @return
* @throws IOException IO
*/
public int loadAndPrepare(IoSession session, int readSize) throws IOException {
// , session , session
if (MessageLoader.isStreamEnd(readSize) || !session.isConnected()) {
session.getMessageLoader().setStopType(MessageLoader.StopType.STREAM_END);
session.close();
return -1;
} else {
ByteBufferChannel appByteBufferChannel = session.getReadByteBufferChannel();
if (readSize > 0) {
if(session.isSSLMode()) {
// SSL ,
if (!SSLParser.isHandShakeDone(session)) {
session.getSSLParser().doHandShake();
return readSize;
} else {
session.getSSLParser().unWarpByteBufferChannel();
}
}
if (!session.getState().isReceive() && appByteBufferChannel.size() > 0) {
// onReceive
if(SocketContext.ASYNC_RECIVE) {
EventTrigger.fireReceiveAsync(session);
} else {
EventTrigger.fireReceive(session);
}
}
}
return readSize;
}
}
static String BROKEN_PIPE = "Broken pipe";
static String CONNECTION_RESET = "Connection reset by peer";
/**
*
* @param socketContext SocketContext
* @param e Exception
* @return -1
*/
public int dealException(SocketContext socketContext, Exception e) {
if(BROKEN_PIPE.equals(e.getMessage()) || CONNECTION_RESET.equals(e.getMessage())){
socketContext.close();
return -1;
}
// windows "java.io.IOException: "
if(e.getStackTrace()[0].getClassName().contains("sun.tcp.ch")){
return -1;
}
if(e instanceof Exception){
// onException
try {
EventTrigger.fireException((IoSession) socketContext.getSession(), e);
} catch (Exception ex) {
Logger.error(e);
}
}
return -1;
}
}
|
package com.ternaryop.widget;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.RelativeLayout;
/**
* Used to select items in listView
*
* @author dave
*
*/
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private boolean isChecked;
private List<Checkable> checkableViews;
public CheckableRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CheckableRelativeLayout(Context context, int checkableId) {
super(context);
init();
}
private void init() {
checkableViews = new ArrayList<Checkable>();
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
setSelected(isChecked);
for (Checkable c : checkableViews) {
c.setChecked(checked);
}
}
public void toggle() {
isChecked = !isChecked;
setSelected(isChecked);
for (Checkable c : checkableViews) {
c.toggle();
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
final int childCount = this.getChildCount();
for (int i = 0; i < childCount; ++i) {
findCheckableChildren(this.getChildAt(i));
}
}
private void findCheckableChildren(View v) {
if (v instanceof Checkable) {
checkableViews.add((Checkable) v);
}
if (v instanceof ViewGroup) {
final ViewGroup vg = (ViewGroup) v;
final int childCount = vg.getChildCount();
for (int i = 0; i < childCount; ++i) {
findCheckableChildren(vg.getChildAt(i));
}
}
}
}
|
package org.bouncycastle.crypto.test;
import java.util.ArrayList;
import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.SimpleTest;
public class Argon2Test
extends SimpleTest
{
private static final int DEFAULT_OUTPUTLEN = 32;
public String getName()
{
return "ArgonTest";
}
public void performTest()
throws Exception
{
if (getJvmVersion() < 7)
{
return;
}
testPermutations();
testVectorsFromInternetDraft();
int version = Argon2Parameters.ARGON2_VERSION_10;
/* Multiple test cases for various input values */
hashTest(version, 2, 16, 1, "password", "somesalt",
"f6c4db4a54e2a370627aff3db6176b94a2a209a62c8e36152711802f7b30c694", DEFAULT_OUTPUTLEN);
// TODO: this test actually causes gradle to run out of memory!
// hashTest(version, 2, 20, 1, "password", "somesalt",
// "9690ec55d28d3ed32562f2e73ea62b02b018757643a2ae6e79528459de8106e9",
// DEFAULT_OUTPUTLEN);
hashTest(version, 2, 18, 1, "password", "somesalt",
"3e689aaa3d28a77cf2bc72a51ac53166761751182f1ee292e3f677a7da4c2467",
DEFAULT_OUTPUTLEN);
hashTest(version, 2, 8, 1, "password", "somesalt",
"fd4dd83d762c49bdeaf57c47bdcd0c2f1babf863fdeb490df63ede9975fccf06",
DEFAULT_OUTPUTLEN);
hashTest(version, 2, 8, 2, "password", "somesalt",
"b6c11560a6a9d61eac706b79a2f97d68b4463aa3ad87e00c07e2b01e90c564fb", DEFAULT_OUTPUTLEN);
hashTest(version, 1, 16, 1, "password", "somesalt",
"81630552b8f3b1f48cdb1992c4c678643d490b2b5eb4ff6c4b3438b5621724b2", DEFAULT_OUTPUTLEN);
hashTest(version, 4, 16, 1, "password", "somesalt",
"f212f01615e6eb5d74734dc3ef40ade2d51d052468d8c69440a3a1f2c1c2847b", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 16, 1, "differentpassword", "somesalt",
"e9c902074b6754531a3a0be519e5baf404b30ce69b3f01ac3bf21229960109a3", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 16, 1, "password", "diffsalt",
"79a103b90fe8aef8570cb31fc8b22259778916f8336b7bdac3892569d4f1c497", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 16, 1, "password", "diffsalt",
"1a097a5d1c80e579583f6e19c7e4763ccb7c522ca85b7d58143738e12ca39f8e6e42734c950ff2463675b97c37ba" +
"39feba4a9cd9cc5b4c798f2aaf70eb4bd044c8d148decb569870dbd923430b82a083f284beae777812cce18cdac68ee8ccef" +
"c6ec9789f30a6b5a034591f51af830f4",
112);
version = Argon2Parameters.ARGON2_VERSION_13;
/* Multiple test cases for various input values */
hashTest(version, 2, 16, 1, "password", "somesalt",
"c1628832147d9720c5bd1cfd61367078729f6dfb6f8fea9ff98158e0d7816ed0",
DEFAULT_OUTPUTLEN);
// TODO: this test actually causes gradle to run out of memory!
// hashTest(version, 2, 20, 1, "password", "somesalt",
// "d1587aca0922c3b5d6a83edab31bee3c4ebaef342ed6127a55d19b2351ad1f41", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 18, 1, "password", "somesalt",
"296dbae80b807cdceaad44ae741b506f14db0959267b183b118f9b24229bc7cb", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 8, 1, "password", "somesalt",
"89e9029f4637b295beb027056a7336c414fadd43f6b208645281cb214a56452f", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 8, 2, "password", "somesalt",
"4ff5ce2769a1d7f4c8a491df09d41a9fbe90e5eb02155a13e4c01e20cd4eab61", DEFAULT_OUTPUTLEN);
hashTest(version, 1, 16, 1, "password", "somesalt",
"d168075c4d985e13ebeae560cf8b94c3b5d8a16c51916b6f4ac2da3ac11bbecf", DEFAULT_OUTPUTLEN);
hashTest(version, 4, 16, 1, "password", "somesalt",
"aaa953d58af3706ce3df1aefd4a64a84e31d7f54175231f1285259f88174ce5b", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 16, 1, "differentpassword", "somesalt",
"14ae8da01afea8700c2358dcef7c5358d9021282bd88663a4562f59fb74d22ee", DEFAULT_OUTPUTLEN);
hashTest(version, 2, 16, 1, "password", "diffsalt",
"b0357cccfbef91f3860b0dba447b2348cbefecadaf990abfe9cc40726c521271", DEFAULT_OUTPUTLEN);
}
public void testPermutations()
throws Exception
{
byte[] rootPassword = Strings.toByteArray("aac");
byte[] buf = null;
byte[][] salts = new byte[3][];
salts[0] = new byte[16];
salts[1] = new byte[16];
salts[2] = new byte[16];
for (int t = 0; t < 16; t++)
{
salts[1][t] = (byte)t;
salts[2][t] = (byte)(16 - t);
}
// Permutation, starting with a shorter array, same length then one longer.
for (int j = rootPassword.length - 1; j < rootPassword.length + 2; j++)
{
buf = new byte[j];
for (int a = 0; a < rootPassword.length; a++)
{
for (int b = 0; b < buf.length; b++)
{
buf[b] = rootPassword[(a + b) % rootPassword.length];
}
ArrayList<byte[]> permutations = new ArrayList<byte[]>();
permute(permutations, buf, 0, buf.length - 1);
for (int i = 0; i != permutations.size(); i++)
{
byte[] candidate = (byte[])permutations.get(i);
for (int k = 0; k != salts.length; k++)
{
byte[] salt = salts[k];
byte[] expected = generate(Argon2Parameters.ARGON2_VERSION_10, 1, 8, 2, rootPassword, salt, 32);
byte[] testValue = generate(Argon2Parameters.ARGON2_VERSION_10, 1, 8, 2, candidate, salt, 32);
// If the passwords are the same for the same salt we should have the same string.
boolean sameAsRoot = Arrays.areEqual(rootPassword, candidate);
isTrue("expected same result", sameAsRoot == Arrays.areEqual(expected, testValue));
}
}
}
}
}
private void swap(byte[] buf, int i, int j)
{
byte b = buf[i];
buf[i] = buf[j];
buf[j] = b;
}
private void permute(ArrayList<byte[]> permutation, byte[] a, int l, int r)
{
if (l == r)
{
permutation.add(Arrays.clone(a));
}
else
{
for (int i = l; i <= r; i++)
{
// Swapping done
swap(a, l, i);
// Recursion called
permute(permutation, a, l + 1, r);
//backtrack
swap(a, l, i);
}
}
}
private byte[] generate(int version, int iterations, int memory, int parallelism,
byte[] password, byte[] salt, int outputLength)
{
Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i)
.withVersion(version)
.withIterations(iterations)
.withMemoryPowOfTwo(memory)
.withParallelism(parallelism)
.withSalt(salt);
// Set the password.
Argon2BytesGenerator gen = new Argon2BytesGenerator();
gen.init(builder.build());
byte[] result = new byte[outputLength];
gen.generateBytes(password, result, 0, result.length);
return result;
}
private void hashTest(int version, int iterations, int memory, int parallelism,
String password, String salt, String passwordRef, int outputLength)
{
Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i)
.withVersion(version)
.withIterations(iterations)
.withMemoryPowOfTwo(memory)
.withParallelism(parallelism)
.withSalt(Strings.toByteArray(salt));
// Set the password.
Argon2BytesGenerator gen = new Argon2BytesGenerator();
gen.init(builder.build());
byte[] result = new byte[outputLength];
gen.generateBytes(password.toCharArray(), result, 0, result.length);
isTrue(passwordRef + " Failed", areEqual(result, Hex.decode(passwordRef)));
Arrays.clear(result);
// Should be able to re-use generator after successful use
gen.generateBytes(password.toCharArray(), result, 0, result.length);
isTrue(passwordRef + " Failed", areEqual(result, Hex.decode(passwordRef)));
}
private void testVectorsFromInternetDraft()
{
byte[] ad = Hex.decode("040404040404040404040404");
byte[] secret = Hex.decode("0303030303030303");
byte[] salt = Hex.decode("02020202020202020202020202020202");
byte[] password = Hex.decode("0101010101010101010101010101010101010101010101010101010101010101");
Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_d)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(3)
.withMemoryAsKB(32)
.withParallelism(4)
.withAdditional(ad)
.withSecret(secret)
.withSalt(salt);
Argon2BytesGenerator dig = new Argon2BytesGenerator();
dig.init(builder.build());
byte[] result = new byte[32];
dig.generateBytes(password, result);
isTrue("Argon 2d Failed", areEqual(result, Hex.decode("512b391b6f1162975371d30919734294f" +
"868e3be3984f3c1a13a4db9fabe4acb")));
builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_i)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(3)
.withMemoryAsKB(32)
.withParallelism(4)
.withAdditional(ad)
.withSecret(secret)
.withSalt(salt);
dig = new Argon2BytesGenerator();
dig.init(builder.build());
result = new byte[32];
dig.generateBytes(password, result);
isTrue("Argon 2i Failed", areEqual(result, Hex.decode("c814d9d1dc7f37aa13f0d77f2494bda1c8de6b016" +
"dd388d29952a4c4672b6ce8")));
builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(3)
.withMemoryAsKB(32)
.withParallelism(4)
.withAdditional(ad)
.withSecret(secret)
.withSalt(salt);
dig = new Argon2BytesGenerator();
dig.init(builder.build());
result = new byte[32];
dig.generateBytes(password, result);
isTrue("Argon 2id Failed", areEqual(result, Hex.decode("0d640df58d78766c08c037a34a8b53c9d01ef0452" +
"d75b65eb52520e96b01e659")));
}
private static int getJvmVersion()
{
String version = System.getProperty("java.specification.version");
if (null == version)
{
return -1;
}
String[] parts = version.split("\\.");
if (parts == null || parts.length < 1)
{
return -1;
}
try
{
int major = Integer.parseInt(parts[0]);
if (major == 1 && parts.length > 1)
{
return Integer.parseInt(parts[1]);
}
return major;
}
catch (NumberFormatException e)
{
return -1;
}
}
public static void main(String[] args)
{
runTest(new Argon2Test());
}
}
|
package tachyon.master;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import tachyon.Constants;
import tachyon.Pair;
import tachyon.TachyonURI;
import tachyon.TestUtils;
import tachyon.client.TachyonFS;
import tachyon.util.CommonUtils;
/**
* Local Tachyon cluster with multiple master for unit tests.
*/
public class MasterFaultToleranceTest {
private static final int BLOCK_SIZE = 30;
private static final int MASTERS = 5;
private LocalTachyonClusterMultiMaster mLocalTachyonClusterMultiMaster = null;
private TachyonFS mTfs = null;
@After
public final void after() throws Exception {
mLocalTachyonClusterMultiMaster.stop();
System.clearProperty("tachyon.user.quota.unit.bytes");
System.clearProperty("tachyon.user.default.block.size.byte");
System.clearProperty("fs.hdfs.impl.disable.cache");
}
@Before
public final void before() throws IOException {
System.setProperty("tachyon.user.quota.unit.bytes", "1000");
System.setProperty("tachyon.user.default.block.size.byte", String.valueOf(BLOCK_SIZE));
System.setProperty("fs.hdfs.impl.disable.cache", "true");
mLocalTachyonClusterMultiMaster = new LocalTachyonClusterMultiMaster(10000, MASTERS);
mLocalTachyonClusterMultiMaster.start();
mTfs = mLocalTachyonClusterMultiMaster.getClient();
}
/**
* Create 10 files in the folder
*
* @param folderName the folder name to create
* @param answer the results, the mapping from file id to file path
* @throws IOException
*/
private void faultTestDataCreation(TachyonURI folderName, List<Pair<Integer, TachyonURI>> answer)
throws IOException {
TachyonFS tfs = mLocalTachyonClusterMultiMaster.getClient();
if (!tfs.exist(folderName)) {
tfs.mkdir(folderName);
answer.add(new Pair<Integer, TachyonURI>(tfs.getFileId(folderName), folderName));
}
for (int k = 0; k < 10; k ++) {
TachyonURI path =
new TachyonURI(folderName + TachyonURI.SEPARATOR + folderName.toString().substring(1) + k);
answer.add(new Pair<Integer, TachyonURI>(tfs.createFile(path), path));
}
}
/**
* Tells if the results can match the answer
*
* @param answer the correct results
* @throws IOException
*/
private void faultTestDataCheck(List<Pair<Integer, TachyonURI>> answer) throws IOException {
TachyonFS tfs = mLocalTachyonClusterMultiMaster.getClient();
List<String> files = TestUtils.listFiles(tfs, Constants.PATH_SEPARATOR);
Assert.assertEquals(answer.size(), files.size());
for (int k = 0; k < answer.size(); k ++) {
Assert.assertEquals(answer.get(k).getSecond().toString(),
tfs.getFile(answer.get(k).getFirst()).getPath());
Assert.assertEquals(answer.get(k).getFirst().intValue(),
tfs.getFileId(answer.get(k).getSecond()));
}
}
@Test
public void faultTest() throws IOException {
int clients = 10;
List<Pair<Integer, TachyonURI>> answer = new ArrayList<Pair<Integer, TachyonURI>>();
for (int k = 0; k < clients; k ++) {
faultTestDataCreation(new TachyonURI("/data" + k), answer);
}
faultTestDataCheck(answer);
for (int kills = 0; kills < 1; kills ++) {
Assert.assertTrue(mLocalTachyonClusterMultiMaster.killLeader());
CommonUtils.sleepMs(null, Constants.SECOND_MS * 3);
faultTestDataCheck(answer);
}
for (int kills = 1; kills < MASTERS - 1; kills ++) {
Assert.assertTrue(mLocalTachyonClusterMultiMaster.killLeader());
CommonUtils.sleepMs(null, Constants.SECOND_MS * 3);
faultTestDataCheck(answer);
// TODO Add the following line back
// faultTestDataCreation("/data" + (clients + kills + 1), answer);
}
}
@Test
public void getClientsTest() throws IOException {
int clients = 10;
mTfs.createFile(new TachyonURI("/0"), 1024);
for (int k = 1; k < clients; k ++) {
TachyonFS tfs = mLocalTachyonClusterMultiMaster.getClient();
tfs.createFile(new TachyonURI(Constants.PATH_SEPARATOR + k), 1024);
}
List<String> files = TestUtils.listFiles(mTfs, Constants.PATH_SEPARATOR);
Assert.assertEquals(clients, files.size());
for (int k = 0; k < clients; k ++) {
Assert.assertEquals(Constants.PATH_SEPARATOR + k, files.get(k));
}
}
}
|
package com.cesarsk.say_it.ui;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.Voice;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.Fade;
import android.transition.Slide;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.cesarsk.say_it.NotificationReceiver;
import com.cesarsk.say_it.R;
import com.cesarsk.say_it.ui.fragments.FavoritesFragment;
import com.cesarsk.say_it.ui.fragments.HistoryFragment;
import com.cesarsk.say_it.ui.fragments.HomeFragment;
import com.cesarsk.say_it.ui.fragments.RecordingsFragment;
import com.cesarsk.say_it.utility.UtilityDictionary;
import com.cesarsk.say_it.utility.UtilityRecordings;
import com.cesarsk.say_it.utility.UtilitySharedPrefs;
import com.cesarsk.say_it.utility.utility_aidl.IabHelper;
import com.cesarsk.say_it.utility.utility_aidl.IabResult;
import com.cesarsk.say_it.utility.utility_aidl.Inventory;
import com.github.fernandodev.easyratingdialog.library.EasyRatingDialog;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnTabSelectListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Set;
import static android.speech.tts.Voice.LATENCY_VERY_LOW;
import static android.speech.tts.Voice.QUALITY_VERY_HIGH;
import static com.cesarsk.say_it.utility.LCSecurity.base64EncodedPublicKey;
public class MainActivity extends AppCompatActivity {
//Indici per la FragmentList
private final int HOME_FRAGMENT_INDEX = 0;
private final int FAVORITES_FRAGMENT_INDEX = 1;
private final int HISTORY_FRAGMENT_INDEX = 2;
private final int RECORDINGS_FRAGMENT_INDEX = 3;
//Definizione variabile TTS
public static TextToSpeech american_speaker_google;
public static TextToSpeech british_speaker_google;
public static Voice voice_american_female = new Voice("American Language", Locale.US, QUALITY_VERY_HIGH, LATENCY_VERY_LOW, false, null);
public static Voice voice_british_female = new Voice("British Language", Locale.UK, QUALITY_VERY_HIGH, LATENCY_VERY_LOW, false, null);
//Gestione preferiti, history e recordings
public static Set<String> FAVORITES = null;
public static Set<String> HISTORY = null;
public static ArrayList<File> RECORDINGS = null;
public static String DEFAULT_NOTIFICATION_RATE = null;
public static String DEFAULT_ACCENT = null;
public static String DEFAULT_NOTIFICATION_HOUR = null;
public static String DEFAULT_NOTIFICATION_MINUTE = null;
public static boolean NO_ADS = false;
//Gestione Preferenze
public final static String PREFS_NAME = "SAY_IT_PREFS"; //Nome del file delle SharedPreferences
public final static String FAVORITES_PREFS_KEY = "SAY.IT.FAVORITES"; //Chiave che identifica il Set dei favorites nelle SharedPreferences
public final static String HISTORY_PREFS_KEY = "SAY.IT.HISTORY"; //Chiave che identifica il Set della history nelle SharedPreferences
public final static String RECORDINGS_PREFS_KEY = "SAY.IT.RECORDINGS"; //Chiave che identifica il Set della lista dei Recordings
public final static String DEFAULT_ACCENT_KEY = "SAY.IT.DEFAULT.ACCENT"; //Chiave che identifica il DEFAULT ACCENT
public final static String DEFAULT_NOTIFICATION_RATE_KEY = "SAY.IT.DEFAULT.NOTIFICATION.RATE";
public final static String DEFAULT_NOTIFICATION_HOUR_KEY = "SAY.IT.DEFAULT.NOTIFICATION.HOUR";
public final static String DEFAULT_NOTIFICATION_MINUTE_KEY = "SAY.IT.DEFAULT.NOTIFICATION.MINUTE";
public final static String NO_ADS_STATUS_KEY = "SAY.IT.NO.ADS.KEY";
public final static int REQUEST_CODE = 1;
boolean doubleBackToExitPressedOnce = false;
boolean hasInterstitialDisplayed = false;
//In-App Billing Helper
IabHelper mHelper;
//Definizione variabile WordList
public static final ArrayList<String> WordList = new ArrayList<>();
public static final HashMap<String, ArrayList<Pair<String, String>>> Wordlists_Map = new HashMap<>();
public static final ArrayList<String> Quotes = new ArrayList<>();
public static String wordOfTheDay;
public static String IPAofTheDay;
//Bottom Bar variable
public static BottomBar bottomBar;
//EditText Searchbar variable
EditText editText;
ImageView lens_search_button;
ImageButton voice_search_button;
//Notification id
public static final int notifId = 150;
//Rate Dialog
EasyRatingDialog easyRatingDialog;
final FragmentManager fragmentManager = getFragmentManager();
InterstitialAd mInterstitialAd;
@Override
protected void onStop() {
super.onStop();
UtilitySharedPrefs.savePrefs(this, FAVORITES, FAVORITES_PREFS_KEY);
UtilitySharedPrefs.savePrefs(this, HISTORY, HISTORY_PREFS_KEY);
}
@Override
protected void onDestroy() {
super.onDestroy();
american_speaker_google.shutdown();
british_speaker_google.shutdown();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle b = intent.getExtras();
int value = 0; // or other values
if (b != null) {
value = b.getInt("fragment_index");
bottomBar.selectTabAtPosition(value);
} else bottomBar.selectTabAtPosition(HOME_FRAGMENT_INDEX);
}
@Override
protected void onStart() {
super.onStart();
easyRatingDialog.onStart();
}
@Override
protected void onResume() {
super.onResume();
easyRatingDialog.showIfNeeded();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
easyRatingDialog = new EasyRatingDialog(this);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id_test));
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
final IabHelper.QueryInventoryFinishedListener mGotInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
@Override
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
Toast.makeText(MainActivity.this, "Query Failed!", Toast.LENGTH_SHORT).show();
} else {
if (inventory.hasPurchase(PlayActivity.no_ads_in_app)) {
UtilitySharedPrefs.savePrefs(MainActivity.this, true, NO_ADS_STATUS_KEY);
}
}
}
};
//IAB Helper initialization
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh no, there was a problem.
Log.d("Say It!", "Problem setting up In-app Billing: " + result);
}
ArrayList<String> SKUs = new ArrayList<>();
SKUs.add(PlayActivity.no_ads_in_app);
try {
mHelper.queryInventoryAsync(SKUs, mGotInventoryListener);
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
Log.d("Say It!", "Hooray. IAB is fully set up!" + result);
}
});
//PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
//Caricamento preferenze
UtilitySharedPrefs.loadSettingsPrefs(this);
UtilitySharedPrefs.loadFavs(this);
UtilitySharedPrefs.loadHist(this);
UtilitySharedPrefs.loadAdsStatus(this);
RECORDINGS = UtilityRecordings.loadRecordingsfromStorage(this);
if (Wordlists_Map.isEmpty()) {
//Caricamento dizionario (inclusa word of the day)
try {
UtilityDictionary.loadDictionary(this);
UtilitySharedPrefs.loadQuotes(this);
int parsedHour = Integer.parseInt(DEFAULT_NOTIFICATION_HOUR);
int parsedMinute = Integer.parseInt(DEFAULT_NOTIFICATION_MINUTE);
NotificationReceiver.scheduleNotification(this, parsedHour, parsedMinute, DEFAULT_NOTIFICATION_RATE);
} catch (IOException e) {
e.printStackTrace();
}
}
//SETUP TOOLBAR
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//TODO SISTEMARE LISTENER
editText = (EditText) findViewById(R.id.search_bar_edit_text);
lens_search_button = (ImageView) findViewById(R.id.search_bar_hint_icon);
voice_search_button = (ImageButton) findViewById(R.id.search_bar_voice_icon);
View.OnClickListener search_bar_listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent search_activity_intent = new Intent(v.getContext(), SearchActivity.class);
if (v.getId() == R.id.search_bar_voice_icon)
search_activity_intent.putExtra("VOICE_SEARCH_SELECTED", true);
startActivity(search_activity_intent);
}
};
editText.setOnClickListener(search_bar_listener);
lens_search_button.setOnClickListener(search_bar_listener);
voice_search_button.setOnClickListener(search_bar_listener);
//Gestione Fragment
final ArrayList<Fragment> FragmentArrayList = new ArrayList<>();
FragmentArrayList.add(new HomeFragment());
FragmentArrayList.add(new FavoritesFragment());
FragmentArrayList.add(new HistoryFragment());
FragmentArrayList.add(new RecordingsFragment());
for (Fragment element : FragmentArrayList) {
element.setExitTransition(new Fade());
}
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, FragmentArrayList.get(HOME_FRAGMENT_INDEX));
transaction.commit();
bottomBar = (BottomBar) findViewById(R.id.bottomBar);
bottomBar.selectTabAtPosition(HOME_FRAGMENT_INDEX); //Default: Home
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
private int last_index = HOME_FRAGMENT_INDEX;
@Override
public void onTabSelected(@IdRes int tabId) {
//Creating the Fragment transaction
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (tabId) {
case R.id.tab_favorites:
if (FAVORITES_FRAGMENT_INDEX > last_index) {
FragmentArrayList.get(FAVORITES_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.RIGHT));
//transaction.setCustomAnimations(R.animator.slide_from_right, R.animator.slide_to_left);
} else if (FAVORITES_FRAGMENT_INDEX < last_index) {
FragmentArrayList.get(FAVORITES_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.LEFT));
//transaction.setCustomAnimations(R.animator.slide_from_left, R.animator.slide_to_right);
}
transaction.replace(R.id.fragment_container, FragmentArrayList.get(FAVORITES_FRAGMENT_INDEX));
last_index = FAVORITES_FRAGMENT_INDEX;
break;
case R.id.tab_home:
if (HOME_FRAGMENT_INDEX > last_index) {
FragmentArrayList.get(HOME_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.RIGHT));
//transaction.setCustomAnimations(R.animator.slide_from_right, R.animator.slide_to_left);
} else if (HOME_FRAGMENT_INDEX < last_index) {
FragmentArrayList.get(HOME_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.LEFT));
//transaction.setCustomAnimations(R.animator.slide_from_left, R.animator.slide_to_right);
}
transaction.replace(R.id.fragment_container, FragmentArrayList.get(HOME_FRAGMENT_INDEX));
last_index = HOME_FRAGMENT_INDEX;
break;
case R.id.tab_history:
if (HISTORY_FRAGMENT_INDEX > last_index) {
FragmentArrayList.get(HISTORY_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.RIGHT));
//transaction.setCustomAnimations(R.animator.slide_from_right, R.animator.slide_to_left);
} else if (HISTORY_FRAGMENT_INDEX < last_index) {
FragmentArrayList.get(HISTORY_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.LEFT));
//transaction.setCustomAnimations(R.animator.slide_from_left, R.animator.slide_to_right);
}
transaction.replace(R.id.fragment_container, FragmentArrayList.get(HISTORY_FRAGMENT_INDEX));
last_index = HISTORY_FRAGMENT_INDEX;
break;
case R.id.tab_recordings:
if (RECORDINGS_FRAGMENT_INDEX > last_index) {
FragmentArrayList.get(RECORDINGS_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.RIGHT));
//transaction.setCustomAnimations(R.animator.slide_from_right, R.animator.slide_to_left);
} else if (RECORDINGS_FRAGMENT_INDEX < last_index) {
FragmentArrayList.get(RECORDINGS_FRAGMENT_INDEX).setEnterTransition(new Slide(Gravity.LEFT));
//transaction.setCustomAnimations(R.animator.slide_from_left, R.animator.slide_to_right);
}
transaction.replace(R.id.fragment_container, FragmentArrayList.get(RECORDINGS_FRAGMENT_INDEX));
last_index = RECORDINGS_FRAGMENT_INDEX;
break;
}
transaction.commit();
}
});
//IMPOSTAZIONE TEXT TO SPEECH
american_speaker_google = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO OTTIMIZZARE TTS
if (status == TextToSpeech.SUCCESS) {
//Ridondante?
american_speaker_google.setPitch((float) 0.90);
american_speaker_google.setSpeechRate((float) 0.90);
american_speaker_google.setVoice(voice_american_female);
} else
Log.e("error", "Initilization Failed!");
}
});
british_speaker_google = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO OTTIMIZZARE TTS
if (status == TextToSpeech.SUCCESS) {
//Ridondante?
british_speaker_google.setPitch((float) 0.90);
british_speaker_google.setSpeechRate((float) 0.90);
british_speaker_google.setVoice(voice_british_female);
} else
Log.e("error", "Initilization Failed!");
}
});
}
@Override
public void onBackPressed() {
if (mInterstitialAd.isLoaded() && !hasInterstitialDisplayed) {
mInterstitialAd.show();
hasInterstitialDisplayed = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
hasInterstitialDisplayed = false;
}
}, 60000);
} else {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Click Back again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().addTestDevice(getResources().getString(R.string.test_device_oneplus_3)).build();
mInterstitialAd.loadAd(adRequest);
}
}
|
package de.longri.cachebox3.sqlite.dao;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import de.longri.cachebox3.TestUtils;
import de.longri.cachebox3.sqlite.Database;
import de.longri.cachebox3.types.AbstractWaypoint;
import de.longri.cachebox3.types.CacheTypes;
import de.longri.cachebox3.types.ImmutableWaypoint;
import de.longri.cachebox3.types.MutableWaypoint;
import de.longri.gdx.sqlite.GdxSqliteCursor;
import de.longri.gdx.sqlite.SQLiteGdxException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
class Waypoint3DAOTest {
static FileHandle testDbFileHandle;
static FileHandle copyDbFileHandle;
static Database cb3Database;
@BeforeAll
static void beforeAll() throws SQLiteGdxException {
TestUtils.initialGdx();
// copy testDb
testDbFileHandle = TestUtils.getResourceFileHandle("testsResources/Database/testACB2.db3");
copyDbFileHandle = testDbFileHandle.parent().child("testWaypointDAO.db3");
if (copyDbFileHandle.exists()) {
// delete first
assertThat("TestDB must be deleted for cleanup", copyDbFileHandle.delete());
}
testDbFileHandle.copyTo(copyDbFileHandle);
assertThat("TestDB must exist", copyDbFileHandle.exists());
// open DataBase
cb3Database = new Database(Database.DatabaseType.CacheBox3);
cb3Database.startUp(copyDbFileHandle);
}
@AfterAll
static void cleanUpRecources() {
cb3Database.close();
assertThat("TestDB must be deleted after cleanup", copyDbFileHandle.delete());
}
@Test
void getWaypointsFromCacheID() {
Waypoint3DAO dao = new Waypoint3DAO();
Array<AbstractWaypoint> waypoints = dao.getWaypointsFromCacheID(cb3Database, null, true);
assertThat("TestDB must have 282 Waypoints but has:" + waypoints.size, waypoints.size == 282);
waypoints = dao.getWaypointsFromCacheID(cb3Database, 20919627218633543L, true);
assertThat("TestDB must have 6 Waypoints but has:" + waypoints.size, waypoints.size == 6);
AbstractWaypoint wp = waypoints.get(1);
assertThat("Waypoint.GcCode must be 'S23EJRJ' but was: '" + wp.getGcCode() + "'", wp.getGcCode().equals("S23EJRJ"));
assertThat("Waypoint.Latitude must be '52.507768' but was: '" + TestUtils.roundDoubleCoordinate(wp.getLatitude()) + "'", TestUtils.roundDoubleCoordinate(wp.getLatitude()) == 52.507768);
assertThat("Waypoint.Longitude must be '13.465333' but was: '" + TestUtils.roundDoubleCoordinate(wp.getLongitude()) + "'", TestUtils.roundDoubleCoordinate(wp.getLongitude()) == 13.465333);
assertThat("Waypoint.Type must be 'Question to Answer' but was: '" + wp.getType() + "'", wp.getType() == CacheTypes.MultiQuestion);
assertThat("Waypoint.Start must be 'false' but was: '" + wp.isStart() + "'", !wp.isStart());
assertThat("Waypoint.SyncExcluded must be 'false' but was: '" + wp.isSyncExcluded() + "'", !wp.isSyncExcluded());
assertThat("Waypoint.UserWaypoint must be 'false' but was: '" + wp.isUserWaypoint() + "'", !wp.isUserWaypoint());
assertThat("Waypoint.Title must be 'Stage 2' but was: '" + wp.getTitle() + "'", wp.getTitle().equals("Stage 2"));
assertThat("Waypoint.Description must be 'Wohin geht der Mann im Hauseingang Nr. 9? Der erste Buchstabe wird gesucht' but was: '" + wp.getDescription(cb3Database) + "'", wp.getDescription(cb3Database).equals("Wohin geht der Mann im Hauseingang Nr. 9? Der erste Buchstabe wird gesucht"));
assertThat("Waypoint.Clue must be '' but was: '" + wp.getClue(cb3Database) + "'", wp.getClue(cb3Database).equals(""));
}
@Test
void exceptionThrowing() {
//ImmutableWaypoint class must throw a Exception with set properties
AbstractWaypoint wp = new ImmutableWaypoint(should_Latitude, should_Longitude);
boolean hasThrowed = false;
try {
wp.setCacheId(should_cacheId);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set CacheID must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setLatLon(should_Latitude, should_Longitude);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set LatLon must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setGcCode(should_GcCode);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set GcCode must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setTitle(should_Title);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set Title must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setType(should_Type);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set Type must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setStart(should_isStart);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set Start must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setSyncExcluded(should_syncExclude);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set SyncExclude must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setUserWaypoint(should_userWaypoint);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set UserWaypoint must throw a RuntimeException", hasThrowed);
}
hasThrowed = false;
try {
wp.setUserWaypoint(should_userWaypoint);
} catch (Exception e) {
hasThrowed = true;
} finally {
assertThat("Set UserWaypoint must throw a RuntimeException", hasThrowed);
}
}
private final double should_Latitude = 53.123;
private final double should_Longitude = 13.456;
private final long should_cacheId = 1234567890L;
private final String should_GcCode = "GCCCCCX";
private final String should_Title = "Waypoint-Title";
private final CacheTypes should_Type = CacheTypes.MultiQuestion;
private final boolean should_isStart = true;
private final boolean should_syncExclude = true;
private final boolean should_userWaypoint = true;
private final String should_Description = " Waypoint description";
private final String should_Clue = " Waypoint clue";
private final double should2_Latitude = 53.456;
private final double should2_Longitude = 13.789;
private final String should2_Title = "Waypoint-Title Updated";
private final CacheTypes should2_Type = CacheTypes.CITO;
private final boolean should2_isStart = false;
private final boolean should2_syncExclude = false;
private final boolean should2_userWaypoint = false;
private final String should2_Description = " Waypoint updated description";
private final String should2_Clue = " Waypoint updated clue";
@Test
void writeToDatabase() {
//1. write new wp to DB
//2. update wp
//3. delete wp
AbstractWaypoint wp = new MutableWaypoint(0, 0, should_cacheId);
wp.setLatLon(should_Latitude, should_Longitude);
wp.setGcCode(should_GcCode);
wp.setTitle(should_Title);
wp.setType(should_Type);
wp.setStart(should_isStart);
wp.setSyncExcluded(should_syncExclude);
wp.setUserWaypoint(should_userWaypoint);
wp.setDescription(should_Description);
wp.setClue(should_Clue);
assertWp("MutableWaypoint", wp);
Waypoint3DAO DAO = new Waypoint3DAO();
DAO.writeToDatabase(cb3Database, wp);
Array<AbstractWaypoint> waypoints = DAO.getWaypointsFromCacheID(cb3Database, should_cacheId, true);
AbstractWaypoint wp2 = waypoints.get(0);
assertWp("StoredWaypoint", wp2);
if (!wp2.isMutable()) {
wp2 = wp2.getMutable(cb3Database);
}
wp2.setLatLon(should2_Latitude, should2_Longitude);
wp2.setTitle(should2_Title);
wp2.setType(should2_Type);
wp2.setStart(should2_isStart);
wp2.setSyncExcluded(should2_syncExclude);
wp2.setUserWaypoint(should2_userWaypoint);
wp2.setDescription(should2_Description);
wp2.setClue(should2_Clue);
assertWp2("ChangedWaypoint", wp2);
DAO.updateDatabase(cb3Database, wp2);
Array<AbstractWaypoint> waypoints2 = DAO.getWaypointsFromCacheID(cb3Database, should_cacheId, true);
AbstractWaypoint wp3 = waypoints2.get(0);
assertWp2("updatedWaypoint", wp3);
DAO.delete(cb3Database, wp3);
Array<AbstractWaypoint> waypoints3 = DAO.getWaypointsFromCacheID(cb3Database, should_cacheId, true);
assertThat("Waypoint list must be empty", waypoints3.size == 0);
//check is also deleted from WaypointsText table
GdxSqliteCursor cursor = cb3Database.rawQuery("SELECT * FROM WaypointsText WHERE GcCode='GCCCCCX'",(String[]) null);
if (cursor!=null) {
cursor.moveToFirst();
assertThat("Waypoint must also deleted from WaypointsText table", cursor.isAfterLast());
}
}
private void assertWp(String msg, AbstractWaypoint wp) {
assertThat(msg + " Id must equals", wp.getCacheId() == should_cacheId);
assertThat(msg + " Latitude must equals", TestUtils.roundDoubleCoordinate(wp.getLatitude()) == should_Latitude);
assertThat(msg + " Longitude must equals", TestUtils.roundDoubleCoordinate(wp.getLongitude()) == should_Longitude);
assertThat(msg + " GcCode must equals", wp.getGcCode().equals(should_GcCode));
assertThat(msg + " Type must equals", wp.getType() == should_Type);
assertThat(msg + " IsStart must equals", wp.isStart() == should_isStart);
assertThat(msg + " SyncExclude must equals", wp.isSyncExcluded() == should_syncExclude);
assertThat(msg + " IsUserWaypoint must equals", wp.isUserWaypoint() == should_userWaypoint);
assertThat(msg + " Title must equals", wp.getTitle().equals(should_Title));
assertThat(msg + " Description must equals", wp.getDescription(cb3Database).equals(should_Description));
assertThat(msg + " Clue must equals", wp.getClue(cb3Database).equals(should_Clue));
}
private void assertWp2(String msg, AbstractWaypoint wp) {
assertThat(msg + " Id must equals", wp.getCacheId() == should_cacheId);
assertThat(msg + " Latitude must equals", TestUtils.roundDoubleCoordinate(wp.getLatitude()) == should2_Latitude);
assertThat(msg + " Longitude must equals", TestUtils.roundDoubleCoordinate(wp.getLongitude()) == should2_Longitude);
assertThat(msg + " GcCode must equals", wp.getGcCode().equals(should_GcCode));
assertThat(msg + " Type must equals", wp.getType() == should2_Type);
assertThat(msg + " IsStart must equals", wp.isStart() == should2_isStart);
assertThat(msg + " SyncExclude must equals", wp.isSyncExcluded() == should2_syncExclude);
assertThat(msg + " IsUserWaypoint must equals", wp.isUserWaypoint() == should2_userWaypoint);
assertThat(msg + " Title must equals", wp.getTitle().equals(should2_Title));
assertThat(msg + " Description must equals", wp.getDescription(cb3Database).equals(should2_Description));
assertThat(msg + " Clue must equals", wp.getClue(cb3Database).equals(should2_Clue));
}
@Test
void resetStartWaypoint() {
}
}
|
package com.diusrex.tictactoe;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import com.diusrex.tictactoe.box_images.BoxImageResourceInfo;
import com.diusrex.tictactoe.box_images.LargeMove;
import com.diusrex.tictactoe.box_images.LargeMoveMostRecent;
import com.diusrex.tictactoe.box_images.MostRecentMove;
import com.diusrex.tictactoe.box_images.RegularMove;
import com.diusrex.tictactoe.dialogs.WinDialogActivityListener;
import com.diusrex.tictactoe.dialogs.WinDialogFragment;
import com.diusrex.tictactoe.logic.BoardStatus;
import com.diusrex.tictactoe.logic.BoxPosition;
import com.diusrex.tictactoe.logic.Move;
import com.diusrex.tictactoe.logic.Player;
import com.diusrex.tictactoe.logic.SectionPosition;
import com.diusrex.tictactoe.logic.TicTacToeEngine;
import com.diusrex.tictactoe.logic.UndoAction;
import java.util.Calendar;
public class GameActivity extends Activity implements GameEventHandler, WinDialogActivityListener {
static public final String IS_NEW_GAME = "IsNewGame";
static private final long COOLDOWN = 250;
BoardStatus board;
Player currentPlayer;
BoardStateSaverAndLoader saverAndLoader;
SectionPosition currentSelectedSection;
MainGridOwner mainGridOwner;
SectionOwner mainSection;
BoxImageResourceInfo regularBox;
BoxImageResourceInfo mostRecentBox;
BoxImageResourceInfo largeBox;
BoxImageResourceInfo largeBoxMostRecent;
long previousTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
saverAndLoader = new BoardStateSaverAndLoader(this);
regularBox = new RegularMove();
mostRecentBox = new MostRecentMove();
largeBox = new LargeMove();
largeBoxMostRecent = new LargeMoveMostRecent();
MyGrid mainGrid = (MyGrid) findViewById(R.id.mainGrid);
mainGridOwner = new MainGridOwner(this, this, mainGrid);
boolean newGame = getIntent().getBooleanExtra(IS_NEW_GAME, true);
if (newGame) {
saverAndLoader.resetBoardState();
// Make sure it does not try this again
getIntent().putExtra(IS_NEW_GAME, false);
}
}
@Override
protected void onResume() {
super.onResume();
board = saverAndLoader.loadBoard();
updateCurrentPlayer();
redrawBoard();
SectionPosition selectedSection = saverAndLoader.loadSelectedSection(board);
if (!winnerExists()) {
prepareForNextMove(getCurrentTime(), selectedSection);
} else {
// Will now reshow the win dialog if there is a winner
disablePerformingMove();
sectionSelected(selectedSection);
}
}
private void updateCurrentPlayer() {
currentPlayer = TicTacToeEngine.getNextPlayer(board);
}
private void redrawBoard() {
GridOrganizer.populateGrid(this, board, mainGridOwner, regularBox);
updateMostRecentBox();
}
@Override
protected void onPause() {
super.onPause();
saverAndLoader.saveGameState(board, currentSelectedSection);
}
@Override
public void boxSelected(BoxPosition position) {
Move move = new Move(position, currentPlayer);
long currentTime = getCurrentTime();
if (TicTacToeEngine.isValidMove(board, move) && currentTime - previousTime > COOLDOWN) {
changeMostRecentMoveToRegular();
TicTacToeEngine.applyMoveIfValid(board, move);
mainGridOwner.updateBoxValue(board, position, mostRecentBox);
handleWinOrPrepareForNextMove(position, currentTime);
}
}
private void changeMostRecentMoveToRegular() {
Move mostRecent = TicTacToeEngine.getMostRecentMoveOrNull(board);
if (mostRecent != null) {
mainGridOwner.updateBoxValue(board, mostRecent.getPosition(), regularBox);
}
}
private void handleWinOrPrepareForNextMove(BoxPosition position, long currentTime) {
if (winnerExists()) {
handleWin(position);
} else {
prepareForNextMove(currentTime, board.getSectionToPlayIn());
}
}
private boolean winnerExists() {
return TicTacToeEngine.getWinner(board) != Player.Unowned;
}
private void prepareForNextMove(long currentTime, SectionPosition selectedSection) {
updateCurrentPlayer();
sectionSelected(selectedSection);
updateSectionToPlayIn();
previousTime = currentTime;
}
private void updateSectionToPlayIn() {
mainGridOwner.selectionToPlayInChanged(board.getSectionToPlayIn());
}
private void handleWin(BoxPosition position) {
mainGridOwner.updateWinLine(board);
sectionSelected(position.getSectionIn());
String winningPlayer = getPlayerAsString();
disablePerformingMove();
showWinDialog(winningPlayer);
}
private void disablePerformingMove() {
// Will not allow the player unowned to play
currentPlayer = Player.Unowned;
// There is no section to play into
mainGridOwner.selectionToPlayInChanged(SectionPosition.make(-1, -1));
}
private void showWinDialog(String winningPlayer) {
DialogFragment fragment = WinDialogFragment.newInstance(winningPlayer);
fragment.show(getFragmentManager(), "dialog");
}
@Override
public void sectionSelected(SectionPosition section) {
currentSelectedSection = section;
populateSelectedSection(section);
mainGridOwner.selectionSelectedChanged(section);
}
private void populateSelectedSection(SectionPosition section) {
MyGrid selectedSectionGrid = (MyGrid) findViewById(R.id.selectedSection);
mainSection = new SelectedSectionOwner(section, selectedSectionGrid, this);
GridOrganizer.populateGrid(this, board, mainSection, largeBox);
updateSelectedSectionMostRecent(section);
}
private void updateSelectedSectionMostRecent(SectionPosition section) {
Move mostRecentMove = TicTacToeEngine.getMostRecentMoveOrNull(board);
if (mostRecentMove == null)
return;
SectionPosition mostRecentMoveSection = mostRecentMove.getSectionIn();
if (mostRecentMoveSection.equals(section)) {
mainSection.updateBoxValue(board, mostRecentMove.getPosition(), largeBoxMostRecent);
}
}
private long getCurrentTime() {
Calendar c = Calendar.getInstance();
return c.getTimeInMillis();
}
public void undoMove(View v) {
if (canUndoLastMove()) {
Move lastMove = board.getAllMoves().peek();
UndoAction.undoLastMove(board);
prepareForNextMove(getCurrentTime(), board.getSectionToPlayIn());
mainGridOwner.updateBoxValue(board, lastMove.getPosition(), regularBox);
mainGridOwner.updateWinLine(board);
updateMostRecentBox();
}
}
private String getPlayerAsString() {
switch (currentPlayer) {
case Player_1:
return getString(R.string.player_1);
case Player_2:
return getString(R.string.player_2);
default:
return getString(R.string.no_player);
}
}
private boolean canUndoLastMove() {
return board.getAllMoves().size() != 0;
}
private void updateMostRecentBox() {
Move mostRecent = TicTacToeEngine.getMostRecentMoveOrNull(board);
if (mostRecent != null) {
mainGridOwner.updateBoxValue(board, mostRecent.getPosition(), mostRecentBox);
}
}
@Override
public void returnToMainMenu() {
// Need to reset these because they are what will be saved
board = new BoardStatus();
currentSelectedSection = board.getSectionToPlayIn();
finish();
}
@Override
public void returnToGame() {
// Nothing needs to be done here
}
@Override
public void runNewGame() {
board = new BoardStatus();
redrawBoard();
SectionPosition selectedSection = board.getSectionToPlayIn();
prepareForNextMove(getCurrentTime(), selectedSection);
}
}
|
package beginner;
import com.sandwich.koan.Koan;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
public class AboutConditionals {
@Koan
public void basicIfWithoutCurly(){
// Ifs without curly braces are ugly and not recommended but still valid:
int x = 1;
if (true)
x++;
assertEquals(x, 2);
}
@Koan
public void basicIfElseWithoutCurly(){
// Ifs without curly braces are ugly and not recommended but still valid:
int x = 1;
boolean secretBoolean = false;
if (secretBoolean)
x++;
else
x
assertEquals(x, 0);
}
@Koan
public void basicIfElseIfElseWithoutCurly(){
int x = 1;
boolean secretBoolean = false;
boolean otherBooleanCondition = true;
// Ifs without curly braces are ugly and not recommended but still valid:
if (secretBoolean)
x++;
else if (otherBooleanCondition)
x = 10;
else
x
assertEquals(x, 10);
}
@Koan
public void nestedIfsWithoutCurlysAreReallyMisleading() {
// Why are these ugly you ask? Well, try for yourself
int x = 1;
boolean secretBoolean = false;
boolean otherBooleanCondition = true;
// Ifs without curly braces are ugly and not recommended but still valid:
if (secretBoolean) x++;
if (otherBooleanCondition) x = 10;
else x
// Where does this else belong to!?
assertEquals(x, 10);
}
@Koan
public void ifAsIntended() {
boolean secretBoolean = true;
int x = 1;
if (secretBoolean) {
x++;
} else {
x = 0;
}
// There are different opinions on where the curly braces go...
// But as long as you put them here. You avoid problems as seen above.
assertEquals(x, 2);
}
@Koan
public void basicSwitchStatement() {
int i = 1;
String result = "Basic ";
switch(i) {
case 1:
result += "One";
break;
case 2:
result += "Two";
break;
default:
result += "Nothing";
}
assertEquals(result, "Basic One");
}
@Koan
public void switchStatementFallThrough() {
int i = 1;
String result = "Basic ";
switch(i) {
case 1:
result += "One";
case 2:
result += "Two";
default:
result += "Nothing";
}
assertEquals(result, "Basic OneTwoNothing");
}
@Koan
public void switchStatementCrazyFallThrough() {
int i = 5;
String result = "Basic ";
switch(i) {
case 1:
result += "One";
default:
result += "Nothing";
case 2:
result += "Two";
}
assertEquals(result, "Basic NothingTwo");
}
@Koan
public void switchStatementConstants() {
int i = 5;
// What happens if you remove the 'final' modifier?
// What does this mean for case values?
final int caseOne = 1;
String result = "Basic ";
switch(i) {
case caseOne:
result += "One";
break;
default:
result += "Nothing";
}
assertEquals(result, "Basic Nothing");
}
@Koan
public void switchStatementSwitchValues() {
// Try different (primitive) types for 'c'
// Which types do compile?
// Does boxing work?
byte c = 'a';
String result = "Basic ";
switch(c) {
case 'a':
result += "One";
break;
default:
result += "Nothing";
}
assertEquals(result, "Basic One");
}
}
|
package de.longri.cachebox3.utils.lists;
import com.badlogic.gdx.utils.StringBuilder;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
class ThreadStackTest {
class TestCancelRunnable implements CancelRunable {
private final StringBuilder stringBuilder;
private final String name;
private boolean cancel = false;
TestCancelRunnable(StringBuilder stringBuilder, String name) {
this.stringBuilder = stringBuilder;
this.name = name;
}
@Override
public void cancel() {
cancel = true;
}
@Override
public void run() {
stringBuilder.append("Start Runnable " + name + "\n");
int count = 0;
while (!cancel && count < 20) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
if (count < 20) {
stringBuilder.append("Cancel Runnable " + name + "\n");
stringBuilder.append("\n");
} else {
stringBuilder.append("Finish Runnable " + name + "\n");
stringBuilder.append("\n");
}
}
}
@Test
void ConstructorTest() {
ThreadStack<TestCancelRunnable> runnables = new ThreadStack<TestCancelRunnable>();
assertThat("Must constructable", runnables != null);
assertThat("Max item size must be 1", runnables.getMaxItemSize() == 1);
runnables.dispose();
ThreadStack<TestCancelRunnable> limetedRunnables = new ThreadStack<TestCancelRunnable>(10);
assertThat("Must constructable", limetedRunnables != null);
assertThat("Max item size must be 10", limetedRunnables.getMaxItemSize() == 10);
limetedRunnables.dispose();
}
@Test
void runTest() {
StringBuilder stringBuilder = new StringBuilder();
ThreadStack<TestCancelRunnable> runnables = new ThreadStack<TestCancelRunnable>();
TestCancelRunnable runnable = new TestCancelRunnable(stringBuilder, "SingleRunnable");
runnables.pushAndStart(runnable);
sleep(1000);
//wait for ready with work
int testCount = 0;
while (!runnables.isReadyAndEmpty()) {
sleep(10);
testCount++;
}
System.out.println("TestCount:" + testCount);
System.out.print(stringBuilder.toString());
System.out.flush();
StringBuilder testStringBuilder = new StringBuilder();
testStringBuilder.append("Start Runnable SingleRunnable\n");
testStringBuilder.append("Finish Runnable SingleRunnable\n\n");
assertThat("Threat must start and finish", testStringBuilder.equals(stringBuilder));
}
@Test()
void runTest2() {
StringBuilder stringBuilder = new StringBuilder();
ThreadStack<TestCancelRunnable> runnables = new ThreadStack<TestCancelRunnable>();
TestCancelRunnable runnable1 = new TestCancelRunnable(stringBuilder, "Runnable 1");
TestCancelRunnable runnable2 = new TestCancelRunnable(stringBuilder, "Runnable 2");
TestCancelRunnable runnable3 = new TestCancelRunnable(stringBuilder, "Runnable 3");
runnables.pushAndStart(runnable1);
sleep(5);
runnables.pushAndStart(runnable2);
sleep(5);
runnables.pushAndStart(runnable3);
sleep(1000);
//wait for ready with work
int testCount = 0;
while (!runnables.isReadyAndEmpty()) {
sleep(10);
testCount++;
}
System.out.println("TestCount:" + testCount);
System.out.print(stringBuilder.toString());
System.out.flush();
StringBuilder testStringBuilder = new StringBuilder();
testStringBuilder.append("Start Runnable Runnable 1\n");
testStringBuilder.append("Finish Runnable Runnable 1\n\n");
testStringBuilder.append("Start Runnable Runnable 3\n");
testStringBuilder.append("Finish Runnable Runnable 3\n\n");
assertThat("Runnable1 mast start and finish before Runnable3," +
" Runnable2 must ignored", testStringBuilder.equals(stringBuilder));
}
@Test()
void runTest3() {
StringBuilder stringBuilder = new StringBuilder();
ThreadStack<TestCancelRunnable> runnables = new ThreadStack<TestCancelRunnable>();
TestCancelRunnable runnable1 = new TestCancelRunnable(stringBuilder, "Runnable 1");
TestCancelRunnable runnable2 = new TestCancelRunnable(stringBuilder, "Runnable 2");
TestCancelRunnable runnable3 = new TestCancelRunnable(stringBuilder, "Runnable 3");
TestCancelRunnable runnable4 = new TestCancelRunnable(stringBuilder, "Runnable 4");
TestCancelRunnable runnable5 = new TestCancelRunnable(stringBuilder, "Runnable 5");
runnables.pushAndStart(runnable1);
sleep(10);
runnables.pushAndStart(runnable2);
sleep(10);
runnables.pushAndStart(runnable3);
sleep(100);
runnables.pushAndStart(runnable4);
sleep(10);
runnables.pushAndStart(runnable5);
sleep(1000);
//wait for ready with work
int testCount = 0;
while (!runnables.isReadyAndEmpty()) {
sleep(10);
testCount++;
}
System.out.println("TestCount:" + testCount);
System.out.print(stringBuilder.toString());
System.out.flush();
StringBuilder testStringBuilder = new StringBuilder();
testStringBuilder.append("Start Runnable Runnable 1\n");
testStringBuilder.append("Finish Runnable Runnable 1\n\n");
testStringBuilder.append("Start Runnable Runnable 3\n");
testStringBuilder.append("Finish Runnable Runnable 3\n\n");
testStringBuilder.append("Start Runnable Runnable 4\n");
testStringBuilder.append("Finish Runnable Runnable 4\n\n");
testStringBuilder.append("Start Runnable Runnable 5\n");
testStringBuilder.append("Finish Runnable Runnable 5\n\n");
assertThat("Runnable1 mast start and finish before Runnable3," +
" Runnable2 must ignored", testStringBuilder.equals(stringBuilder));
}
@Test()
void runTestwithCancel() {
StringBuilder stringBuilder = new StringBuilder();
ThreadStack<TestCancelRunnable> runnables = new ThreadStack<TestCancelRunnable>();
TestCancelRunnable runnable1 = new TestCancelRunnable(stringBuilder, "Runnable 1");
TestCancelRunnable runnable2 = new TestCancelRunnable(stringBuilder, "Runnable 2");
TestCancelRunnable runnable3 = new TestCancelRunnable(stringBuilder, "Runnable 3");
TestCancelRunnable runnable4 = new TestCancelRunnable(stringBuilder, "Runnable 4");
TestCancelRunnable runnable5 = new TestCancelRunnable(stringBuilder, "Runnable 5");
runnables.pushAndStartWithCancelRunning(runnable1);
sleep(20);
runnables.pushAndStartWithCancelRunning(runnable2);
sleep(20);
runnables.pushAndStartWithCancelRunning(runnable3);
sleep(100);
runnables.pushAndStartWithCancelRunning(runnable4);
sleep(20);
runnables.pushAndStartWithCancelRunning(runnable5);
sleep(1000);
//wait for ready with work
int testCount = 0;
while (!runnables.isReadyAndEmpty()) {
sleep(10);
testCount++;
}
System.out.println("TestCount:" + testCount);
System.out.print(stringBuilder.toString());
System.out.flush();
StringBuilder testStringBuilder = new StringBuilder();
testStringBuilder.append("Start Runnable Runnable 1\n");
testStringBuilder.append("Cancel Runnable Runnable 1\n\n");
testStringBuilder.append("Start Runnable Runnable 2\n");
testStringBuilder.append("Cancel Runnable Runnable 2\n\n");
testStringBuilder.append("Start Runnable Runnable 3\n");
testStringBuilder.append("Finish Runnable Runnable 3\n\n");
testStringBuilder.append("Start Runnable Runnable 4\n");
testStringBuilder.append("Cancel Runnable Runnable 4\n\n");
testStringBuilder.append("Start Runnable Runnable 5\n");
testStringBuilder.append("Finish Runnable Runnable 5\n\n");
assertThat("Runnable1 mast start and finish before Runnable3," +
" Runnable2 must ignored", testStringBuilder.equals(stringBuilder));
}
private void sleep(int value) {
try {
Thread.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package fr.esiea.CanadianLumberjack;
import java.io.File;
/**
* Configuration Class
*
*/
public class Configuration {
/**
* Constructor with default values
* Default parameters are:
* For every class, errorlevel <code>ERROR</code>, target <code>TargetConsole</code>
*
*/
public Configuration(){
}
/**
* Uses the configuration specified in the properties file in parameter
*
* DOCUMENTATION DU FICHIER PROPERTIES :
* faire
*
* @param configFile
*/
public Configuration(File configFile)/* throws FileException, BadConfigException */{
/* A DEFINIR */
/* le fileexception est redfinir (il faut jeter une exception s'il y a un souci avec le fichier)
* et le badconfigexceptin est crer */
}
/**
* Add a target to a class
* Using it for the first time crushed the default value
*
* @param classe
* @param cible
*/
public void ajouterCible(Class classe, Target cible){
/* A DEFINIR */
}
}
|
package com.example.lit.saving;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* The DataHandler class is to be used to save an object for longtime storage.
* This object should be used for a single object or a collection of the same type
* of objects.
* Objects that are not the same type should be separated into two different
* DataHandler objects and as such two different files.
*
* @author Riley Dixon
*/
//TODO: BONUS, upgrade to java.nio.files.Files and introduce file locking
//The above TO DO is just a bonus and should be used to ensure
//file consistency but ensuring that there is only one writer or reader
// at a time.
public class DataHandler<T> {
private long lastOfflineSave;
private long lastOnlineSave;
private String FILENAME;
/**
* Builds a handler that is used to save data to both local storage for offline use as
* well as online via ElasticSearch.
*
* @param username What the username of the current logged in user is.
* This is required to give a cleaner file hierarchy.
* @param savedObject What object is currently being saved? Is this HabitList or
* HabitHistory for example.
* @param context The context of the activity. In most cases when constructing
* the object this parameter is "this".
* TODO: Fix Javadoc to clarify that the below parameter is the generic T and no longer a parameter
* @param typeOfDataBeingStored The type of data being stored. As arrayList's
* are being used and we cannot confirm what the
* type of the arrayList is at runtime due to Java's
* type erasure of generics at runtime, the type of
* arrayList being passed MUST be passed explicitly.
* See the GSON Javadoc for how to generate the Type
* object to pass to this constructor.
*
* @see Gson
*/
DataHandler(String username, String savedObject, Context context){
this.FILENAME = context.getFilesDir().getAbsolutePath() + File.separator
+ username;
File filePath = new File(FILENAME);
//Check if the subdirectory has been created yet or not
//Create subdirectory if it hasn't been created yet.
if(!filePath.exists()){
filePath.mkdirs();
}
FILENAME += File.separator + savedObject + ".sav";
}
public void saveArrayList(ArrayList<T> arrayListToBeSaved){
long currentTime = System.currentTimeMillis();
try{
saveArrayToOffline(arrayListToBeSaved);
lastOfflineSave = currentTime;
}catch (IOException e) {
throw new RuntimeException();
}
//TODO: Online part
}
public void saveSingularElement(T element){
long currentTime = System.currentTimeMillis();
try{
saveSingularElementToOffline(element);
lastOfflineSave = currentTime;
}catch (IOException e){
throw new RuntimeException();
}
//TODO: Online part
}
public ArrayList<T> loadArrayList(){
long currentTime = System.currentTimeMillis();
ArrayList<T> loadedList;
//TODO: Compare offline and online file, then decide which file to load from
//TODO: If the files timestamps are different, sync with the newer file
try{
loadedList = loadArrayFromOffline();
}catch (IOException e){
throw new RuntimeException();
}
return loadedList;
}
public T loadSingularElement(){
long currentTime = System.currentTimeMillis();
T loadedElement;
//TODO: Compare offline and online file, then decide which file to load from
//TODO: If the files timestamps are different, sync with the newer file
try{
loadedElement = loadSingularElementFromOffline();
}catch (IOException e){
throw new RuntimeException();
}
return loadedElement;
}
private void saveArrayToOffline(ArrayList<T> arrayListToSave)throws IOException{
FileOutputStream fos = new FileOutputStream(new File(FILENAME));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
Type typeOfArrayList = new TypeToken<ArrayList<T>>(){}.getType();
//Write to the stream.
Gson gson = new Gson();
gson.toJson(arrayListToSave, typeOfArrayList, out); //OBJECT, TYPE, APPENDABLE
//Close the writing stream.
out.flush();
fos.close();
}
private void saveArrayToOnline(){
}
private void saveSingularElementToOffline(T singleElementToSave) throws IOException{
FileOutputStream fos = new FileOutputStream(new File(FILENAME));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
Type typeOfElement = new TypeToken<T>(){}.getType();
//Write to the stream.
Gson gson = new Gson();
gson.toJson(singleElementToSave, typeOfElement, out); //OBJECT, TYPE, APPENDABLE
//Close the writing stream.
out.flush();
fos.close();
}
private void saveSingularElementToOnline(){
}
private ArrayList<T> loadArrayFromOffline() throws IOException{
ArrayList<T> loadedList;
try {
FileInputStream fis = new FileInputStream(new File(FILENAME));
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
Type typeOfArrayList = new TypeToken<ArrayList<T>>(){}.getType();
//Read from the stream
Gson gson = new Gson();
loadedList = gson.fromJson(in, typeOfArrayList);
//Close the stream
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return new ArrayList<T>();
}
return loadedList;
}
private ArrayList<T> loadArrayFromOnline(){
return null;
}
private T loadSingularElementFromOffline() throws IOException{
T loadedElement;
//Build the FileInputStream
FileInputStream fis = new FileInputStream(new File(FILENAME));
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
Type typeOfElement = new TypeToken<T>(){}.getType();
//Read from inputstream
Gson gson = new Gson();
loadedElement = gson.fromJson(in, typeOfElement);
//Close stream
fis.close();
return loadedElement;
}
private T loadSingularElementFromOnline(){
return null;
}
}
|
package com.gazlaws.codeboard;
import android.content.Context;
import android.content.SharedPreferences;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static android.view.KeyEvent.KEYCODE_CTRL_LEFT;
import static android.view.KeyEvent.KEYCODE_SHIFT_LEFT;
import static android.view.KeyEvent.META_CTRL_ON;
import static android.view.KeyEvent.META_SHIFT_ON;
public class CodeBoardIME extends InputMethodService
implements KeyboardView.OnKeyboardActionListener {
private KeyboardView kv;
private Keyboard keyboard;
EditorInfo sEditorInfo;
private boolean vibratorOn;
private boolean shiftLock = false;
private boolean shift = false;
private boolean ctrl = false;
private int mKeyboardState = R.integer.keyboard_normal;
private int mLayout, mToprow, mSize;
private Timer timerLongPress = null;
private boolean switchedKeyboard=false;
public void onKeyCtrl(int code, InputConnection ic) {
long now2 = System.currentTimeMillis();
switch (code) {
case 'a':
case 'A':
if (sEditorInfo.imeOptions == 1342177286)//fix for DroidEdit
{
getCurrentInputConnection().performContextMenuAction(android.R.id.selectAll);
} else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A, 0, META_CTRL_ON));
break;
case 'c':
case 'C':
if (sEditorInfo.imeOptions == 1342177286)//fix for DroidEdit
{
getCurrentInputConnection().performContextMenuAction(android.R.id.copy);
} else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_C, 0, META_CTRL_ON));
break;
case 'v':
case 'V':
if (sEditorInfo.imeOptions == 1342177286)//fix for DroidEdit
{
getCurrentInputConnection().performContextMenuAction(android.R.id.paste);
} else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_V, 0, META_CTRL_ON));
break;
case 'x':
case 'X':
if (sEditorInfo.imeOptions == 1342177286)//fix for DroidEdit
{
getCurrentInputConnection().performContextMenuAction(android.R.id.cut);
} else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_X, 0, META_CTRL_ON));
break;
case 'z':
case 'Z':
if (shift) {
if (ic != null) {
if (sEditorInfo.imeOptions == 1342177286)//fix for DroidEdit
{
getCurrentInputConnection().performContextMenuAction(android.R.id.redo);
} else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_Z, 0, META_CTRL_ON | META_SHIFT_ON));
shift = false;
shiftLock = false;
shiftKeyUpdateView();
}
} else {
//Log.e("ctrl", "z");
if (sEditorInfo.imeOptions == 1342177286)//fix for DroidEdit
{
getCurrentInputConnection().performContextMenuAction(android.R.id.undo);
} else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_Z, 0, META_CTRL_ON));
}
break;
case 'b':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_B, 0, META_CTRL_ON));
break;
case 'd':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_D, 0, META_CTRL_ON));
break;
case 'e':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_E, 0, META_CTRL_ON));
break;
case 'f':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_F, 0, META_CTRL_ON));
break;
case 'g':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_G, 0, META_CTRL_ON));
break;
case 'h':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_H, 0, META_CTRL_ON));
break;
case 'i':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_I, 0, META_CTRL_ON));
break;
case 'j':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_J, 0, META_CTRL_ON));
break;
case 'k':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_K, 0, META_CTRL_ON));
break;
case 'l':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_L, 0, META_CTRL_ON));
break;
case 'm':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_M, 0, META_CTRL_ON));
break;
case 'n':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_N, 0, META_CTRL_ON));
break;
case 'o':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_O, 0, META_CTRL_ON));
break;
case 'p':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_P, 0, META_CTRL_ON));
break;
case 'q':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_P, 0, META_CTRL_ON));
break;
case 'r':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_R, 0, META_CTRL_ON));
break;
case 's':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_S, 0, META_CTRL_ON));
break;
case 't':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_T, 0, META_CTRL_ON));
break;
case 'u':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_U, 0, META_CTRL_ON));
break;
case 'w':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_W, 0, META_CTRL_ON));
break;
case 'y':
ic.sendKeyEvent(new KeyEvent(
now2 + 1, now2 + 1,
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_Y, 0, META_CTRL_ON));
break;
default:
if (Character.isLetter(code) && shift) {
code = Character.toUpperCase(code);
ic.commitText(String.valueOf(code), 1);
if (!shiftLock) {
shift = false;
shiftKeyUpdateView();
//Log.e("CodeboardIME", "Unshifted b/c no lock");
}
}
break;
}
}
@Override
public void onKey(int primaryCode, int[] KeyCodes) {
InputConnection ic = getCurrentInputConnection();
keyboard = kv.getKeyboard();
switch (primaryCode) {
case 53737:
getCurrentInputConnection().performContextMenuAction(android.R.id.selectAll);
break;
case 53738:
getCurrentInputConnection().performContextMenuAction(android.R.id.cut);
break;
case 53739:
getCurrentInputConnection().performContextMenuAction(android.R.id.copy);
break;
case 53740:
getCurrentInputConnection().performContextMenuAction(android.R.id.paste);
break;
case 53741:
getCurrentInputConnection().performContextMenuAction(android.R.id.undo);
break;
case 53742:
getCurrentInputConnection().performContextMenuAction(android.R.id.redo);
break;
case Keyboard.KEYCODE_DELETE:
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
break;
case Keyboard.KEYCODE_DONE:
sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER);
break;
case 27:
//Escape
long now = System.currentTimeMillis();
ic.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ESCAPE, 0, KeyEvent.META_CTRL_ON | KeyEvent.META_CTRL_LEFT_ON));
break;
case -13:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showInputMethodPicker();
break;
case -15:
if (kv != null) {
if (mKeyboardState == R.integer.keyboard_normal) {
//change to symbol keyboard
Keyboard symbolKeyboard = chooseKB(mLayout, mToprow, mSize, R.integer.keyboard_sym);
kv.setKeyboard(symbolKeyboard);
mKeyboardState = R.integer.keyboard_sym;
} else if (mKeyboardState == R.integer.keyboard_sym) {
//change to normal keyboard
Keyboard normalKeyboard = chooseKB(mLayout, mToprow, mSize, R.integer.keyboard_normal);
kv.setKeyboard(normalKeyboard);
mKeyboardState = R.integer.keyboard_normal;
}
controlKeyUpdateView();
shiftKeyUpdateView();
}
break;
case 17:
// ctrl key
long nowCtrl = System.currentTimeMillis();
if (ctrl)
ic.sendKeyEvent(new KeyEvent(nowCtrl, nowCtrl, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_CTRL_LEFT, 0, META_CTRL_ON));
else
ic.sendKeyEvent(new KeyEvent(nowCtrl, nowCtrl, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_CTRL_LEFT, 0, META_CTRL_ON));
ctrl = !ctrl;
controlKeyUpdateView();
break;
case 16:
// Log.e("CodeBoardIME", "onKey" + Boolean.toString(shiftLock));
//Shift - runs after long press, so shiftlock may have just been activated
long nowShift = System.currentTimeMillis();
if (shift)
ic.sendKeyEvent(new KeyEvent(nowShift, nowShift, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT, 0, META_SHIFT_ON));
else
ic.sendKeyEvent(new KeyEvent(nowShift, nowShift, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, META_SHIFT_ON));
if (shiftLock) {
shift = true;
shiftKeyUpdateView();
} else {
shift = !shift;
shiftKeyUpdateView();
}
break;
case 9:
//tab
// ic.commitText("\u0009", 1);
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
break;
case 5000:
handleArrow(KeyEvent.KEYCODE_DPAD_LEFT);
break;
case 5001:
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_DOWN);
break;
case 5002:
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_UP);
break;
case 5003:
handleArrow(KeyEvent.KEYCODE_DPAD_RIGHT);
break;
default:
char code = (char) primaryCode;
if (ctrl) {
onKeyCtrl(code, ic);
if (!shiftLock) {
shift = false;
shiftKeyUpdateView();
}
ctrl = false;
controlKeyUpdateView();
} else if (Character.isLetter(code) && shift) {
code = Character.toUpperCase(code);
ic.commitText(String.valueOf(code), 1);
if (!shiftLock) {
shift = false;
shiftKeyUpdateView();
//Log.e("CodeboardIME", "Unshifted b/c no lock");
}
} else{
if(!switchedKeyboard) {
ic.commitText(String.valueOf(code), 1);
}
switchedKeyboard=false;
}
}
}
@Override
public void onPress(final int primaryCode) {
if (vibratorOn) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if(vibrator!=null)
vibrator.vibrate(20);
}
if (timerLongPress != null)
timerLongPress.cancel();
timerLongPress = new Timer();
timerLongPress.schedule(new TimerTask() {
@Override
public void run() {
try {
Handler uiHandler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
CodeBoardIME.this.onKeyLongPress(primaryCode);
} catch (Exception e) {
Log.e(CodeBoardIME.class.getSimpleName(), "uiHandler.run: " + e.getMessage(), e);
}
}
};
uiHandler.post(runnable);
} catch (Exception e) {
Log.e(CodeBoardIME.class.getSimpleName(), "Timer.run: " + e.getMessage(), e);
}
}
}, ViewConfiguration.getLongPressTimeout());
}
@Override
public void onRelease(int primaryCode) {
if (timerLongPress != null)
timerLongPress.cancel();
}
public void onKeyLongPress(int keyCode) {
// Process long-click here
if (keyCode == 16) {
shiftLock = !shiftLock;
//Log.e("CodeBoardIME", "long press" + Boolean.toString(shiftLock));
//and onKey will now happen
}
if (keyCode == 32) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm!=null)
imm.showInputMethodPicker();
switchedKeyboard=true;
}
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if(vibrator!=null)
vibrator.vibrate(50);
}
@Override
public void onText(CharSequence text) {
InputConnection ic = getCurrentInputConnection();
if (text.toString().contains("for")) {
ic.commitText(text, 1);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
} else {
ic.commitText(text, 1);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
}
}
@Override
public void swipeDown() {
kv.closing();
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeUp() {
}
public Keyboard chooseKB(int layout, int toprow, int size, int mode) {
Keyboard keyboard;
if (layout == 0) {
if (toprow == 1) {
if (size == 0) {
keyboard = new Keyboard(this, R.xml.qwerty0r, mode);
} else if (size == 1) {
keyboard = new Keyboard(this, R.xml.qwerty1r, mode);
} else if (size == 2) {
keyboard = new Keyboard(this, R.xml.qwerty2r, mode);
} else keyboard = new Keyboard(this, R.xml.qwerty3r, mode);
} else {
if (size == 0) {
keyboard = new Keyboard(this, R.xml.qwerty0e, mode);
} else if (size == 1) {
keyboard = new Keyboard(this, R.xml.qwerty1e, mode);
} else if (size == 2) {
keyboard = new Keyboard(this, R.xml.qwerty2e, mode);
} else keyboard = new Keyboard(this, R.xml.qwerty3e, mode);
}
} else {
if (toprow == 1) {
if (size == 0) {
keyboard = new Keyboard(this, R.xml.azerty0r, mode);
} else if (size == 1) {
keyboard = new Keyboard(this, R.xml.azerty1r, mode);
} else if (size == 2) {
keyboard = new Keyboard(this, R.xml.azerty2r, mode);
} else keyboard = new Keyboard(this, R.xml.azerty3r, mode);
} else {
if (size == 0) {
keyboard = new Keyboard(this, R.xml.azerty0e, mode);
} else if (size == 1) {
keyboard = new Keyboard(this, R.xml.azerty1e, mode);
} else if (size == 2) {
keyboard = new Keyboard(this, R.xml.azerty2e, mode);
} else keyboard = new Keyboard(this, R.xml.azerty3e, mode);
}
}
return keyboard;
}
@Override
public View onCreateInputView() {
SharedPreferences pre = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
switch (pre.getInt("RADIO_INDEX_COLOUR", 0)) {
case 0:
//kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
break;
case 1:
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard1, null);
break;
case 2:
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard2, null);
break;
case 3:
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard3, null);
break;
case 4:
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard4, null);
break;
case 5:
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard5, null);
break;
default:
kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
break;
}
if (pre.getInt("PREVIEW", 0) == 1) {
kv.setPreviewEnabled(true);
} else kv.setPreviewEnabled(false);
if (pre.getInt("VIBRATE", 1) == 1) {
vibratorOn = true;
} else vibratorOn = false;
shift = false;
ctrl = false;
mLayout = pre.getInt("RADIO_INDEX_LAYOUT", 0);
mSize = pre.getInt("SIZE", 2);
mToprow = pre.getInt("ARROW_ROW", 1);
mKeyboardState = R.integer.keyboard_normal;
//reset to normal
Keyboard keyboard = chooseKB(mLayout, mToprow, mSize, mKeyboardState);
kv.setKeyboard(keyboard);
kv.setOnKeyboardActionListener(this);
return kv;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
super.onStartInputView(attribute, restarting);
setInputView(onCreateInputView());
sEditorInfo = attribute;
}
public void controlKeyUpdateView() {
keyboard = kv.getKeyboard();
int i;
List<Keyboard.Key> keys = keyboard.getKeys();
for (i = 0; i < keys.size(); i++) {
if (ctrl) {
if (keys.get(i).label != null && keys.get(i).label.equals("Ctrl")) {
keys.get(i).label = "CTRL";
break;
}
} else {
if (keys.get(i).label != null && keys.get(i).label.equals("CTRL")) {
keys.get(i).label = "Ctrl";
break;
}
}
}
kv.invalidateKey(i);
}
public void shiftKeyUpdateView() {
keyboard = kv.getKeyboard();
List<Keyboard.Key> keys = keyboard.getKeys();
for (int i = 0; i < keys.size(); i++) {
if (shift) {
if (keys.get(i).label != null && keys.get(i).label.equals("Shft")) {
keys.get(i).label = "SHFT";
break;
}
} else {
if (keys.get(i).label != null && keys.get(i).label.equals("SHFT")) {
keys.get(i).label = "Shft";
break;
}
}
}
keyboard.setShifted(shift);
kv.invalidateAllKeys();
}
public void handleArrow(int keyCode) {
InputConnection ic = getCurrentInputConnection();
Long now2 = System.currentTimeMillis();
if (ctrl && shift) {
ic.sendKeyEvent(new KeyEvent(now2, now2, KeyEvent.ACTION_DOWN, KEYCODE_CTRL_LEFT, 0, META_SHIFT_ON | META_CTRL_ON));
moveSelection(keyCode);
ic.sendKeyEvent(new KeyEvent(now2 + 4, now2 + 4, KeyEvent.ACTION_UP, KEYCODE_CTRL_LEFT, 0, META_SHIFT_ON | META_CTRL_ON));
} else if (shift)
moveSelection(keyCode);
else if (ctrl)
ic.sendKeyEvent(new KeyEvent(now2, now2, KeyEvent.ACTION_DOWN, keyCode, 0, META_SHIFT_ON | META_CTRL_ON));
else sendDownUpKeyEvents(keyCode);
}
private void moveSelection(int keyCode) {
// inputMethodService.sendDownKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0);
// inputMethodService.sendDownAndUpKeyEvent(dpad_keyCode, 0);
// inputMethodService.sendUpKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0);
InputConnection ic = getCurrentInputConnection();
Long now2 = System.currentTimeMillis();
ic.sendKeyEvent(new KeyEvent(now2, now2, KeyEvent.ACTION_DOWN, KEYCODE_SHIFT_LEFT, 0, META_SHIFT_ON | META_CTRL_ON));
if (ctrl)
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, keyCode, 0, META_SHIFT_ON | META_CTRL_ON));
else
ic.sendKeyEvent(new KeyEvent(now2 + 1, now2 + 1, KeyEvent.ACTION_DOWN, keyCode, 0, META_SHIFT_ON));
ic.sendKeyEvent(new KeyEvent(now2 + 3, now2 + 3, KeyEvent.ACTION_UP, KEYCODE_SHIFT_LEFT, 0, META_SHIFT_ON | META_CTRL_ON));
}
}
|
package com.ibm.mil.smartringer;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
public final class NoiseMeter {
public static final int METER_LIMIT = 32768;
private static final int SAMPLE_RATE = 8000;
private static final int MIN_BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
private AudioRecord mAudioRecord;
public void start() {
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, MIN_BUFFER_SIZE);
mAudioRecord.startRecording();
}
public void stop() {
if (mAudioRecord != null) {
mAudioRecord.stop();
mAudioRecord.release();
mAudioRecord = null;
}
}
public int getMaxAmplitude() {
short[] buffer = new short[MIN_BUFFER_SIZE];
if (mAudioRecord != null) {
mAudioRecord.read(buffer, 0, MIN_BUFFER_SIZE);
}
int max = 0;
for (short s : buffer) {
int abs = Math.abs(s);
if (abs > max) {
max = abs;
}
}
return max;
}
public final static class Sampler {
private NoiseMeter mNoiseMeter;
private int mPollingRate;
private Receiver mReceiver;
public Sampler(NoiseMeter noiseMeter, int pollingRate, Receiver receiver) {
mNoiseMeter = noiseMeter;
mPollingRate = pollingRate;
mReceiver = receiver;
}
public void startSampling() {
// sample from noise meter and notify receiver of result
mReceiver.receiveSample(1000);
}
public void stopSampling() {
// stop sampling from noise meter
}
}
public interface Receiver {
void receiveSample(int amplitude);
}
}
|
package info.nightscout.androidaps;
import android.app.Application;
import android.content.Intent;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfileFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanFragment;
import info.nightscout.androidaps.plugins.LocalProfile.LocalProfileFragment;
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.MDI.MDIFragment;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalFragment;
import info.nightscout.androidaps.plugins.NSProfile.NSProfileFragment;
import info.nightscout.androidaps.plugins.Objectives.ObjectivesFragment;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
import info.nightscout.androidaps.plugins.SafetyFragment.SafetyFragment;
import info.nightscout.androidaps.plugins.SimpleProfile.SimpleProfileFragment;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorFragment;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gFragment;
import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientFragment;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripFragment;
import info.nightscout.androidaps.plugins.TempBasals.TempBasalsFragment;
import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangeFragment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment;
import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpFragment;
import info.nightscout.androidaps.plugins.Wear.WearFragment;
import info.nightscout.androidaps.plugins.persistentnotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import io.fabric.sdk.android.Fabric;
public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(MainApp.class);
private static KeepAliveReceiver keepAliveReceiver;
private static Bus sBus;
private static MainApp sInstance;
public static Resources sResources;
private static DatabaseHelper sDatabaseHelper = null;
private static ConfigBuilderPlugin sConfigBuilder = null;
private static ArrayList<PluginBase> pluginsList = null;
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
Fabric.with(this, new Answers());
Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION);
log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
Answers.getInstance().logCustom(new CustomEvent("AppStart"));
sBus = new Bus(ThreadEnforcer.ANY);
sInstance = this;
sResources = getResources();
if (pluginsList == null) {
pluginsList = new ArrayList<>();
// Register all tabs in app here
pluginsList.add(OverviewFragment.getPlugin());
if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRFragment.getPlugin());
if (Config.DANARKOREAN) pluginsList.add(DanaRKoreanFragment.getPlugin());
pluginsList.add(CareportalFragment.getPlugin());
if (Config.MDI) pluginsList.add(MDIFragment.getPlugin());
if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpFragment.getPlugin());
if (Config.LOOPENABLED) pluginsList.add(LoopFragment.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSMAFragment.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSAMAFragment.getPlugin());
pluginsList.add(NSProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(SimpleProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(LocalProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
if (Config.APS) pluginsList.add(TempTargetRangeFragment.getPlugin());
pluginsList.add(TreatmentsFragment.getPlugin());
if (Config.TEMPBASALS) pluginsList.add(TempBasalsFragment.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyFragment.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin());
pluginsList.add(SourceXdripFragment.getPlugin());
pluginsList.add(SourceNSClientFragment.getPlugin());
pluginsList.add(SourceMM640gFragment.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorFragment.getPlugin());
if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this));
pluginsList.add(new PersistentNotificationPlugin(this));
pluginsList.add(NSClientInternalFragment.getPlugin());
pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin());
MainApp.getConfigBuilder().initialize();
}
MainApp.getConfigBuilder().uploadAppStart();
startKeepAliveService();
}
private void startKeepAliveService() {
if (keepAliveReceiver == null) {
keepAliveReceiver = new KeepAliveReceiver();
if (Config.DANAR) {
startService(new Intent(this, info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService.class));
startService(new Intent(this, info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService.class));
}
keepAliveReceiver.setAlarm(this);
}
}
public void stopKeepAliveService(){
if(keepAliveReceiver!=null)
keepAliveReceiver.cancelAlarm(this);
}
public static Bus bus() {
return sBus;
}
public static MainApp instance() {
return sInstance;
}
public static DatabaseHelper getDbHelper() {
if (sDatabaseHelper == null) {
sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class);
}
return sDatabaseHelper;
}
public static void closeDbHelper() {
if (sDatabaseHelper != null) {
sDatabaseHelper.close();
sDatabaseHelper = null;
}
}
public static ConfigBuilderPlugin getConfigBuilder() {
return sConfigBuilder;
}
public static ArrayList<PluginBase> getPluginsList() {
return pluginsList;
}
public static ArrayList<PluginBase> getSpecificPluginsList(int type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
@Nullable
public static PluginBase getSpecificPlugin(Class pluginClass) {
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() == pluginClass)
return p;
}
} else {
log.error("pluginsList=null");
}
return null;
}
@Override
public void onTerminate() {
super.onTerminate();
sDatabaseHelper.close();
}
}
|
package org.radarcns.kafka.rest;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import org.apache.avro.Schema;
import org.radarcns.data.AvroEncoder;
import org.radarcns.data.Record;
import org.radarcns.kafka.AvroTopic;
import org.radarcns.kafka.KafkaSender;
import org.radarcns.kafka.KafkaTopicSender;
import org.radarcns.kafka.ParsedSchemaMetadata;
import org.radarcns.kafka.SchemaRetriever;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
import okio.Sink;
public class RestSender<K, V> implements KafkaSender<K, V> {
private final static Logger logger = LoggerFactory.getLogger(RestSender.class);
private final SchemaRetriever schemaRetriever;
private final URL kafkaUrl;
private final AvroEncoder keyEncoder;
private final AvroEncoder valueEncoder;
private final JsonFactory jsonFactory;
private final OkHttpClient httpClient;
public final static String KAFKA_REST_ACCEPT_ENCODING = "application/vnd.kafka.v1+json, application/vnd.kafka+json, application/json";
public final static MediaType KAFKA_REST_AVRO_ENCODING = MediaType.parse("application/vnd.kafka.avro.v1+json; charset=utf-8");
private final Request isConnectedRequest;
private final HttpUrl schemalessKeyUrl;
private final HttpUrl schemalessValueUrl;
public RestSender(URL kafkaUrl, SchemaRetriever schemaRetriever, AvroEncoder keyEncoder, AvroEncoder valueEncoder) {
this.kafkaUrl = kafkaUrl;
this.schemaRetriever = schemaRetriever;
this.keyEncoder = keyEncoder;
this.valueEncoder = valueEncoder;
try {
schemalessKeyUrl = HttpUrl.get(new URL(kafkaUrl, "topics/schemaless-key"));
schemalessValueUrl = HttpUrl.get(new URL(kafkaUrl, "topics/schemaless-value"));
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Schemaless topics do not have a valid URL");
}
jsonFactory = new JsonFactory();
// Default timeout is 10 seconds.
httpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
isConnectedRequest = new Request.Builder().url(kafkaUrl).head().build();
}
class RestTopicSender<L extends K, W extends V> implements KafkaTopicSender<L, W> {
long lastOffsetSent = -1L;
final AvroTopic<L, W> topic;
final HttpUrl url;
final TopicRequestBody requestBody;
RestTopicSender(AvroTopic<L, W> topic) throws IOException {
this.topic = topic;
URL rawUrl = new URL(kafkaUrl, "topics/" + topic.getName());
url = HttpUrl.get(rawUrl);
if (url == null) {
throw new MalformedURLException("Cannot parse " + rawUrl);
}
requestBody = new TopicRequestBody();
}
@Override
public void send(long offset, L key, W value) throws IOException {
List<Record<L, W>> records = new ArrayList<>(1);
records.add(new Record<>(offset, key, value));
send(records);
}
/**
* Actually make a REST request to the Kafka REST server and Schema Registry.
* @param records values to send
* @throws IOException if records could not be sent
*/
@Override
public void send(List<Record<L, W>> records) throws IOException {
if (records.isEmpty()) {
return;
}
// Get schema IDs
Schema valueSchema = topic.getValueSchema();
String sendTopic = topic.getName();
HttpUrl sendToUrl = url;
try {
ParsedSchemaMetadata metadata = schemaRetriever.getOrSetSchemaMetadata(sendTopic, false, topic.getKeySchema());
requestBody.keySchemaId = metadata.getId();
} catch (IOException ex) {
sendToUrl = schemalessKeyUrl;
requestBody.keySchemaId = null;
}
requestBody.keySchemaString = requestBody.keySchemaId == null ? topic.getKeySchema().toString() : null;
try {
ParsedSchemaMetadata metadata = schemaRetriever.getOrSetSchemaMetadata(sendTopic, true, valueSchema);
requestBody.valueSchemaId = metadata.getId();
} catch (IOException ex) {
sendToUrl = schemalessValueUrl;
requestBody.valueSchemaId = null;
}
requestBody.valueSchemaString = requestBody.valueSchemaId == null ? topic.getValueSchema().toString() : null;
requestBody.records = records;
Request request = new Request.Builder()
.url(sendToUrl)
.addHeader("Accept", KAFKA_REST_ACCEPT_ENCODING)
.post(requestBody)
.build();
try (Response response = httpClient.newCall(request).execute()) {
// Evaluate the result
if (response.isSuccessful()) {
if (logger.isDebugEnabled()) {
logger.info("Added message to topic {} -> {}", sendTopic, response.body().string());
}
lastOffsetSent = records.get(records.size() - 1).offset;
} else {
String content = response.body().string();
logger.error("FAILED to transmit message: {} -> {}...", content, requestBody.content().substring(0, 255));
throw new IOException("Failed to submit (HTTP status code " + response.code() + "): " + content);
}
} catch (IOException ex) {
logger.error("FAILED to transmit message: {}...", requestBody.content().substring(0, 255), ex);
throw ex;
}
}
@Override
public long getLastSentOffset() {
return lastOffsetSent;
}
@Override
public void clear() {
// noop
}
@Override
public void flush() {
// noop
}
@Override
public void close() {
// noop
}
class TopicRequestBody extends RequestBody {
Integer keySchemaId, valueSchemaId;
String keySchemaString, valueSchemaString;
final AvroEncoder.AvroWriter<L> keyWriter;
final AvroEncoder.AvroWriter<W> valueWriter;
List<Record<L, W>> records;
TopicRequestBody() throws IOException {
keyWriter = keyEncoder.writer(topic.getKeySchema(), topic.getKeyClass());
valueWriter = valueEncoder.writer(topic.getValueSchema(), topic.getValueClass());
}
@Override
public MediaType contentType() {
return KAFKA_REST_AVRO_ENCODING;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
try (OutputStream out = sink.outputStream(); JsonGenerator writer = jsonFactory.createGenerator(out, JsonEncoding.UTF8)) {
writer.writeStartObject();
if (keySchemaId != null) {
writer.writeNumberField("key_schema_id", keySchemaId);
} else {
writer.writeStringField("key_schema", keySchemaString);
}
if (valueSchemaId != null) {
writer.writeNumberField("value_schema_id", valueSchemaId);
} else {
writer.writeStringField("value_schema", valueSchemaString);
}
writer.writeArrayFieldStart("records");
for (Record<L, W> record : records) {
writer.writeStartObject();
writer.writeFieldName("key");
writer.writeRawValue(new String(keyWriter.encode(record.key)));
writer.writeFieldName("value");
writer.writeRawValue(new String(valueWriter.encode(record.value)));
writer.writeEndObject();
}
writer.writeEndArray();
writer.writeEndObject();
}
}
String content() throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
try (Sink sink = Okio.sink(out); BufferedSink bufferedSink = Okio.buffer(sink)) {
writeTo(bufferedSink);
}
return out.toString();
}
}
}
}
@Override
public <L extends K, W extends V> KafkaTopicSender<L, W> sender(AvroTopic<L, W> topic) throws IOException {
return new RestTopicSender<>(topic);
}
@Override
public boolean resetConnection() {
return isConnected();
}
public boolean isConnected() {
try (Response response = httpClient.newCall(isConnectedRequest).execute()) {
if (response.isSuccessful()) {
return true;
} else {
logger.warn("Failed to make heartbeat request to {} (HTTP status code {}): {}", kafkaUrl, response.code(), response.body().string());
return false;
}
} catch (IOException ex) {
logger.debug("Failed to make heartbeat request to {}", kafkaUrl, ex);
return false;
}
}
@Override
public void close() {
// noop
}
}
|
package treehacks.tinderplusplus;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Collections;
public class Questions extends AppCompatActivity {
private static ArrayList<Question> questions;
private int currentQuestion = -1;
private boolean[] answers = new boolean[questions.size()];
private static Button optA, optB;
static {
questions = new ArrayList<>();
questions.add(new Question(1,"Which pronounciation?", "Giff", "Jiff"));
questions.add(new Question(2,"", "Android", "iOS"));
questions.add(new Question(3,"Indentation Preference", "Tabs", "Spaces"));
questions.add(new Question(4,"Naming Preferences", "Camel Case", "Snake Case"));
questions.add(new Question(5,"Editor Color Scheme", "White on black", "Black on White"));
questions.add(new Question(6,"", "github", "Bitbucket"));
questions.add(new Question(7,"Strings", "Single Quotes", "Double Quotes"));
questions.add(new Question(8,"", "Scrolling", "Inverted Scrolling"));
questions.add(new Question(9,"", "Front End", "Back End"));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
Collections.shuffle(questions);
optA = (Button)findViewById(R.id.optA);
optB = (Button)findViewById(R.id.optB);
nextQuestion();
optA.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
answers[currentQuestion] = false;
nextQuestion();
}
});
optB.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
answers[currentQuestion] = true;
nextQuestion();
}
});
}
public void nextQuestion() {
if (currentQuestion < questions.size()-1){
currentQuestion++;
Question q = questions.get(currentQuestion);
optA.setText(q.opt1);
optB.setText(q.opt2);
}
else{
Intent i = new Intent(this, Matching.class);
startActivity(i);
}
}
public static class Question {
public String question;
public String opt1;
public String opt2;
public Question(int id,String q, String o1, String o2) {
question = q;
opt1 = o1;
opt2 = o2;
}
}
}
|
package us.kbase.jgiintegration.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
import us.kbase.abstracthandle.AbstractHandleClient;
import us.kbase.abstracthandle.Handle;
import us.kbase.auth.AuthService;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.Tuple2;
import us.kbase.common.utils.MD5DigestOutputStream;
import us.kbase.shock.client.BasicShockClient;
import us.kbase.shock.client.ShockNode;
import us.kbase.shock.client.ShockNodeId;
import us.kbase.wipedev03.WipeDev03Client;
import us.kbase.workspace.ObjectData;
import us.kbase.workspace.ObjectIdentity;
import us.kbase.workspace.WorkspaceClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class JGIIntegrationTest {
//TODO set up automated runner with jenkins
//TODO add more data types other than reads
//TODO add a list of files (in another suite? - factor out the common test code)
//TODO test with nothing selected: use code like:
/*
* List<String> alerts = new LinkedList<String>();
* cli.setAlertHandler(new CollectingAlertHandler(alerts));
*/
private static String WS_URL =
"https://dev03.berkeley.kbase.us/services/ws";
private static String HANDLE_URL =
"https://dev03.berkeley.kbase.us/services/handle_service";
private static String WIPE_URL =
"http://dev03.berkeley.kbase.us:9000";
private static final int PUSH_TO_WS_TIMEOUT_SEC = 20 * 60; //20min
private static final int PUSH_TO_WS_SLEEP_SEC = 5;
//for testing
private static final boolean SKIP_WIPE = false;
private static String JGI_USER;
private static String JGI_PWD;
private static String KB_USER_1;
private static String KB_PWD_1;
private static WorkspaceClient WS_CLI1;
private static AbstractHandleClient HANDLE_CLI;
private static final ObjectMapper SORTED_MAPPER = new ObjectMapper();
static {
SORTED_MAPPER.configure(
SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
}
@BeforeClass
public static void setUpClass() throws Exception {
Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
JGI_USER = System.getProperty("test.jgi.user");
JGI_PWD = System.getProperty("test.jgi.pwd");
KB_USER_1 = System.getProperty("test.kbase.user1");
KB_PWD_1 = System.getProperty("test.kbase.pwd1");
WS_CLI1 = new WorkspaceClient(new URL(WS_URL), KB_USER_1, KB_PWD_1);
WS_CLI1.setIsInsecureHttpConnectionAllowed(true);
WS_CLI1.setAllSSLCertificatesTrusted(true);
HANDLE_CLI = new AbstractHandleClient(
new URL(HANDLE_URL), KB_USER_1, KB_PWD_1);
HANDLE_CLI.setIsInsecureHttpConnectionAllowed(true);
HANDLE_CLI.setAllSSLCertificatesTrusted(true);
String wipeUser = System.getProperty("test.kbase.wipe_user");
String wipePwd = System.getProperty("test.kbase.wipe_pwd");
WipeDev03Client wipe = new WipeDev03Client(new URL(WIPE_URL), wipeUser,
wipePwd);
wipe.setIsInsecureHttpConnectionAllowed(true);
wipe.setAllSSLCertificatesTrusted(true);
wipe.setConnectionReadTimeOut(60000);
if (!SKIP_WIPE) {
System.out.print("triggering remote wipe of test data stores... ");
Tuple2<Long, String> w = wipe.wipeDev03();
if (w.getE1() > 0 ) {
throw new TestException(
"Wipe of test server failed. The wipe server said:\n" +
w.getE2());
}
System.out.println("done. Server said:\n" + w.getE2());
}
}
private static class JGIOrganismPage {
private final static String JGI_SIGN_ON =
"https://signon.jgi.doe.gov/signon";
private final static String JGI_ORGANISM_PAGE =
"http://genomeportal.jgi.doe.gov/pages/dynamicOrganismDownload.jsf?organism=";
private final String organismCode;
private HtmlPage page;
private final WebClient client;
private final Set<JGIFileLocation> selected =
new HashSet<JGIFileLocation>();
public JGIOrganismPage(
WebClient client,
String organismCode,
String JGIuser,
String JGIpwd)
throws Exception {
super();
System.out.print(String.format("Opening %s page... ",
organismCode));
this.client = client;
signOnToJGI(client, JGIuser, JGIpwd);
this.organismCode = organismCode;
this.page = this.client.getPage(JGI_ORGANISM_PAGE + organismCode);
Thread.sleep(3000); // wait for page & file table to load
//TODO find a better way to check page is loaded
System.out.println("done.");
closePushedFilesDialog(false);
}
private void signOnToJGI(WebClient cli, String user, String password)
throws IOException, MalformedURLException {
HtmlPage hp = cli.getPage(JGI_SIGN_ON);
assertThat("Signon title ok", hp.getTitleText(),
is("JGI Single Sign On"));
try {
hp.getHtmlElementById("highlight-me");
fail("logged in already");
} catch (ElementNotFoundException enfe) {
//we're all good
}
//login form has no name, which is the only way to get a specific form
List<HtmlForm> forms = hp.getForms();
assertThat("2 forms on login page", forms.size(), is(2));
HtmlForm form = forms.get(1);
form.getInputByName("login").setValueAttribute(user);
form.getInputByName("password").setValueAttribute(password);
HtmlPage loggedIn = form.getInputByName("commit").click();
HtmlDivision div = loggedIn.getHtmlElementById("highlight-me");
assertThat("signed in correctly", div.getTextContent(),
is("You have signed in successfully."));
}
public void selectFile(JGIFileLocation file) throws
IOException, InterruptedException {
//text element with the file group name
System.out.println(String.format("Selecting file %s from group %s",
file.getFile(), file.getGroup()));
DomElement fileText = findFile(file);
HtmlInput filetoggle = (HtmlInput) ((DomElement) fileText
.getParentNode()
.getParentNode()
.getParentNode() //span
.getParentNode())
.getElementsByTagName("input").get(0);
if (filetoggle.getCheckedAttribute().equals("checked")) {
return;
}
this.page = filetoggle.click();
selected.add(file);
Thread.sleep(1000); //every click gets sent to the server
System.out.println(String.format("Selected file %s from group %s.",
file.getFile(), file.getGroup()));
}
private DomElement findFile(JGIFileLocation file)
throws IOException, InterruptedException {
DomElement fileGroup = openFileGroup(file);
//this is ugly but it doesn't seem like there's another way
//to get the node
DomElement selGroup = null;
List<HtmlElement> bold = fileGroup.getElementsByTagName("b");
for (HtmlElement de: bold) {
if (file.getFile().equals(de.getTextContent())) {
selGroup = de;
break;
}
}
if (selGroup == null) {
throw new TestException(String.format(
"There is no file %s in file group %s for the organism %s",
file.getFile(), file.getGroup(), organismCode));
}
return selGroup;
}
private DomElement openFileGroup(JGIFileLocation file)
throws IOException, InterruptedException {
int timeoutSec = 20;
System.out.print(String.format("Opening file group %s... ",
file.getGroup()));
DomElement fileGroupText = findFileGroup(file);
DomElement fileContainer = getFilesDivFromFilesGroup(
fileGroupText);
//TODO this is not tested - test with multiple files per test
if (fileContainer.isDisplayed()) {
System.out.println("already open.");
return fileContainer;
}
HtmlAnchor fileSetToggle = (HtmlAnchor) fileGroupText
.getParentNode()
.getPreviousSibling() //td folder icon
.getPreviousSibling() //td toggle icon
.getChildNodes().get(0) //div
.getChildNodes().get(0);
this.page = fileSetToggle.click();
Long startNanos = System.nanoTime();
while (!fileContainer.isDisplayed()) {
fileGroupText = findFileGroup(file);
fileContainer = getFilesDivFromFilesGroup(fileGroupText);
checkTimeout(startNanos, timeoutSec, String.format(
"Timed out waiting for file group %s to open",
file.getGroup()));
Thread.sleep(1000);
}
System.out.println("done");
return fileContainer;
}
public void pushToKBase(String user, String pwd)
throws IOException, InterruptedException {
HtmlInput push = (HtmlInput) page.getElementById(
"downloadForm:fileTreePanel")
.getChildNodes().get(2) //div
.getFirstChild() //div
.getFirstChild() //table
.getFirstChild() //tbody
.getFirstChild()
.getChildNodes().get(1)
.getFirstChild(); //input
this.page = push.click();
Thread.sleep(1000); // just in case, should be fast to create modal
HtmlForm kbLogin = page.getFormByName("form"); //interesting id there
kbLogin.getInputByName("user_id").setValueAttribute(KB_USER_1);
kbLogin.getInputByName("password").setValueAttribute(KB_PWD_1);
HtmlAnchor loginButton = (HtmlAnchor) kbLogin
.getParentNode()
.getParentNode() //div
.getNextSibling() //div
.getFirstChild() //div
.getChildNodes().get(1) //div
.getChildNodes().get(1);
this.page = loginButton.click();
checkPushedFiles();
closePushedFilesDialog(true);
}
private void closePushedFilesDialog(boolean failIfClosedNow)
throws IOException, InterruptedException {
System.out.print("Closing result dialog... ");
HtmlElement resDialogDiv =
(HtmlElement) page.getElementById("filesPushedToKbase");
if (failIfClosedNow) {
assertThat("result dialog open", resDialogDiv.isDisplayed(),
is(true));
} else {
if (!resDialogDiv.isDisplayed()) {
System.out.println("already closed.");
return;
}
}
HtmlInput ok = (HtmlInput) resDialogDiv
.getNextSibling()
.getNextSibling()
.getNextSibling(); //input
page = ok.click();
Thread.sleep(2000);
resDialogDiv =
(HtmlElement) page.getElementById("filesPushedToKbase");
assertThat("Dialog closed", resDialogDiv.isDisplayed(), is(false));
System.out.println("done.");
}
public String getWorkspaceName(String user) {
DomNode foldable = page.getElementById("foldable");
DomNode projName = foldable
.getFirstChild()
.getFirstChild()
.getChildNodes().get(1);
return projName.getTextContent().replace(' ', '_') + '_' + user;
}
private void checkPushedFiles() throws InterruptedException {
// make this configurable per test?
//may need to be longer for tape files
int timeoutSec = 20;
HtmlElement resDialogDiv =
(HtmlElement) page.getElementById("filesPushedToKbase");
Long startNanos = System.nanoTime();
//TODO use visibility here vs. contents
while (resDialogDiv.getTextContent() == null ||
resDialogDiv.getTextContent().isEmpty()) {
checkTimeout(startNanos, timeoutSec,
"Timed out waiting for files to push to Kbase");
Thread.sleep(1000);
}
String[] splDialog = resDialogDiv.getTextContent().split("\n");
Set<String> filesFound = new HashSet<String>();
//skip first row
for (int i = 1; i < splDialog.length; i++) {
String[] filespl = splDialog[i].split("/");
if (filespl.length > 1) {
filesFound.add(filespl[filespl.length - 1]);
}
}
Set<String> filesExpected = new HashSet<String>();
for (JGIFileLocation file: selected) {
filesExpected.add(file.getFile());
}
assertThat("correct files in dialog", filesFound,
is(filesExpected));
}
private DomElement getFilesDivFromFilesGroup(DomElement selGroup) {
return (DomElement) selGroup
.getParentNode()
.getParentNode()
.getParentNode() //tbody
.getParentNode() //table
.getNextSibling(); //div below table
}
private DomElement findFileGroup(JGIFileLocation file) {
//this is ugly but it doesn't seem like there's another way
//to get the node
DomElement selGroup = null;
List<DomElement> bold = page.getElementsByTagName("b");
for (DomElement de: bold) {
if (file.getGroup().equals(de.getTextContent())) {
selGroup = de;
break;
}
}
if (selGroup == null) {
throw new TestException(String.format(
"There is no file group %s for the organism %s",
file.getGroup(), organismCode));
}
return selGroup;
}
}
private static class JGIFileLocation {
private final String group;
private final String file;
public JGIFileLocation(String group, String file) {
super();
this.group = group;
this.file = file;
}
public String getGroup() {
return group;
}
public String getFile() {
return file;
}
}
@SuppressWarnings("serial")
private static class TestException extends RuntimeException {
public TestException(String msg) {
super(msg);
}
}
@Test
public void fullIntegration() throws Exception {
WebClient cli = new WebClient();
//TODO ZZ: if JGI fixes login page remove next line
cli.getOptions().setThrowExceptionOnScriptError(false);
cli.setAlertHandler(new AlertHandler() {
@Override
public void handleAlert(Page arg0, String arg1) {
throw new TestException("Unexpected alert: " + arg1);
}
});
final String organismCode = "BlaspURHD0036";
final String fileGroup = "QC Filtered Raw Data";
String fileName = "7625.2.79179.AGTTCC.adnq.fastq.gz";
final String type = "KBaseFile.PairedEndLibrary-2.1";
final long expectedVersion = 1;
//MD5 of object when variable fields are replaced by "dummy"
String workspaceDummyMD5 = "39db907edfb9ba1861b5402201b72ada";
String shockMD5 = "5c66abbb2515674a074d2a41ecf01017";
JGIOrganismPage org = new JGIOrganismPage(cli, organismCode,
JGI_USER, JGI_PWD);
JGIFileLocation qcReads = new JGIFileLocation(fileGroup,
fileName);
org.selectFile(qcReads);
org.pushToKBase(KB_USER_1, KB_PWD_1);
System.out.println(String.format(
"Finished push at UI level at %s for test %s",
new Date(), getMethodName()));
String wsName = org.getWorkspaceName(KB_USER_1);
//TODO make this a method
Long start = System.nanoTime();
ObjectData wsObj = null;
while(wsObj == null) {
checkTimeout(start, PUSH_TO_WS_TIMEOUT_SEC, String.format(
"Timed out attempting to access object %s in workspace %s after %s sec",
fileName, wsName, PUSH_TO_WS_TIMEOUT_SEC));
try {
wsObj = WS_CLI1.getObjects(Arrays.asList(new ObjectIdentity()
.withWorkspace(wsName).withName(fileName))).get(0);
} catch (ServerException se) {
if (!se.getMessage().contains("cannot be accessed")) {
throw se;
} //otherwise try again
Thread.sleep(PUSH_TO_WS_SLEEP_SEC * 1000);
}
}
@SuppressWarnings("unchecked")
Map<String, Object> data = wsObj.getData().asClassInstance(Map.class);
@SuppressWarnings("unchecked")
Map<String, Object> lib1 = (Map<String, Object>) data.get("lib1");
@SuppressWarnings("unchecked")
Map<String, Object> file = (Map<String, Object>) lib1.get("file");
String hid = (String) file.get("hid");
String shockID = (String) file.get("id");
String url = (String) file.get("url");
file.put("hid", "dummy");
file.put("id", "dummy");
file.put("url", "dummy");
MD5DigestOutputStream md5out = new MD5DigestOutputStream();
SORTED_MAPPER.writeValue(md5out, data);
assertThat("correct md5 for workspace object",
md5out.getMD5().getMD5(), is(workspaceDummyMD5));
//TODO check metadata
//TODO test provenance when added
Handle h = HANDLE_CLI.hidsToHandles(Arrays.asList(hid)).get(0);
assertThat("handle type correct", h.getType(), is("shock"));
assertThat("handle hid correct", h.getHid(), is(hid));
assertThat("handle shock id correct", h.getId(), is(shockID));
assertThat("handle url correct", h.getUrl(), is(url));
assertThat("correct version of object", wsObj.getInfo().getE5(),
is(expectedVersion));
assertThat("object type correct", wsObj.getInfo().getE3(),
is(type));
BasicShockClient shock = new BasicShockClient(new URL(url),
AuthService.login(KB_USER_1, KB_PWD_1).getToken(), true);
ShockNode node = shock.getNode(new ShockNodeId(shockID));
//can't check ACLs, can only check that file is accessible
//need to be owner to see ACLs
assertThat("Shock file md5 correct",
node.getFileInformation().getChecksum("md5"), is(shockMD5));
cli.closeAllWindows();
}
private String getMethodName() {
Exception e = new Exception();
e.fillInStackTrace();
return e.getStackTrace()[1].getMethodName();
}
private static void checkTimeout(Long startNanos, int timeoutSec,
String message) {
if ((System.nanoTime() - startNanos) / 1000000000 > timeoutSec) {
throw new TestException(message);
}
}
}
|
// LegacyImageMap.java
package imagej.legacy;
import ij.ImagePlus;
import ij.gui.ImageWindow;
import ij.gui.Roi;
import imagej.data.Dataset;
import imagej.data.roi.Overlay;
import imagej.display.Display;
import imagej.display.event.DisplayCreatedEvent;
import imagej.display.event.DisplayDeletedEvent;
import imagej.event.EventSubscriber;
import imagej.event.Events;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* An image map between IJ1 {@link ImagePlus} objects and IJ2 {@link Display}s.
* Because every {@link ImagePlus} has a corresponding {@link ImageWindow} and
* vice versa, it works out best to associate each {@link ImagePlus} with a
* {@link Display} rather than with a {@link Dataset}.
* <p>
* Any {@link Overlay}s present in the {@link Display} are translated to a
* {@link Roi} attached to the {@link ImagePlus}, and vice versa.
* </p>
* <p>
* In the case of one {@link Dataset} belonging to multiple {@link Display}s,
* there is a separate {@link ImagePlus} for each {@link Display}, with pixels
* by reference.
* </p>
* <p>
* In the case of multiple {@link Dataset}s in a single {@link Display}, only
* the first {@link Dataset} is translated to the {@link ImagePlus}.
* </p>
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class LegacyImageMap {
// -- Fields --
/** Table of {@link ImagePlus} objects corresponding to {@link Display}s. */
private final Map<Display, ImagePlus> imagePlusTable;
/** Table of {@link Display} objects corresponding to {@link ImagePlus}es. */
private final Map<ImagePlus, Display> displayTable;
/**
* The {@link ImageTranslator} to use when creating {@link ImagePlus} and
* {@link Display} objects corresponding to one another.
*/
private final ImageTranslator imageTranslator;
/** List of event subscribers, to avoid garbage collection. */
private final ArrayList<EventSubscriber<?>> subscribers;
// -- Constructor --
public LegacyImageMap() {
imagePlusTable = new ConcurrentHashMap<Display, ImagePlus>();
displayTable = new ConcurrentHashMap<ImagePlus, Display>();
imageTranslator = new DefaultImageTranslator();
subscribers = new ArrayList<EventSubscriber<?>>();
subscribeToEvents();
}
// -- LegacyImageMap methods --
/**
* Gets the {@link ImageTranslator} used to create {@link ImagePlus} and
* {@link Display} objects linked to one another.
*/
public ImageTranslator getTranslator() {
return imageTranslator;
}
/**
* Gets the {@link Display} corresponding to the given {@link ImagePlus}, or
* null if there is no existing table entry.
*/
public Display lookupDisplay(final ImagePlus imp) {
if (imp == null) return null;
return displayTable.get(imp);
}
/**
* Gets the {@link ImagePlus} corresponding to the given {@link Display}, or
* null if there is no existing table entry.
*/
public ImagePlus lookupImagePlus(final Display display) {
if (display == null) return null;
return imagePlusTable.get(display);
}
/**
* Ensures that the given {@link Display} has a corresponding legacy image.
*
* @return the {@link ImagePlus} object shadowing the given {@link Display},
* creating it if necessary using the {@link ImageTranslator}.
*/
public ImagePlus registerDisplay(final Display display) {
ImagePlus imp = lookupImagePlus(display);
if (imp == null) {
// mapping does not exist; mirror display to image window
imp = imageTranslator.createLegacyImage(display);
imagePlusTable.put(display, imp);
displayTable.put(imp, display);
}
return imp;
}
/**
* Ensures that the given legacy image has a corresponding {@link Display}.
*
* @return the {@link Display} object shadowing the given {@link ImagePlus},
* creating it if necessary using the {@link ImageTranslator}.
*/
public Display registerLegacyImage(final ImagePlus imp) {
Display display = lookupDisplay(imp);
if (display == null) {
// mapping does not exist; mirror legacy image to display
display = imageTranslator.createDisplay(imp);
imagePlusTable.put(display, imp);
displayTable.put(imp, display);
}
return display;
}
/** Removes the mapping associated with the given {@link Display}. */
public void unregisterDisplay(final Display display) {
final ImagePlus imp = lookupImagePlus(display);
if (display != null) displayTable.remove(display);
if (imp != null) {
imagePlusTable.remove(imp);
LegacyUtils.deleteImagePlus(imp);
}
}
/** Removes the mapping associated with the given {@link ImagePlus}. */
public void unregisterLegacyImage(final ImagePlus imp) {
final Display display = lookupDisplay(imp);
if (display != null) displayTable.remove(display);
if (imp != null) {
imagePlusTable.remove(imp);
LegacyUtils.deleteImagePlus(imp);
}
}
// -- Helper methods --
private void subscribeToEvents() {
final EventSubscriber<DisplayCreatedEvent> creationSubscriber =
new EventSubscriber<DisplayCreatedEvent>() {
@Override
public void onEvent(final DisplayCreatedEvent event) {
registerDisplay(event.getObject());
}
};
subscribers.add(creationSubscriber);
Events.subscribe(DisplayCreatedEvent.class, creationSubscriber);
final EventSubscriber<DisplayDeletedEvent> deletionSubscriber =
new EventSubscriber<DisplayDeletedEvent>() {
@Override
public void onEvent(final DisplayDeletedEvent event) {
unregisterDisplay(event.getObject());
}
};
subscribers.add(deletionSubscriber);
Events.subscribe(DisplayDeletedEvent.class, deletionSubscriber);
}
}
|
package unit.tests;
import gr.ntua.vision.monitoring.VismoVMInfo;
import gr.ntua.vision.monitoring.metrics.HostCPULoad;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import junit.framework.TestCase;
public class HostCPULoadTest extends TestCase {
private HostCPULoad cpuLoad;
private final CountDownLatch latch = new CountDownLatch(2);
private final VismoVMInfo vm = new VismoVMInfo();
/**
* @throws IOException
* @throws InterruptedException
*/
public void testShouldGetCPULoad() throws IOException, InterruptedException {
cpuLoad = new HostCPULoad();
final double load = cpuLoad.get();
latch.await();
System.err.println("cpu load for this host (" + vm.getAddress().getHostAddress() + ") is about " + load);
assertTrue("expecting cpu load for jvm to be greater than zero", load > 0);
}
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
final PrimeCountingThread t1 = new PrimeCountingThread(latch);
t1.setDaemon(true);
final PrimeCountingThread t2 = new PrimeCountingThread(latch);
t2.setDaemon(true);
t1.start();
t2.start();
}
}
|
// LegacyImageMap.java
package imagej.legacy;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import imagej.data.Dataset;
import imagej.util.Index;
import java.util.Map;
import java.util.WeakHashMap;
import net.imglib2.img.Axes;
import net.imglib2.img.ImgPlus;
import net.imglib2.img.basictypeaccess.PlanarAccess;
/**
* TODO
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class LegacyImageMap {
// -- instance variables --
private Map<ImagePlus, Dataset> imageTable =
new WeakHashMap<ImagePlus, Dataset>();
private ImageTranslator imageTranslator = new DefaultImageTranslator();
private LegacyMetadataTranslator metadataTranslator =
new LegacyMetadataTranslator();
// -- public interface --
/**
* Ensures that the given legacy image has a corresponding dataset.
*
* @return the {@link Dataset} object shadowing this legacy image.
*/
public Dataset registerLegacyImage(ImagePlus imp) {
synchronized (imageTable) {
Dataset dataset = imageTable.get(imp);
if (dataset == null) {
// mirror image window to dataset
dataset = imageTranslator.createDataset(imp);
imageTable.put(imp, dataset);
}
else { // dataset was already existing
reconcileDifferences(dataset, imp);
}
return dataset;
}
}
/**
* Ensures that the given dataset has a corresponding legacy image.
*
* @return the {@link ImagePlus} object shadowing this dataset.
*/
public ImagePlus registerDataset(Dataset dataset) {
// find image window
ImagePlus imp = null;
synchronized (imageTable) {
for (final ImagePlus key : imageTable.keySet()) {
final Dataset value = imageTable.get(key);
if (dataset == value) {
imp = key;
break;
}
}
if (imp == null) {
// mirror dataset to image window
imp = imageTranslator.createLegacyImage(dataset);
imageTable.put(imp, dataset);
}
}
WindowManager.setTempCurrentImage(imp);
return imp;
}
// -- private helpers --
/** changes the data within a Dataset to match data in an ImagePlus */
private void reconcileDifferences(Dataset ds, ImagePlus imp) {
// is our dataset not sharing planes with the ImagePlus by reference?
// if so assume any change possible and thus rebuild all
if ( ! (ds.getImgPlus().getImg() instanceof PlanarAccess) ) {
rebuildNonplanarData(ds, imp);
return;
}
// color data is not shared by reference
// any change to plane data must somehow be copied back
// the easiest way to copy back is via new creation
if (imp.getType() == ImagePlus.COLOR_RGB) {
rebuildData(ds, imp);
return;
}
// if here we know its not a RGB imp. If we were a color Dataset
// then forget that fact now.
ds.setRGBMerged(false);
// was a slice added or deleted?
if (dimensionsDifferent(ds, imp)) {
rebuildData(ds, imp);
return;
}
// if here we know we have planar backing
// the plane references could have changed in some way:
// - setPixels, setProcessor, stack rearrangement, etc.
// its easier to always reassign them rather than
// calculate exactly what to do
assignPlaneReferences(ds, imp);
// make sure metadata accurately updated
metadataTranslator.setDatasetMetadata(ds,imp);
// TODO - any other cases?
// Since we are storing planes by reference we're done
ds.update();
}
/** fills a nonplanar Dataset's values with data from an ImagePlus */
private void rebuildNonplanarData(Dataset ds, ImagePlus imp) {
Dataset tmpDs = imageTranslator.createDataset(imp);
ds.copyDataFrom(tmpDs);
}
/** fills a Dataset's values with data from an ImagePlus */
private void rebuildData(Dataset ds, ImagePlus imp) {
Dataset tmpDs = imageTranslator.createDataset(imp);
ds.setImgPlus(tmpDs.getImgPlus());
}
/** determines whether a Dataset and an ImagePlus have different dimensionality */
private boolean dimensionsDifferent(Dataset ds, ImagePlus imp) {
ImgPlus<?> imgPlus = ds.getImgPlus();
boolean different =
dimensionDifferent(imgPlus, ds.getAxisIndex(Axes.X), imp.getWidth()) ||
dimensionDifferent(imgPlus, ds.getAxisIndex(Axes.Y), imp.getHeight()) ||
dimensionDifferent(imgPlus, ds.getAxisIndex(Axes.CHANNEL), imp.getNChannels()) ||
dimensionDifferent(imgPlus, ds.getAxisIndex(Axes.Z), imp.getNSlices()) ||
dimensionDifferent(imgPlus, ds.getAxisIndex(Axes.TIME), imp.getNFrames());
if ( ! different )
if ( LegacyUtils.hasNonIJ1Axes(imgPlus) )
throw new IllegalStateException(
"Dataset associated with ImagePlus has axes incompatible with IJ1");
return different;
}
/** determines whether a single dimension in an ImgPlus differs from
* a given value */
private boolean dimensionDifferent(ImgPlus<?> imgPlus, int axis, int value) {
if (axis >= 0)
return imgPlus.dimension(axis) != value;
// axis < 0 : not present in imgPlus
return value != 1;
}
/** assigns the plane references of a planar Dataset to match the plane
* references of a given ImagePlus
*/
private void assignPlaneReferences(Dataset ds, ImagePlus imp) {
ImageStack stack = imp.getStack();
if (stack == null) { // just a 2d image
Object pixels = imp.getProcessor().getPixels();
ds.setPlane(0, pixels);
return;
}
int zIndex = ds.getAxisIndex(Axes.Z);
int cIndex = ds.getAxisIndex(Axes.CHANNEL);
int tIndex = ds.getAxisIndex(Axes.TIME);
int z = (int) ( (zIndex < 0) ? 1 : ds.getImgPlus().dimension(zIndex) );
int c = (int) ( (cIndex < 0) ? 1 : ds.getImgPlus().dimension(cIndex) );
int t = (int) ( (tIndex < 0) ? 1 : ds.getImgPlus().dimension(tIndex) );
long[] planeDims = new long[ds.getImgPlus().numDimensions()-2];
if (zIndex >= 0) planeDims[zIndex-2] = z;
if (cIndex >= 0) planeDims[cIndex-2] = c;
if (tIndex >= 0) planeDims[tIndex-2] = t;
long[] planePos = new long[planeDims.length];
int imagejPlaneNumber = 1;
for (int ti = 0; ti < t; ti++) {
if (tIndex >= 0) planePos[tIndex-2] = ti;
for (int zi = 0; zi < z; zi++) {
if (zIndex >= 0) planePos[zIndex-2] = zi;
for (int ci = 0; ci < c; ci++) {
if (cIndex >= 0) planePos[cIndex-2] = ci;
long imglibPlaneNumber = Index.indexNDto1D(planeDims, planePos);
Object plane = stack.getPixels(imagejPlaneNumber);
ds.setPlane((int)imglibPlaneNumber, plane);
imagejPlaneNumber++;
}
}
}
}
}
|
package com.sequenceiq.cloudbreak.service.stack.flow;
import static com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status.AVAILABLE;
import static com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status.DELETED_ON_PROVIDER_SIDE;
import static com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status.DELETE_FAILED;
import static com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status.STOPPED;
import static com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status.WAIT_FOR_SYNC;
import static com.sequenceiq.cloudbreak.cloud.model.CloudInstance.INSTANCE_NAME;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.CLUSTER_FAILED_NODES_REPORTED;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_SYNC_INSTANCE_DELETED_BY_PROVIDER_CBMETADATA;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_SYNC_INSTANCE_DELETED_CBMETADATA;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_SYNC_INSTANCE_STATE_SYNCED;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_SYNC_INSTANCE_STATUS_RETRIEVAL_FAILED;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DetailedStackStatus;
import com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceStatus;
import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException;
import com.sequenceiq.cloudbreak.cloud.model.CloudInstance;
import com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus;
import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException;
import com.sequenceiq.cloudbreak.common.json.Json;
import com.sequenceiq.cloudbreak.core.CloudbreakImageNotFoundException;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceGroup;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData;
import com.sequenceiq.cloudbreak.service.StackUpdater;
import com.sequenceiq.cloudbreak.service.cluster.ClusterService;
import com.sequenceiq.cloudbreak.service.image.ImageService;
import com.sequenceiq.cloudbreak.service.stack.InstanceMetaDataService;
import com.sequenceiq.cloudbreak.service.stack.StackService;
import com.sequenceiq.cloudbreak.service.stack.connector.adapter.ServiceProviderMetadataAdapter;
import com.sequenceiq.cloudbreak.structuredevent.event.CloudbreakEventService;
@Service
public class StackSyncService {
private static final Logger LOGGER = LoggerFactory.getLogger(StackSyncService.class);
private static final String SYNC_STATUS_REASON = "Synced instance states with the cloud provider.";
@Inject
private StackService stackService;
@Inject
private StackUpdater stackUpdater;
@Inject
private CloudbreakEventService eventService;
@Inject
private InstanceMetaDataService instanceMetaDataService;
@Inject
private ServiceProviderMetadataAdapter metadata;
@Inject
private ImageService imageService;
@Inject
private ClusterService clusterService;
public void updateInstances(Stack stack, Iterable<InstanceMetaData> instanceMetaDataList, Collection<CloudVmInstanceStatus> instanceStatuses,
boolean stackStatusUpdateEnabled) {
try {
Map<InstanceSyncState, Integer> counts = initInstanceStateCounts();
Json imageJson = new Json(imageService.getImage(stack.getId()));
for (InstanceMetaData metaData : instanceMetaDataList) {
Optional<CloudVmInstanceStatus> status = instanceStatuses.stream()
.filter(is -> is != null && is.getCloudInstance().getInstanceId() != null
&& is.getCloudInstance().getInstanceId().equals(metaData.getInstanceId()))
.findFirst();
InstanceSyncState state;
if (status.isPresent()) {
CloudVmInstanceStatus cloudVmInstanceStatus = status.get();
CloudInstance cloudInstance = cloudVmInstanceStatus.getCloudInstance();
state = InstanceSyncState.getInstanceSyncState(cloudVmInstanceStatus.getStatus());
syncInstance(metaData, cloudInstance, imageJson);
} else {
state = InstanceSyncState.DELETED;
}
syncInstanceStatusByState(stack, counts, metaData, state);
}
handleSyncResult(stack, counts, stackStatusUpdateEnabled);
} catch (CloudbreakImageNotFoundException | IllegalArgumentException ex) {
LOGGER.info("Error during stack sync:", ex);
throw new CloudbreakServiceException("Stack sync failed", ex);
}
}
public void sync(Long stackId, boolean stackStatusUpdateEnabled) {
Stack stack = stackService.getByIdWithListsInTransaction(stackId);
// TODO: is it a good condition?
if (stack.isStackInDeletionPhase() || stack.isModificationInProgress()) {
LOGGER.debug("Stack could not be synchronized in {} state!", stack.getStatus());
} else {
sync(stack, stackStatusUpdateEnabled);
}
}
private void sync(Stack stack, boolean stackStatusUpdateEnabled) {
Long stackId = stack.getId();
Set<InstanceMetaData> instances = instanceMetaDataService.findNotTerminatedForStack(stackId);
Map<InstanceSyncState, Integer> instanceStateCounts = initInstanceStateCounts();
for (InstanceMetaData instance : instances) {
InstanceGroup instanceGroup = instance.getInstanceGroup();
try {
InstanceSyncState state = metadata.getState(stack, instanceGroup, instance.getInstanceId());
syncInstanceStatusByState(stack, instanceStateCounts, instance, state);
} catch (CloudConnectorException e) {
LOGGER.warn(e.getMessage(), e);
eventService.fireCloudbreakEvent(stackId, AVAILABLE.name(),
STACK_SYNC_INSTANCE_STATUS_RETRIEVAL_FAILED,
Collections.singletonList(instance.getInstanceId()));
instanceStateCounts.put(InstanceSyncState.UNKNOWN, instanceStateCounts.get(InstanceSyncState.UNKNOWN) + 1);
}
}
handleSyncResult(stack, instanceStateCounts, stackStatusUpdateEnabled);
}
private void syncInstance(InstanceMetaData instanceMetaData, CloudInstance cloudInstance, Json imageJson) {
String instanceName = cloudInstance.getStringParameter(INSTANCE_NAME);
instanceMetaData.setInstanceName(instanceName);
if (instanceMetaData.getImage() == null) {
instanceMetaData.setImage(imageJson);
}
instanceMetaDataService.save(instanceMetaData);
}
public void autoSync(Stack stack, Collection<InstanceMetaData> instances, List<CloudVmInstanceStatus> instanceStatuses,
boolean stackStatusUpdateEnabled, InstanceSyncState defaultState) {
Map<String, InstanceSyncState> instanceSyncStates = instanceStatuses.stream()
.collect(Collectors.toMap(i -> i.getCloudInstance().getInstanceId(), i -> InstanceSyncState.getInstanceSyncState(i.getStatus())));
Map<InstanceSyncState, Integer> instanceStateCounts = initInstanceStateCounts();
for (InstanceMetaData instance : instances) {
try {
syncInstanceStatusByState(stack, instanceStateCounts, instance,
instanceSyncStates.getOrDefault(instance.getInstanceId(), defaultState));
} catch (CloudConnectorException e) {
LOGGER.warn(e.getMessage(), e);
eventService.fireCloudbreakEvent(stack.getId(), AVAILABLE.name(),
STACK_SYNC_INSTANCE_STATUS_RETRIEVAL_FAILED,
Collections.singletonList(instance.getInstanceId()));
instanceStateCounts.put(InstanceSyncState.UNKNOWN, instanceStateCounts.get(InstanceSyncState.UNKNOWN) + 1);
}
}
handleSyncResult(stack, instanceStateCounts, stackStatusUpdateEnabled);
}
private void syncInstanceStatusByState(Stack stack, Map<InstanceSyncState, Integer> counts, InstanceMetaData metaData, InstanceSyncState state) {
if (InstanceSyncState.DELETED.equals(state)
|| InstanceSyncState.DELETED_ON_PROVIDER_SIDE.equals(state)
|| InstanceSyncState.DELETED_BY_PROVIDER.equals(state)) {
syncDeletedInstance(stack, counts, metaData, state);
} else if (InstanceSyncState.RUNNING.equals(state)) {
syncRunningInstance(stack, counts, metaData);
} else if (InstanceSyncState.STOPPED.equals(state)) {
syncStoppedInstance(stack, counts, metaData);
} else {
counts.put(state, counts.getOrDefault(state, 0) + 1);
}
}
private void syncStoppedInstance(Stack stack, Map<InstanceSyncState, Integer> instanceStateCounts, InstanceMetaData instance) {
instanceStateCounts.put(InstanceSyncState.STOPPED, instanceStateCounts.get(InstanceSyncState.STOPPED) + 1);
if (!instance.isTerminated() && instance.getInstanceStatus() != InstanceStatus.STOPPED) {
LOGGER.debug("Instance '{}' is reported as stopped on the cloud provider, setting its state to STOPPED.", instance.getInstanceId());
instance.setInstanceStatus(InstanceStatus.STOPPED);
instanceMetaDataService.save(instance);
}
}
private void syncRunningInstance(Stack stack, Map<InstanceSyncState, Integer> instanceStateCounts, InstanceMetaData instance) {
instanceStateCounts.put(InstanceSyncState.RUNNING, instanceStateCounts.get(InstanceSyncState.RUNNING) + 1);
if (stack.getStatus() == WAIT_FOR_SYNC && instance.isCreated()) {
LOGGER.debug("Instance '{}' is reported as created on the cloud provider but not member of the cluster, setting its state to FAILED.",
instance.getInstanceId());
instance.setInstanceStatus(InstanceStatus.FAILED);
instanceMetaDataService.save(instance);
} else if (!instance.isRunning()) {
LOGGER.info("Instance '{}' is reported as running on the cloud provider, updating metadata.", instance.getInstanceId());
updateMetaDataToRunning(instance);
}
}
private void syncDeletedInstance(Stack stack, Map<InstanceSyncState, Integer> instanceStateCounts, InstanceMetaData instance, InstanceSyncState state) {
if (!instance.isTerminated() || !instance.isDeletedOnProvider()) {
if (instance.getInstanceId() == null) {
instanceStateCounts.put(InstanceSyncState.DELETED, instanceStateCounts.get(InstanceSyncState.DELETED) + 1);
LOGGER.debug("Instance with private id '{}' don't have instanceId, setting its state to DELETED.",
instance.getPrivateId());
instance.setInstanceStatus(InstanceStatus.TERMINATED);
instanceMetaDataService.save(instance);
} else {
instanceStateCounts.put(state, instanceStateCounts.get(state) + 1);
LOGGER.debug("Instance '{}' is reported as deleted on the cloud provider, setting its state to {}.",
instance.getInstanceId(), state.name());
eventService.fireCloudbreakEvent(stack.getId(), "RECOVERY",
CLUSTER_FAILED_NODES_REPORTED,
Collections.singletonList(instance.getDiscoveryFQDN()));
if (InstanceSyncState.DELETED_BY_PROVIDER.equals(state)) {
updateMetaDataToDeletedByProvider(stack, instance);
} else {
updateMetaDataToDeletedOnProviderSide(stack, instance);
}
}
}
}
private void handleSyncResult(Stack stack, Map<InstanceSyncState, Integer> instanceStateCounts, boolean stackStatusUpdateEnabled) {
Set<InstanceMetaData> instances = instanceMetaDataService.findNotTerminatedForStackWithoutInstanceGroups(stack.getId());
if (instanceStateCounts.get(InstanceSyncState.RUNNING) > 0 && stack.getStatus() != AVAILABLE) {
updateStackStatusIfEnabled(stack.getId(), DetailedStackStatus.AVAILABLE, SYNC_STATUS_REASON, stackStatusUpdateEnabled);
eventService.fireCloudbreakEvent(stack.getId(), AVAILABLE.name(), STACK_SYNC_INSTANCE_STATE_SYNCED);
} else if (isAllStopped(instanceStateCounts, instances.size()) && stack.getStatus() != STOPPED) {
updateStackStatusIfEnabled(stack.getId(), DetailedStackStatus.STOPPED, SYNC_STATUS_REASON, stackStatusUpdateEnabled);
updateClusterStatusIfEnabled(stack.getId(), STOPPED, stackStatusUpdateEnabled);
eventService.fireCloudbreakEvent(stack.getId(), STOPPED.name(), STACK_SYNC_INSTANCE_STATE_SYNCED);
} else if (isAllDeletedOnProvider(instanceStateCounts, instances.size()) && stack.getStatus() != DELETE_FAILED) {
updateStackStatusIfEnabled(stack.getId(), DetailedStackStatus.DELETED_ON_PROVIDER_SIDE, SYNC_STATUS_REASON, stackStatusUpdateEnabled);
updateClusterStatusIfEnabled(stack.getId(), DELETED_ON_PROVIDER_SIDE, stackStatusUpdateEnabled);
eventService.fireCloudbreakEvent(stack.getId(), DELETED_ON_PROVIDER_SIDE.name(), STACK_SYNC_INSTANCE_STATE_SYNCED);
}
}
private boolean isAllDeletedOnProvider(Map<InstanceSyncState, Integer> instanceStateCounts, int numberOfInstances) {
return instanceStateCounts.get(InstanceSyncState.DELETED_ON_PROVIDER_SIDE) + instanceStateCounts.get(InstanceSyncState.DELETED_BY_PROVIDER) > 0
&& numberOfInstances == 0;
}
private boolean isAllStopped(Map<InstanceSyncState, Integer> instanceStateCounts, int numberOfInstances) {
return instanceStateCounts.get(InstanceSyncState.STOPPED).equals(numberOfInstances) && numberOfInstances > 0;
}
private void updateStackStatusIfEnabled(Long stackId, DetailedStackStatus status, String statusReason, boolean stackStatusUpdateEnabled) {
if (stackStatusUpdateEnabled) {
stackUpdater.updateStackStatus(stackId, status, statusReason);
}
}
private void updateClusterStatusIfEnabled(Long stackId, Status status, boolean stackStatusUpdateEnabled) {
if (stackStatusUpdateEnabled) {
clusterService.updateClusterStatusByStackId(stackId, status);
}
}
private Map<InstanceSyncState, Integer> initInstanceStateCounts() {
Map<InstanceSyncState, Integer> instanceStates = new EnumMap<>(InstanceSyncState.class);
instanceStates.put(InstanceSyncState.DELETED, 0);
instanceStates.put(InstanceSyncState.DELETED_ON_PROVIDER_SIDE, 0);
instanceStates.put(InstanceSyncState.DELETED_BY_PROVIDER, 0);
instanceStates.put(InstanceSyncState.STOPPED, 0);
instanceStates.put(InstanceSyncState.RUNNING, 0);
instanceStates.put(InstanceSyncState.IN_PROGRESS, 0);
instanceStates.put(InstanceSyncState.UNKNOWN, 0);
return instanceStates;
}
private void updateMetaDataToDeletedOnProviderSide(Stack stack, InstanceMetaData instanceMetaData) {
instanceMetaData.setInstanceStatus(InstanceStatus.DELETED_ON_PROVIDER_SIDE);
instanceMetaDataService.save(instanceMetaData);
eventService.fireCloudbreakEvent(stack.getId(), AVAILABLE.name(), STACK_SYNC_INSTANCE_DELETED_CBMETADATA,
Collections.singletonList(getInstanceName(instanceMetaData)));
}
private void updateMetaDataToDeletedByProvider(Stack stack, InstanceMetaData instanceMetaData) {
instanceMetaData.setInstanceStatus(InstanceStatus.DELETED_BY_PROVIDER);
instanceMetaDataService.save(instanceMetaData);
eventService.fireCloudbreakEvent(stack.getId(), AVAILABLE.name(), STACK_SYNC_INSTANCE_DELETED_BY_PROVIDER_CBMETADATA,
Collections.singletonList(getInstanceName(instanceMetaData)));
}
private String getInstanceName(InstanceMetaData instanceMetaData) {
return instanceMetaData.getDiscoveryFQDN() == null
? instanceMetaData.getInstanceId()
: String.format("%s (%s)", instanceMetaData.getInstanceId(), instanceMetaData.getDiscoveryFQDN());
}
private void updateMetaDataToRunning(InstanceMetaData instanceMetaData) {
LOGGER.info("Instance '{}' state to RUNNING.", instanceMetaData.getInstanceId());
instanceMetaData.setInstanceStatus(InstanceStatus.SERVICES_RUNNING);
instanceMetaData.setStatusReason("Services running");
instanceMetaDataService.save(instanceMetaData);
}
}
|
package vasco.soot;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import soot.MethodContext;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.callgraph.ContextSensitiveEdge;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalUnitGraph;
import vasco.ProgramRepresentation;
/**
* A program representation for Soot using the Jimple IR with a context-sensitive
* call graph. This representation uses control-flow graphs of individual units including exceptional
* control flow, and resolves virtual calls using the call graph returned by
* {@link soot.Scene#getContextSensitiveCallGraph() Scene#getContextSensitiveCallGraph}.
*
* <p><strong>Note</strong>: This class follows the Singleton pattern. The singleton
* object is available through {@link #v()}.</p>
*
* @author Rohan Padhye
*
*/
public class ContextSensitiveJimpleRepresentation implements ProgramRepresentation<MethodOrMethodContext, Unit> {
// Cache for control flow graphs
private Map<SootMethod, DirectedGraph<Unit>> cfgCache;
// Private constructor, see #v() to retrieve singleton object
private ContextSensitiveJimpleRepresentation() {
cfgCache = new HashMap<SootMethod, DirectedGraph<Unit>>();
}
/**
* Returns a singleton list containing the <code>main</code> method.
* @see Scene#getMainMethod()
*/
@Override
public List<MethodOrMethodContext> getEntryPoints() {
return Collections.singletonList(MethodContext.v(Scene.v().getMainMethod(), null));
}
/**
* Returns an {@link ExceptionalUnitGraph} for a given method.
*/
@Override
public DirectedGraph<Unit> getControlFlowGraph(MethodOrMethodContext momc) {
if (cfgCache.containsKey(momc.method()) == false) {
cfgCache.put(momc.method(), new ExceptionalUnitGraph(momc.method().getActiveBody()));
}
return cfgCache.get(momc.method());
}
/**
* Returns <code>true</code> iff the Jimple statement contains an
* invoke expression.
*/
@Override
public boolean isCall(Unit node) {
return ((soot.jimple.Stmt) node).containsInvokeExpr();
}
/**
* Resolves virtual calls using the Soot's context-sensitive call graph and returns
* a list of method-contexts which are the targets of explicit edges.
*/
@Override
public List<MethodOrMethodContext> resolveTargets(MethodOrMethodContext momc, Unit node) {
List<MethodOrMethodContext> targets = new LinkedList<MethodOrMethodContext>();
@SuppressWarnings("rawtypes")
Iterator it = Scene.v().getContextSensitiveCallGraph().edgesOutOf(momc.context(), momc.method(), node);
while(it.hasNext()) {
ContextSensitiveEdge edge = (ContextSensitiveEdge) it.next();
if (edge.kind().isExplicit()) {
targets.add(MethodContext.v(edge.tgt(), edge.tgtCtxt()));
}
}
return targets;
}
// The singleton object
private static ContextSensitiveJimpleRepresentation singleton = new ContextSensitiveJimpleRepresentation();
/**
* Returns a reference to the singleton object of this class.
*/
public static ContextSensitiveJimpleRepresentation v() { return singleton; }
}
|
package com.badlogic.gdx.ingenuity.utils;
import static com.badlogic.gdx.Input.Keys.D;
import static com.badlogic.gdx.Input.Keys.DOWN;
import static com.badlogic.gdx.Input.Keys.L;
import static com.badlogic.gdx.Input.Keys.LEFT;
import static com.badlogic.gdx.Input.Keys.MINUS;
import static com.badlogic.gdx.Input.Keys.N;
import static com.badlogic.gdx.Input.Keys.O;
import static com.badlogic.gdx.Input.Keys.P;
import static com.badlogic.gdx.Input.Keys.PERIOD;
import static com.badlogic.gdx.Input.Keys.PLUS;
import static com.badlogic.gdx.Input.Keys.RIGHT;
import static com.badlogic.gdx.Input.Keys.UP;
import static com.badlogic.gdx.Input.Keys.Z;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.utils.DragListener;
import com.badlogic.gdx.utils.Align;
/**
* @ Mitkey
* @ 2016411 9:35:08
* @: actor P
* @ xx
*/
public class MoveListener extends DragListener {
private static final String TAG = MoveListener.class.getSimpleName();
private static final String format = "%s X %sY %s %s";
private static int STEP_XY = 1;
Actor actor;
float originX;
float originY;
float x;
float y;
boolean debug;
public MoveListener(Actor actor) {
this.actor = actor;
this.originX = actor.getOriginX();
this.originY = actor.getOriginY();
this.x = actor.getX();
this.y = actor.getY();
}
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
actor.getStage().setKeyboardFocus(actor);
return super.touchDown(event, x, y, pointer, button);
}
@Override
public void drag(InputEvent event, float x, float y, int pointer) {
super.drag(event, x, y, pointer);
actor.moveBy(x - getTouchDownX(), y - getTouchDownY());
}
@Override
public boolean keyDown(InputEvent event, int keycode) {
switch (keycode) {
case UP :
actor.moveBy(0, STEP_XY);
break;
case DOWN :
actor.moveBy(0, -STEP_XY);
break;
case LEFT :
actor.moveBy(-STEP_XY, 0);
break;
case RIGHT :
actor.moveBy(STEP_XY, 0);
break;
case P :
Gdx.app.log(TAG, String.format(format, actor, actor.getX(), actor.getY(), STEP_XY));
break;
case PERIOD :
STEP_XY = 1;
break;
case PLUS :
STEP_XY += 1;
break;
case MINUS :
STEP_XY -= 1;
break;
case D :// debug
debug = !debug;
actor.getStage().setDebugAll(debug);
break;
case L :// actor
actor.addAction(generalLightAction());
break;
case Z :
actor.setPosition(x, y);
break;
case N :
x = actor.getX();
y = actor.getY();
break;
case O :
actor.setPosition(0, 0);
break;
default :
break;
}
return false;
}
private Action generalLightAction() {
actor.clearActions();
actor.setRotation(0);
actor.setOrigin(originX, originY);
return Actions.sequence(
Actions.run(new Runnable() {
@Override
public void run() {
actor.setOrigin(Align.center);
}
}),
Actions.repeat(2,
Actions.sequence(
Actions.rotateTo(360, 0.2f),
Actions.rotateTo(0, 0)
)),
Actions.run(new Runnable() {
@Override
public void run() {
actor.setOrigin(originX, originY);
}
}));
}
}
|
package hudson.tasks.junit;
import com.thoughtworks.xstream.XStream;
import hudson.XmlFile;
import hudson.model.AbstractBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.tasks.test.TestObject;
import hudson.util.HeapSpaceStringConverter;
import hudson.util.XStream2;
import org.kohsuke.stapler.StaplerProxy;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link Action} that displays the JUnit test result.
*
* <p>
* The actual test reports are isolated by {@link WeakReference}
* so that it doesn't eat up too much memory.
*
* @author Kohsuke Kawaguchi
*/
public class TestResultAction extends AbstractTestResultAction<TestResultAction> implements StaplerProxy {
private transient WeakReference<TestResult> result;
// Hudson < 1.25 didn't set these fields, so use Integer
// so that we can distinguish between 0 tests vs not-computed-yet.
private int failCount;
private int skipCount;
private Integer totalCount;
private List<Data> testData = new ArrayList<Data>();
public TestResultAction(AbstractBuild owner, TestResult result, BuildListener listener) {
super(owner);
setResult(result, listener);
}
/**
* Overwrites the {@link TestResult} by a new data set.
*/
public synchronized void setResult(TestResult result, BuildListener listener) {
result.freeze(this);
totalCount = result.getTotalCount();
failCount = result.getFailCount();
skipCount = result.getSkipCount();
// persist the data
try {
getDataFile().write(result);
} catch (IOException e) {
e.printStackTrace(listener.fatalError("Failed to save the JUnit test result"));
}
this.result = new WeakReference<TestResult>(result);
}
private XmlFile getDataFile() {
return new XmlFile(XSTREAM,new File(owner.getRootDir(), "junitResult.xml"));
}
public synchronized TestResult getResult() {
TestResult r;
if(result==null) {
r = load();
result = new WeakReference<TestResult>(r);
} else {
r = result.get();
}
if(r==null) {
r = load();
result = new WeakReference<TestResult>(r);
}
if(totalCount==null) {
totalCount = r.getTotalCount();
failCount = r.getFailCount();
skipCount = r.getSkipCount();
}
return r;
}
@Override
public int getFailCount() {
if(totalCount==null)
getResult(); // this will compute the result
return failCount;
}
@Override
public int getSkipCount() {
if(totalCount==null)
getResult(); // this will compute the result
return skipCount;
}
@Override
public int getTotalCount() {
if(totalCount==null)
getResult(); // this will compute the result
return totalCount;
}
@Override
public List<CaseResult> getFailedTests() {
return getResult().getFailedTests();
}
/**
* Loads a {@link TestResult} from disk.
*/
private TestResult load() {
TestResult r;
try {
r = (TestResult)getDataFile().read();
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to load "+getDataFile(),e);
r = new TestResult(); // return a dummy
}
r.freeze(this);
return r;
}
public Object getTarget() {
return getResult();
}
public List<TestAction> getActions(TestObject object) {
List<TestAction> result = new ArrayList<TestAction>();
// Added check for null testData to avoid NPE from issue 4257.
if (testData!=null) {
for (Data data : testData) {
result.addAll(data.getTestAction(object));
}
}
return Collections.unmodifiableList(result);
}
public void setData(List<Data> testData) {
this.testData = testData;
}
/**
* Resolves {@link TestAction}s for the given {@link TestObject}.
*
* <p>
* This object itself is persisted as a part of {@link AbstractBuild}, so it needs to be XStream-serializable.
*
* @see TestDataPublisher
*/
public static abstract class Data {
/**
* Returns all TestActions for the testObject.
*
* @return
* Can be empty but never null. The caller must assume that the returned list is read-only.
*/
public abstract List<? extends TestAction> getTestAction(hudson.tasks.junit.TestObject testObject);
}
public Object readResolve() {
super.readResolve(); // let it do the post-deserialization work
if (testData == null) {
testData = new ArrayList<Data>();
}
return this;
}
private static final Logger logger = Logger.getLogger(TestResultAction.class.getName());
private static final XStream XSTREAM = new XStream2();
static {
XSTREAM.alias("result",TestResult.class);
XSTREAM.alias("suite",SuiteResult.class);
XSTREAM.alias("case",CaseResult.class);
XSTREAM.registerConverter(new HeapSpaceStringConverter(),100);
}
}
|
package hudson.util;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class ArgumentListBuilderTest {
@Test
public void assertEmptyMask() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg");
builder.add("other", "arguments");
assertFalse("There shouldnt be any masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, false }));
}
@Test
public void assertLastArgumentIsMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg");
builder.addMasked("ismasked");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, true }));
}
@Test
public void assertSeveralMaskedArguments() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg");
builder.addMasked("ismasked");
builder.add("non masked arg");
builder.addMasked("ismasked2");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, true, false, true }));
}
@Test
public void assertPrependAfterAddingMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.addMasked("ismasked");
builder.add("arg");
builder.prepend("first", "second");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, true, false }));
}
@Test
public void assertPrependBeforeAddingMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.prepend("first", "second");
builder.addMasked("ismasked");
builder.add("arg");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, true, false }));
}
@Test
public void testToWindowsCommand() {
ArgumentListBuilder builder = new ArgumentListBuilder(
"ant.bat", "-Dfoo1=abc", // nothing special, no quotes
"-Dfoo2=foo bar", "-Dfoo3=/u*r", "-Dfoo4=/us?", // add quotes
"-Dfoo10=bar,baz",
"-Dfoo5=foo;bar^baz", "-Dfoo6=<xml>&here;</xml>", // add quotes
"-Dfoo7=foo|bar\"baz", // add quotes and "" for "
"-Dfoo8=% %QED% %comspec% %-%(%.%", // add quotes, and extra quotes for %Q and %c
"-Dfoo9=%'''%%@%"); // no quotes as none of the % are followed by a letter
// By default, does not escape %VAR%
assertThat(builder.toWindowsCommand().toCommandArray(), is(new String[] { "cmd.exe", "/C",
"\"ant.bat -Dfoo1=abc \"-Dfoo2=foo bar\""
+ " \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^baz\""
+ " \"-Dfoo6=<xml>&here;</xml>\" \"-Dfoo7=foo|bar\"\"baz\""
+ " \"-Dfoo8=% %QED% %comspec% %-%(%.%\""
+ " -Dfoo9=%'''%%@% && exit %%ERRORLEVEL%%\"" }));
// Pass flag to escape %VAR%
assertThat(builder.toWindowsCommand(true).toCommandArray(), is(new String[] { "cmd.exe", "/C",
"\"ant.bat -Dfoo1=abc \"-Dfoo2=foo bar\""
+ " \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^baz\""
+ " \"-Dfoo6=<xml>&here;</xml>\" \"-Dfoo7=foo|bar\"\"baz\""
+ " \"-Dfoo8=% %\"Q\"ED% %\"c\"omspec% %-%(%.%\""
|
package com.simplifiedlogic.nitro.jshell.json.handler;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import com.simplifiedlogic.nitro.jlink.data.AssembleInstructions;
import com.simplifiedlogic.nitro.jlink.data.FileAssembleResults;
import com.simplifiedlogic.nitro.jlink.data.FileInfoResults;
import com.simplifiedlogic.nitro.jlink.data.FileListInstancesResults;
import com.simplifiedlogic.nitro.jlink.data.FileOpenResults;
import com.simplifiedlogic.nitro.jlink.data.JLAccuracy;
import com.simplifiedlogic.nitro.jlink.data.JLConstraintInput;
import com.simplifiedlogic.nitro.jlink.data.JLTransform;
import com.simplifiedlogic.nitro.jlink.data.ListMaterialResults;
import com.simplifiedlogic.nitro.jlink.data.MasspropsData;
import com.simplifiedlogic.nitro.jlink.intf.IJLFile;
import com.simplifiedlogic.nitro.jshell.json.request.JLFileRequestParams;
import com.simplifiedlogic.nitro.jshell.json.response.JLFileResponseParams;
import com.simplifiedlogic.nitro.rpc.JLIException;
/**
* Handle JSON requests for "file" functions
*
* @author Adam Andrews
*
*/
public class JLJsonFileHandler extends JLJsonCommandHandler implements JLFileRequestParams, JLFileResponseParams {
private IJLFile fileHandler = null;
/**
* @param fileHandler
*/
public JLJsonFileHandler(IJLFile fileHandler) {
this.fileHandler = fileHandler;
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jshell.json.handler.JLJsonCommandHandler#handleFunction(java.lang.String, java.lang.String, java.util.Hashtable)
*/
public Hashtable<String, Object> handleFunction(String sessionId, String function, Hashtable<String, Object> input) throws JLIException {
if (function==null)
return null;
if (function.equals(FUNC_OPEN)) return actionOpen(sessionId, input);
else if (function.equals(FUNC_OPEN_ERRORS)) return actionOpenErrors(sessionId, input);
else if (function.equals(FUNC_RENAME)) return actionRename(sessionId, input);
else if (function.equals(FUNC_SAVE)) return actionSave(sessionId, input);
else if (function.equals(FUNC_BACKUP)) return actionBackup(sessionId, input);
else if (function.equals(FUNC_ERASE)) return actionErase(sessionId, input);
else if (function.equals(FUNC_ERASE_NOT_DISP)) return actionEraseNotDisplayed(sessionId, input);
else if (function.equals(FUNC_REGENERATE)) return actionRegenerate(sessionId, input);
else if (function.equals(FUNC_REFRESH)) return actionRefresh(sessionId, input);
else if (function.equals(FUNC_REPAINT)) return actionRepaint(sessionId, input);
else if (function.equals(FUNC_DISPLAY)) return actionDisplay(sessionId, input);
else if (function.equals(FUNC_CLOSE_WINDOW)) return actionCloseWindow(sessionId, input);
else if (function.equals(FUNC_GET_ACTIVE)) return actionGetActive(sessionId, input);
else if (function.equals(FUNC_IS_ACTIVE)) return actionIsActive(sessionId, input);
else if (function.equals(FUNC_LIST)) return actionList(sessionId, input);
else if (function.equals(FUNC_EXISTS)) return actionExists(sessionId, input);
else if (function.equals(FUNC_GET_FILEINFO)) return actionGetFileinfo(sessionId, input);
else if (function.equals(FUNC_RELATIONS_GET)) return actionRelationsGet(sessionId, input);
else if (function.equals(FUNC_RELATIONS_SET)) return actionRelationsSet(sessionId, input);
else if (function.equals(FUNC_POST_REGEN_RELATIONS_GET)) return actionPostRegenRelationsGet(sessionId, input);
else if (function.equals(FUNC_POST_REGEN_RELATIONS_SET)) return actionPostRegenRelationsSet(sessionId, input);
else if (function.equals(FUNC_HAS_INSTANCES)) return actionHasInstances(sessionId, input);
else if (function.equals(FUNC_LIST_INSTANCES)) return actionListInstances(sessionId, input);
else if (function.equals(FUNC_MASSPROPS)) return actionMassprops(sessionId, input);
else if (function.equals(FUNC_GET_LENGTH_UNITS)) return actionGetLengthUnits(sessionId, input);
else if (function.equals(FUNC_GET_MASS_UNITS)) return actionGetMassUnits(sessionId, input);
else if (function.equals(FUNC_SET_LENGTH_UNITS)) return actionSetLengthUnits(sessionId, input);
else if (function.equals(FUNC_SET_MASS_UNITS)) return actionSetMassUnits(sessionId, input);
else if (function.equals(FUNC_ASSEMBLE)) return actionAssemble(sessionId, input);
else if (function.equals(FUNC_GET_TRANSFORM)) return actionGetTransform(sessionId, input);
else if (function.equals(FUNC_LIST_SIMP_REPS)) return actionListSimpReps(sessionId, input);
else if (function.equals(FUNC_GET_CUR_MATL)) return actionGetCurrentMaterial(sessionId, input);
else if (function.equals(FUNC_GET_CUR_MATL_WILDCARD)) return actionGetCurrentMaterialWildcard(sessionId, input);
else if (function.equals(FUNC_SET_CUR_MATL)) return actionSetCurrentMaterial(sessionId, input);
else if (function.equals(FUNC_LIST_MATERIALS)) return actionListMaterials(sessionId, input);
else if (function.equals(FUNC_LIST_MATERIALS_WILDCARD)) return actionListMaterialsWildcard(sessionId, input);
else if (function.equals(FUNC_LOAD_MATL_FILE)) return actionLoadMaterialFile(sessionId, input);
else if (function.equals(FUNC_DELETE_MATERIAL)) return actionDeleteMaterial(sessionId, input);
else if (function.equals(FUNC_GET_ACCURACY)) return actionGetAccuracy(sessionId, input);
else {
throw new JLIException("Unknown function name: " + function);
}
}
private Hashtable<String, Object> actionOpen(String sessionId, Hashtable<String, Object> input) throws JLIException {
String dirname = checkStringParameter(input, PARAM_DIRNAME, false);
String filename = checkStringParameter(input, PARAM_MODEL, false);
Object namesObj = checkParameter(input, PARAM_MODELS, false);
List<String> filenames = null;
if (namesObj!=null) {
filenames = getStringListValue(namesObj);
}
String generic = checkStringParameter(input, PARAM_GENERIC, false);
boolean display = checkFlagParameter(input, PARAM_DISPLAY, false, false);
boolean activate = checkFlagParameter(input, PARAM_ACTIVATE, false, false);
boolean newwin = checkFlagParameter(input, PARAM_NEWWIN, false, false);
boolean regen_force = checkFlagParameter(input, PARAM_FORCE, false, false);
if (filename==null && filenames==null)
throw new JLIException("No filename or filenames parameter given");
FileOpenResults result = fileHandler.open(dirname, filename, filenames, generic, display, activate, newwin, regen_force, sessionId);
if (result!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
if (result.getDirname()!=null)
out.put(OUTPUT_DIRNAME, result.getDirname());
if (result.getFilenames()!=null)
out.put(OUTPUT_FILES, result.getFilenames());
if (result.getFileRevision()>0)
out.put(OUTPUT_REVISION, result.getFileRevision());
return out;
}
return null;
}
private Hashtable<String, Object> actionOpenErrors(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
boolean errors = fileHandler.openErrors(filename, sessionId);
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_ERRORS, errors);
return out;
}
private Hashtable<String, Object> actionRename(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String newname = checkStringParameter(input, PARAM_NEWNAME, true);
boolean onlysession = checkFlagParameter(input, PARAM_ONLYSESSION, false, false);
String newFilename = fileHandler.rename(filename, newname, onlysession, sessionId);
if (newFilename!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_MODEL, newFilename);
return out;
}
return null;
}
private Hashtable<String, Object> actionSave(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
List<String> filenames = null;
Object namesObj = checkParameter(input, PARAM_MODELS, false);
if (namesObj!=null) {
filenames = getStringListValue(namesObj);
}
fileHandler.save(filename, filenames, sessionId);
return null;
}
private Hashtable<String, Object> actionBackup(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, true);
String targetdir = checkStringParameter(input, PARAM_TARGETDIR, true);
fileHandler.backup(filename, targetdir, sessionId);
return null;
}
private Hashtable<String, Object> actionErase(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
List<String> filenames = null;
Object namesObj = checkParameter(input, PARAM_MODELS, false);
if (namesObj!=null) {
filenames = getStringListValue(namesObj);
}
boolean eraseChildren = checkFlagParameter(input, PARAM_ERASE_CHILDREN, false, false);
fileHandler.erase(filename, filenames, eraseChildren, sessionId);
return null;
}
private Hashtable<String, Object> actionEraseNotDisplayed(String sessionId, Hashtable<String, Object> input) throws JLIException {
fileHandler.eraseNotDisplayed(sessionId);
return null;
}
private Hashtable<String, Object> actionRegenerate(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
List<String> filenames = null;
Object namesObj = checkParameter(input, PARAM_MODELS, false);
if (namesObj!=null) {
filenames = getStringListValue(namesObj);
}
boolean display = checkFlagParameter(input, PARAM_DISPLAY, false, false);
fileHandler.regenerate(filename, filenames, display, sessionId);
return null;
}
private Hashtable<String, Object> actionGetActive(String sessionId, Hashtable<String, Object> input) throws JLIException {
FileOpenResults result = fileHandler.getActive(sessionId);
if (result!=null && result.hasFile()) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
if (result.getDirname()!=null)
out.put(OUTPUT_DIRNAME, result.getDirname());
out.put(OUTPUT_MODEL, result.getFilenames()[0]);
return out;
}
return null;
}
private Hashtable<String, Object> actionList(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
List<String> filenames = null;
Object namesObj = checkParameter(input, PARAM_MODELS, false);
if (namesObj!=null) {
filenames = getStringListValue(namesObj);
}
List<String> files = fileHandler.list(filename, filenames, sessionId);
if (files!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_FILES, files);
return out;
}
return null;
}
private Hashtable<String, Object> actionExists(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, true);
boolean exists = fileHandler.exists(filename, sessionId);
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_EXISTS, exists);
return out;
}
private Hashtable<String, Object> actionGetFileinfo(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
FileInfoResults result = fileHandler.getFileinfo(filename, sessionId);
if (result!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
if (result.getDirname()!=null)
out.put(OUTPUT_DIRNAME, result.getDirname());
if (result.getFilename()!=null)
out.put(OUTPUT_MODEL, result.getFilename());
if (result.getFileRevision()>0)
out.put(OUTPUT_REVISION, result.getFileRevision());
return out;
}
return null;
}
private Hashtable<String, Object> actionHasInstances(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
boolean exists = fileHandler.hasInstances(filename, sessionId);
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_EXISTS, exists);
return out;
}
private Hashtable<String, Object> actionListInstances(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
FileListInstancesResults result = fileHandler.listInstances(filename, sessionId);
if (result!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
if (result.getDirname()!=null)
out.put(OUTPUT_DIRNAME, result.getDirname());
if (result.getGeneric()!=null)
out.put(OUTPUT_GENERIC, result.getGeneric());
if (result.getInstances()!=null && result.getInstances().size()>0)
out.put(OUTPUT_FILES, result.getInstances());
return out;
}
return null;
}
private Hashtable<String, Object> actionMassprops(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
MasspropsData result = fileHandler.massprops(filename, sessionId);
if (result!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_VOLUME, result.getVolume());
out.put(OUTPUT_MASS, result.getMass());
out.put(OUTPUT_DENSITY, result.getDensity());
out.put(OUTPUT_SURFACE_AREA, result.getSurfaceArea());
if (result.getCenterGravityInertiaTensor()!=null) {
Hashtable<String, Object> tmp = writeInertia(result.getCenterGravityInertiaTensor());
if (tmp!=null)
out.put(OUTPUT_CTR_GRAV_INERTIA_TENSOR, tmp);
}
if (result.getCoordSysInertia()!=null) {
Hashtable<String, Object> tmp = writeInertia(result.getCoordSysInertia());
if (tmp!=null)
out.put(OUTPUT_COORD_SYS_INERTIA, tmp);
}
if (result.getCoordSysInertiaTensor()!=null) {
Hashtable<String, Object> tmp = writeInertia(result.getCoordSysInertiaTensor());
if (tmp!=null)
out.put(OUTPUT_COORD_SYS_INERTIA_TENSOR, tmp);
}
return out;
}
return null;
}
private Hashtable<String, Object> actionGetMassUnits(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String units = fileHandler.getMassUnits(filename, sessionId);
if (units!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_UNITS, units);
return out;
}
return null;
}
private Hashtable<String, Object> actionSetMassUnits(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String units = checkStringParameter(input, PARAM_UNITS, true);
boolean convert = checkFlagParameter(input, PARAM_CONVERT, false, true);
fileHandler.setMassUnits(filename, units, convert, sessionId);
return null;
}
private Hashtable<String, Object> actionGetLengthUnits(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String units = fileHandler.getLengthUnits(filename, sessionId);
if (units!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_UNITS, units);
return out;
}
return null;
}
private Hashtable<String, Object> actionSetLengthUnits(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String units = checkStringParameter(input, PARAM_UNITS, true);
boolean convert = checkFlagParameter(input, PARAM_CONVERT, false, true);
fileHandler.setLengthUnits(filename, units, convert, sessionId);
return null;
}
private Hashtable<String, Object> actionRelationsGet(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
List<String> rels = fileHandler.getRelations(filename, sessionId);
if (rels!=null && rels.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_RELATIONS, rels);
return out;
}
return null;
}
private Hashtable<String, Object> actionRelationsSet(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
Object relsObj = checkParameter(input, PARAM_RELATIONS, false);
List<String> rels = null;
if (relsObj!=null)
rels = getStringListValue(relsObj);
fileHandler.setRelations(filename, rels, sessionId);
return null;
}
private Hashtable<String, Object> actionPostRegenRelationsGet(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
List<String> rels = fileHandler.getPostRegenRelations(filename, sessionId);
if (rels!=null && rels.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_RELATIONS, rels);
return out;
}
return null;
}
private Hashtable<String, Object> actionPostRegenRelationsSet(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
Object relsObj = checkParameter(input, PARAM_RELATIONS, false);
List<String> rels = null;
if (relsObj!=null)
rels = getStringListValue(relsObj);
fileHandler.setPostRegenRelations(filename, rels, sessionId);
return null;
}
@SuppressWarnings("unchecked")
private Hashtable<String, Object> actionAssemble(String sessionId, Hashtable<String, Object> input) throws JLIException {
String dirname = checkStringParameter(input, PARAM_DIRNAME, false);
String filename = checkStringParameter(input, PARAM_MODEL, true);
String generic = checkStringParameter(input, PARAM_GENERIC, false);
String asm = checkStringParameter(input, PARAM_INTOASM, false);
List<Integer> path = getIntArray(PARAM_PATH, checkParameter(input, PARAM_PATH, false));
Map<String, Object> transData = checkMapParameter(input, PARAM_TRANSFORM, false);
JLTransform transform = readTransform(transData);
Object constraintObj = checkParameter(input, PARAM_CONSTRAINTS, false);
List<JLConstraintInput> constraints = null;
if (constraintObj!=null) {
if (constraintObj instanceof List<?>) {
constraints = new ArrayList<JLConstraintInput>();
for (Object o : (List<?>)constraintObj) {
if (!(o instanceof Map<?, ?>))
throw new JLIException("Invalid data for constraint: " + o);
constraints.add(readConstraint((Map<String, Object>)o));
}
}
else if (constraintObj instanceof Map<?, ?>) {
constraints = new ArrayList<JLConstraintInput>();
constraints.add(readConstraint((Map<String, Object>)constraintObj));
}
else {
throw new JLIException("Invalid data for constraints: " + constraintObj);
}
}
boolean packageAssembly = checkFlagParameter(input, PARAM_PACKAGE_ASSEMBLY, false, false);
String refModel = checkStringParameter(input, PARAM_REF_MODEL, false);
boolean walkChildren = checkFlagParameter(input, PARAM_WALK_CHILDREN, false, false);
boolean assembleToRoot = checkFlagParameter(input, PARAM_ASSEMBLE_TO_ROOT, false, false);
boolean suppress = checkFlagParameter(input, PARAM_SUPPRESS, false, false);
AssembleInstructions instr = new AssembleInstructions();
instr.setDirname(dirname);
instr.setFilename(filename);
instr.setGenericName(generic);
instr.setIntoAsm(asm);
instr.setComponentPath(path);
instr.setTransData(transform);
instr.setConstraints(constraints);
instr.setPackageAssembly(packageAssembly);
instr.setRefModel(refModel);
instr.setWalkChildren(walkChildren);
instr.setAssembleToRoot(assembleToRoot);
instr.setSuppress(suppress);
FileAssembleResults result = fileHandler.assemble(instr, sessionId);
if (result!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
if (result.getDirname()!=null)
out.put(OUTPUT_DIRNAME, result.getDirname());
if (result.getFilenames()!=null)
out.put(OUTPUT_FILES, result.getFilenames());
if (result.getFileRevision()>0)
out.put(OUTPUT_REVISION, result.getFileRevision());
if (result.getFeatureId()>0)
out.put(OUTPUT_FEATUREID, result.getFeatureId());
return out;
}
return null;
}
private Hashtable<String, Object> actionRefresh(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
fileHandler.refresh(filename, sessionId);
return null;
}
private Hashtable<String, Object> actionRepaint(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
fileHandler.repaint(filename, sessionId);
return null;
}
private Hashtable<String, Object> actionGetTransform(String sessionId, Hashtable<String, Object> input) throws JLIException {
String asm = checkStringParameter(input, PARAM_ASM, false);
List<Integer> path = getIntArray(PARAM_PATH, checkParameter(input, PARAM_PATH, false));
String csys = checkStringParameter(input, PARAM_CSYS, false);
JLTransform transform = fileHandler.getTransform(asm, path, csys, sessionId);
if (transform!=null) {
Hashtable<String, Object> out = writeTransform(transform);
return out;
}
return null;
}
private Hashtable<String, Object> actionIsActive(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, true);
boolean active = fileHandler.isActive(filename, sessionId);
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_ACTIVE, active);
return out;
}
private Hashtable<String, Object> actionDisplay(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, true);
boolean activate = checkFlagParameter(input, PARAM_ACTIVATE, false, false);
fileHandler.display(filename, activate, sessionId);
return null;
}
private Hashtable<String, Object> actionCloseWindow(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
fileHandler.closeWindow(filename, sessionId);
return null;
}
private Hashtable<String, Object> actionListSimpReps(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String repname = checkStringParameter(input, PARAM_REP, false);
List<String> reps = fileHandler.listSimpReps(filename, repname, sessionId);
if (reps!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_REPS, reps);
return out;
}
return null;
}
private Hashtable<String, Object> actionGetCurrentMaterial(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
if (isPattern(filename))
throw new JLIException("Not allowed to use wildcards in "+PARAM_MODEL+" argument.");
List<ListMaterialResults> matls = fileHandler.getCurrentMaterial(filename, false, sessionId);
if (matls!=null && matls.size()>0) {
String matl = matls.get(0).getMaterialName();
if (matl==null)
return null;
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_MATERIAL, matl);
return out;
}
return null;
}
private Hashtable<String, Object> actionGetCurrentMaterialWildcard(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
boolean includeNonMatchingParts = checkFlagParameter(input, PARAM_INCLUDE_NON_MATCHING, false, false);
List<ListMaterialResults> matls = fileHandler.getCurrentMaterial(filename, includeNonMatchingParts, sessionId);
if (matls!=null && matls.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
Vector<Map<String, Object>> outMatls = new Vector<Map<String, Object>>();
Map<String, Object> outMatl = null;
for (ListMaterialResults matl : matls) {
outMatl = new Hashtable<String, Object>();
if (matl.getFilename()!=null)
outMatl.put(PARAM_MODEL, matl.getFilename());
if (matl.getMaterialName()!=null)
outMatl.put(PARAM_MATERIAL, matl.getMaterialName());
outMatls.add(outMatl);
}
if (outMatls.size()>0)
out.put(OUTPUT_MATERIALS, outMatls);
return out;
}
return null;
}
private Hashtable<String, Object> actionSetCurrentMaterial(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String materialName = checkStringParameter(input, PARAM_MATERIAL, true);
List<String> files = fileHandler.setCurrentMaterial(filename, materialName, sessionId);
if (files!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_FILES, files);
return out;
}
return null;
}
private Hashtable<String, Object> actionListMaterials(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
if (isPattern(filename))
throw new JLIException("Not allowed to use wildcards in "+PARAM_MODEL+" argument.");
String materialName = checkStringParameter(input, PARAM_MATERIAL, false);
List<ListMaterialResults> result = fileHandler.listMaterials(filename, materialName, true, sessionId);
if (result!=null && result.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
List<String> matls = new ArrayList<String>();
for (ListMaterialResults res : result)
if (res.getMaterialName()!=null)
matls.add(res.getMaterialName());
if (matls.size()>0)
out.put(OUTPUT_MATERIALS, matls);
return out;
}
return null;
}
private Hashtable<String, Object> actionListMaterialsWildcard(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String materialName = checkStringParameter(input, PARAM_MATERIAL, false);
boolean includeNonMatchingParts = checkFlagParameter(input, PARAM_INCLUDE_NON_MATCHING, false, false);
List<ListMaterialResults> matls = fileHandler.listMaterials(filename, materialName, includeNonMatchingParts, sessionId);
if (matls!=null && matls.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
Vector<Map<String, Object>> outMatls = new Vector<Map<String, Object>>();
Map<String, Object> outMatl = null;
for (ListMaterialResults matl : matls) {
outMatl = new Hashtable<String, Object>();
if (matl.getFilename()!=null)
outMatl.put(PARAM_MODEL, matl.getFilename());
if (matl.getMaterialName()!=null)
outMatl.put(PARAM_MATERIAL, matl.getMaterialName());
outMatls.add(outMatl);
}
if (outMatls.size()>0)
out.put(OUTPUT_MATERIALS, outMatls);
return out;
}
return null;
}
private Hashtable<String, Object> actionLoadMaterialFile(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String dirname = checkStringParameter(input, PARAM_DIRNAME, false);
String materialName = checkStringParameter(input, PARAM_MATERIAL, true);
List<String> files = fileHandler.loadMaterialFile(filename, dirname, materialName, false, sessionId);
if (files!=null && files.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_MODELS, files);
return out;
}
return null;
}
private Hashtable<String, Object> actionDeleteMaterial(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
String materialName = checkStringParameter(input, PARAM_MATERIAL, true);
List<String> files = fileHandler.deleteMaterial(filename, materialName, sessionId);
if (files!=null && files.size()>0) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_MODELS, files);
return out;
}
return null;
}
private Hashtable<String, Object> actionGetAccuracy(String sessionId, Hashtable<String, Object> input) throws JLIException {
String filename = checkStringParameter(input, PARAM_MODEL, false);
JLAccuracy accuracy = fileHandler.getAccuracy(filename, sessionId);
if (accuracy!=null) {
Hashtable<String, Object> out = new Hashtable<String, Object>();
out.put(OUTPUT_ACCURACY, String.valueOf(accuracy.getAccuracy()));
out.put(OUTPUT_RELATIVE, String.valueOf(accuracy.isRelative()));
return out;
}
return null;
}
protected JLConstraintInput readConstraint(Map<String, Object> rec) throws JLIException {
if (rec==null)
return null;
JLConstraintInput con = new JLConstraintInput();
String typeString = checkStringParameter(rec, PARAM_TYPE, true);
String asmref = checkStringParameter(rec, PARAM_ASMREF, false);
String compref = checkStringParameter(rec, PARAM_COMPREF, false);
String asmDatumString = checkStringParameter(rec, PARAM_ASMDATUM, false);
String compDatumString = checkStringParameter(rec, PARAM_COMPDATUM, false);
Double offset = checkDoubleParameter(rec, PARAM_OFFSET, false);
con.setType(typeString);
con.setAsmref(asmref);
con.setCompref(compref);
if (asmDatumString!=null) {
if (DATUM_SIDE_RED.equalsIgnoreCase(asmDatumString))
con.setAsmDatum(JLConstraintInput.DATUM_SIDE_RED);
else if (DATUM_SIDE_YELLOW.equalsIgnoreCase(asmDatumString))
con.setAsmDatum(JLConstraintInput.DATUM_SIDE_YELLOW);
else
throw new JLIException("Invalid value for " + PARAM_ASMDATUM + ": " + asmDatumString);
}
else
con.setAsmDatum(JLConstraintInput.DATUM_SIDE_NONE);
if (compDatumString!=null) {
if (DATUM_SIDE_RED.equalsIgnoreCase(compDatumString))
con.setCompDatum(JLConstraintInput.DATUM_SIDE_RED);
else if (DATUM_SIDE_YELLOW.equalsIgnoreCase(compDatumString))
con.setCompDatum(JLConstraintInput.DATUM_SIDE_YELLOW);
else
throw new JLIException("Invalid value for " + PARAM_COMPDATUM + ": " + compDatumString);
}
else
con.setCompDatum(JLConstraintInput.DATUM_SIDE_NONE);
if (offset!=null)
con.setOffset(offset.doubleValue());
return con;
}
}
|
//$HeadURL$
package org.deegree.commons.utils;
import org.deegree.commons.utils.CollectionUtils.Mapper;
/**
* <code>Triple</code>
*
* @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
* @param <T>
* @param <U>
* @param <V>
*/
public final class Triple<T, U, V> {
public T first;
public U second;
public V third;
public Triple() {
// null values
}
/**
* @param t
* @param u
* @param v
*/
public Triple( T t, U u, V v ) {
first = t;
second = u;
third = v;
}
@Override
public boolean equals( Object other ) {
if ( other != null && other instanceof Triple<?, ?, ?> ) {
// what ever, unchecked.
final Triple<?, ?, ?> that = (Triple<?, ?, ?>) other;
return ( first == null ? that.first == null : first.equals( that.first ) )
&& ( second == null ? that.second == null : second.equals( that.second ) )
&& ( third == null ? that.third == null : third.equals( that.third ) );
}
return false;
}
/**
* Implementation as proposed by Joshua Block in Effective Java (Addison-Wesley 2001), which supplies an even
* distribution and is relatively fast. It is created from field <b>f</b> as follows:
* <ul>
* <li>boolean -- code = (f ? 0 : 1)</li>
* <li>byte, char, short, int -- code = (int)f</li>
* <li>long -- code = (int)(f ^ (f >>>32))</li>
* <li>float -- code = Float.floatToIntBits(f);</li>
* <li>double -- long l = Double.doubleToLongBits(f); code = (int)(l ^ (l >>> 32))</li>
* <li>all Objects, (where equals( ) calls equals( ) for this field) -- code = f.hashCode( )</li>
* <li>Array -- Apply above rules to each element</li>
* </ul>
* <p>
* Combining the hash code(s) computed above: result = 37 * result + code;
* </p>
*
* @return (int) ( result >>> 32 ) ^ (int) result;
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// the 2nd millionth prime, :-)
long result = 32452843;
if ( first != null ) {
result = result * 37 + first.hashCode();
}
if ( second != null ) {
result = result * 37 + second.hashCode();
}
if ( third != null ) {
result = result * 37 + third.hashCode();
}
return (int) ( result >>> 32 ) ^ (int) result;
}
@Override
public String toString() {
return "<" + first + ", " + second + ", " + third + ">";
}
public static <T, U, V> Mapper<T, Triple<T, U, V>> FIRST() {
return new Mapper<T, Triple<T, U, V>>() {
@Override
public T apply( Triple<T, U, V> u ) {
return u.first;
}
};
}
public static <T, U, V> Mapper<U, Triple<T, U, V>> SECOND() {
return new Mapper<U, Triple<T, U, V>>() {
@Override
public U apply( Triple<T, U, V> u ) {
return u.second;
}
};
}
public static <T, U, V> Mapper<V, Triple<T, U, V>> THIRD() {
return new Mapper<V, Triple<T, U, V>>() {
@Override
public V apply( Triple<T, U, V> u ) {
return u.third;
}
};
}
}
|
package edu.utah.sci.cyclist.core.ui.views;
import org.controlsfx.control.RangeSlider;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.MapProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleMapProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import edu.utah.sci.cyclist.core.event.dnd.DnD;
import edu.utah.sci.cyclist.core.model.DataType.FilterType;
import edu.utah.sci.cyclist.core.model.Field;
import edu.utah.sci.cyclist.core.model.FieldProperties;
import edu.utah.sci.cyclist.core.model.Filter;
import edu.utah.sci.cyclist.core.model.Table;
import edu.utah.sci.cyclist.core.model.DataType.Role;
import edu.utah.sci.cyclist.core.model.Table.NumericRangeValues;
import edu.utah.sci.cyclist.core.ui.components.Spring;
import edu.utah.sci.cyclist.core.ui.panels.TitledPanel;
import edu.utah.sci.cyclist.core.util.AwesomeIcon;
import edu.utah.sci.cyclist.core.util.GlyphRegistry;
import edu.utah.sci.cyclist.core.util.SQL;
public class FilterPanel extends TitledPanel {
private Filter _filter;
private ListProperty<Object> _valuesProperty = new SimpleListProperty<>();
private VBox _cbBox;
private ProgressIndicator _indicator;
private Button _closeButton;
private Task<?> _task;
private boolean _reportChange = true;
private BooleanProperty _highlight = new SimpleBooleanProperty(false);
MapProperty<Object, Object> _map = new SimpleMapProperty<>();
private ObjectProperty<EventHandler<ActionEvent>> _closeAction = new SimpleObjectProperty<>();
public BooleanProperty highlight() {
return _highlight;
}
public void setHighlight(boolean value) {
_highlight.set(value);
}
public boolean getHighlight() {
return _highlight.get();
}
public FilterPanel(Filter filter) {
//super(filter.getName());
super(getTitle(filter), GlyphRegistry.get(AwesomeIcon.FILTER));//"FontAwesome|FILTER"));
_filter = filter;
build();
}
public Filter getFilter() {
return _filter;
}
public void setTask(Task<?> task) {
if (_task != null && _task.isRunning()) {
_task.cancel();
}
_task = task;
if (_task == null) {
_indicator.visibleProperty().unbind();
_indicator.setVisible(false);
} else {
_indicator.visibleProperty().bind(_task.runningProperty());
_indicator.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
System.out.println("Canceling task: "+_task.cancel());
}
});
}
}
/*
* Close
*/
public ObjectProperty<EventHandler<ActionEvent>> onCloseProperty() {
return _closeAction;
}
public EventHandler<ActionEvent> getOnClose() {
return _closeAction.get();
}
public void setOnClose(EventHandler<ActionEvent> handler) {
_closeAction.set(handler);
}
private void build() {
setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
final HBox header = getHeader();
_indicator = new ProgressIndicator();
_indicator.setProgress(-1);
_indicator.setMaxWidth(20);
_indicator.setMaxHeight(20);
_indicator.setVisible(false);
_closeButton = new Button();
_closeButton.getStyleClass().add("flat-button");
_closeButton.setGraphic(GlyphRegistry.get(AwesomeIcon.TIMES));//"FontAwesome|TIMES"));
_closeButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
setTask(null);
if(getOnClose() != null){
getOnClose().handle(e);
}
}
});
header.getChildren().addAll(_indicator, new Spring(), _closeButton);
header.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Dragboard db = header.startDragAndDrop(TransferMode.MOVE);
DnD.LocalClipboard clipboard = DnD.getInstance().createLocalClipboard();
clipboard.put(DnD.FILTER_FORMAT, Filter.class, _filter);
ClipboardContent content = new ClipboardContent();
content.putString(_filter.getName());
SnapshotParameters snapParams = new SnapshotParameters();
snapParams.setFill(Color.TRANSPARENT);
content.putImage(header.getChildren().get(0).snapshot(snapParams, null));
db.setContent(content);
}
});
header.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
_highlight.set(!_highlight.get());
}
});
_highlight.addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean oldValue, Boolean newValue) {
if (newValue)
getHeader().setStyle("-fx-background-color: #beffbf");
else
getHeader().setStyle("-fx-background-color: #e0e0ef");
}
});
_filter.setOnDSUpdated((Void)->configure());
configure();
}
private void configure() {
switch (_filter.getClassification()) {
case C:
createList();
break;
case Cdate:
createRange();
break;
case Qd:
createRange();
break;
case Qi:
if(_filter.getFilterType() == FilterType.RANGE){
createRange();
}else{
createList();
}
}
}
private void createList() {
_cbBox = new VBox();
_cbBox.setSpacing(4);
_cbBox.setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
setContent(_cbBox);
_valuesProperty.addListener(new InvalidationListener() {
@Override
public void invalidated(Observable arg0) {
populateValues();
}
});
_valuesProperty.bind(_filter.valuesProperty());
if (!_filter.isValid()) {
Field field = _filter.getField();
Table table = field.getTable();
Task<ObservableList<Object>> task = table.getFieldValues(_filter.getDatasource(),field);
setTask(task);
field.valuesProperty().bind(task.valueProperty());
} else {
populateValues();
}
}
private void populateValues() {
_cbBox.getChildren().clear();
if (_valuesProperty.get() != null) {
_cbBox.getChildren().add(createAllEntry());
for (Object item: _valuesProperty.get()) {
_cbBox.getChildren().add(createEntry(item));
}
}
}
private Node createAllEntry() {
CheckBox cb = new CheckBox("All");
cb.setSelected(true);
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean oldValue, Boolean newValue) {
_reportChange = false;
for (Node node : _cbBox.getChildren()) {
((CheckBox) node).setSelected(newValue);
}
_reportChange = true;
_filter.selectAll(newValue);
}
});
return cb;
}
private Node createEntry(final Object item) {
CheckBox cb = new CheckBox(item.toString());
cb.setSelected(_filter.isSelected(item));
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean oldValue, Boolean newValue) {
if (_reportChange)
_filter.selectValue(item, newValue);
}
});
return cb;
}
/* Name: createRange
* For numerical Fields - get the possible minimum and maximum values of the field
* and creates a filter within that range */
private void createRange() {
_cbBox = new VBox();
_cbBox.setSpacing(4);
_cbBox.setPrefSize(USE_COMPUTED_SIZE,USE_COMPUTED_SIZE);
setContent(_cbBox);
_cbBox.setPadding(new Insets(0,8,0,8));
_map.addListener(new InvalidationListener() {
@Override
public void invalidated(Observable arg0) {
populateRangeValues();
}
});
_map.bind(_filter.rangeValuesProperty());
if (!_filter.isRangeValid()) {
Field field = _filter.getField();
Table table = field.getTable();
Task<ObservableMap<Object,Object>> task = table.getFieldRange( _filter.getDatasource(), field);
setTask(task);
field.rangeValuesProperty().bind(task.valueProperty());
}
else{
populateRangeValues();
}
}
/* Name: populateRangeValues
* Populates a filter panel for a "measure" type filter.
* In this case there would be a range slider which displays the possible values in the range
* and the user can change the minimum and maximum values which are displayed */
private void populateRangeValues() {
_cbBox.getChildren().clear();
if (_map.get() != null) {
Double min = (Double) (_map.get(NumericRangeValues.MIN) != null ? _map.get(NumericRangeValues.MIN):0.0);
Double max = (Double) (_map.get(NumericRangeValues.MAX) != null ? _map.get(NumericRangeValues.MAX):0.0);
final RangeSlider rangeSlider = new RangeSlider(min,max,min,max);
rangeSlider.setShowTickLabels(true);
rangeSlider.setShowTickMarks(true);
//rangeSlider.setOrientation(Orientation.VERTICAL);
double currentWidth = this.widthProperty().doubleValue();
_cbBox.setPrefWidth(0.95*currentWidth);
double majorTicks = (rangeSlider.getMax()-rangeSlider.getMin())/4;
if(majorTicks > 0){
rangeSlider.setMajorTickUnit(majorTicks);
}
final HBox hbox = new HBox();
hbox.setSpacing(20);
final TextField minTxt = new TextField();
final TextField maxTxt = new TextField();
hbox.getChildren().addAll(minTxt, maxTxt);
hbox.setPrefWidth(currentWidth);
hbox.setSpacing(currentWidth-120);
minTxt.setPrefSize(80, 18);
maxTxt.setPrefSize(80, 18);
minTxt.setEditable(false);
maxTxt.setEditable(false);
minTxt.setAlignment(Pos.CENTER_LEFT);
maxTxt.setAlignment(Pos.CENTER_LEFT);
minTxt.setText(Double.toString(min));
maxTxt.setText(Double.toString(max));
_cbBox.getChildren().addAll(rangeSlider,hbox);
//Listen to the width property of the parent - so the slider width can be changed accordingly.
this.widthProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
double width = newValue.doubleValue();
_cbBox.setPrefWidth(0.95*width);
}
});
_cbBox.widthProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
double width = newValue.doubleValue();
hbox.setPrefWidth(width);
hbox.setSpacing(width-160);
}
});
// Change the filter's values according to the user new choice.
rangeSlider.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent e) {
_filter.selectMinMaxValues(rangeSlider.getLowValue(),rangeSlider.getHighValue());
}
});
// Update the text field to show the current value on the slider.
rangeSlider.setOnMouseDragged(new EventHandler<Event>() {
public void handle(Event e) {
minTxt.setText(Double.toString(rangeSlider.getLowValue()));
maxTxt.setText(Double.toString(rangeSlider.getHighValue()));
}
});
}
}
/* Name: getTitle
* Gets the filter name and function (if exists).
* If the filter is connected to a field, and the field has an aggregation function
* sets the filter panel header to display both the filter name and the function*/
private static String getTitle(Filter filter) {
String title = null;
if (filter.getRole() == Role.DIMENSION || filter.getRole() == Role.INT_TIME) {
title = filter.getName();
} else {
String funcName = filter.getField().get(FieldProperties.AGGREGATION_FUNC, String.class);
if (funcName == null){
funcName = filter.getField().get(FieldProperties.AGGREGATION_DEFAULT_FUNC, String.class);
filter.getField().set(FieldProperties.AGGREGATION_FUNC, funcName);
}
SQL.Function func = SQL.getFunction(funcName);
if (func == null)
title = filter.getName();
else
title = func.getLabel(filter.getName());
}
return title;
}
}
|
package org.ocelotds.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.enterprise.util.Nonbinding;
import javax.inject.Qualifier;
/**
* Annotation allows identify explosed classes to clients
*
* @author hhfrancois
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
public @interface DataService {
@Nonbinding String resolver();
@Nonbinding String name() default "";
}
|
import com.sun.star.beans.XPropertySet;
import com.sun.star.ui.ActionTriggerSeparatorType;
import com.sun.star.ui.ContextMenuInterceptorAction;
import com.sun.star.ui.XContextMenuInterceptor;
import com.sun.star.uno.UnoRuntime;
public class ContextMenuInterceptor implements XContextMenuInterceptor {
/**
*Description of the Method
*
*@param args Description of Parameter
*@since
*/
public static void main(String args[])
{
try {
OfficeConnect aConnect = OfficeConnect.createConnection();
com.sun.star.frame.XDesktop xDesktop =
(com.sun.star.frame.XDesktop)aConnect.createRemoteInstance(
com.sun.star.frame.XDesktop.class,"com.sun.star.frame.Desktop");
// create a new test document
com.sun.star.frame.XComponentLoader xCompLoader =
(com.sun.star.frame.XComponentLoader)UnoRuntime.queryInterface(
com.sun.star.frame.XComponentLoader.class, xDesktop);
com.sun.star.lang.XComponent xComponent =
xCompLoader.loadComponentFromURL("private:factory/swriter",
"_blank", 0, new com.sun.star.beans.PropertyValue[0]);
// intialize the test document
com.sun.star.frame.XFrame xFrame = null;
{
com.sun.star.text.XTextDocument xDoc =(com.sun.star.text.XTextDocument)
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComponent);
String infoMsg = new String("All context menus of the created document frame contains now a 'Help' entry with the submenus 'Content', 'Help Agent' and 'Tips'.\n\n Press 'Return' in the shell to remove the context menu interceptor and finish the example!");
xDoc.getText().setString(infoMsg);
// ensure that the document content is optimal visible
com.sun.star.frame.XModel xModel =
(com.sun.star.frame.XModel)UnoRuntime.queryInterface(
com.sun.star.frame.XModel.class, xDoc);
// get the frame for later usage
xFrame = xModel.getCurrentController().getFrame();
com.sun.star.view.XViewSettingsSupplier xViewSettings =
(com.sun.star.view.XViewSettingsSupplier)UnoRuntime.queryInterface(
com.sun.star.view.XViewSettingsSupplier.class, xModel.getCurrentController());
xViewSettings.getViewSettings().setPropertyValue(
"ZoomType", new Short((short)0));
}
// test document will be closed later
// reuse the frame
com.sun.star.frame.XController xController = xFrame.getController();
if ( xController != null ) {
com.sun.star.ui.XContextMenuInterception xContextMenuInterception =
(com.sun.star.ui.XContextMenuInterception)UnoRuntime.queryInterface(
com.sun.star.ui.XContextMenuInterception.class, xController );
if( xContextMenuInterception != null ) {
ContextMenuInterceptor aContextMenuInterceptor = new ContextMenuInterceptor();
com.sun.star.ui.XContextMenuInterceptor xContextMenuInterceptor =
(com.sun.star.ui.XContextMenuInterceptor)UnoRuntime.queryInterface(
com.sun.star.ui.XContextMenuInterceptor.class, aContextMenuInterceptor );
xContextMenuInterception.registerContextMenuInterceptor( xContextMenuInterceptor );
System.out.println( "\n ... all context menus of the created document frame contains now a 'Help' entry with the\n submenus 'Content', 'Help Agent' and 'Tips'.\n\nPress 'Return' to remove the context menu interceptor and finish the example!");
if (System.in.read() > 0) {
xContextMenuInterception.releaseContextMenuInterceptor(
xContextMenuInterceptor );
System.out.println( " ... context menu interceptor removed!" );
}
}
}
// close test document
com.sun.star.util.XCloseable xCloseable = (com.sun.star.util.XCloseable)
UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class,
xComponent );
if (xCloseable != null ) {
xCloseable.close(false);
} else
{
xComponent.dispose();
}
}
catch ( com.sun.star.uno.RuntimeException ex ) {
// something strange has happend!
System.out.println( " Sample caught exception! " + ex );
System.exit(1);
}
catch ( java.lang.Exception ex ) {
// catch java exceptions and do something useful
System.out.println( " Sample caught exception! " + ex );
System.exit(1);
}
System.out.println(" ... exit!\n");
System.exit( 0 );
}
/**
*Description of the Method
*
*@param args Description of Parameter
*@since
*/
public ContextMenuInterceptorAction notifyContextMenuExecute(
com.sun.star.ui.ContextMenuExecuteEvent aEvent ) throws RuntimeException {
try {
// Retrieve context menu container and query for service factory to
// create sub menus, menu entries and separators
com.sun.star.container.XIndexContainer xContextMenu = aEvent.ActionTriggerContainer;
com.sun.star.lang.XMultiServiceFactory xMenuElementFactory =
(com.sun.star.lang.XMultiServiceFactory)UnoRuntime.queryInterface(
com.sun.star.lang.XMultiServiceFactory.class, xContextMenu );
if ( xMenuElementFactory != null ) {
// create root menu entry and sub menu
com.sun.star.beans.XPropertySet xRootMenuEntry =
(XPropertySet)UnoRuntime.queryInterface(
com.sun.star.beans.XPropertySet.class,
xMenuElementFactory.createInstance( "com.sun.star.ui.ActionTrigger" ));
// create a line separator for our new help sub menu
com.sun.star.beans.XPropertySet xSeparator =
(com.sun.star.beans.XPropertySet)UnoRuntime.queryInterface(
com.sun.star.beans.XPropertySet.class,
xMenuElementFactory.createInstance( "com.sun.star.ui.ActionTriggerSeparator" ));
Short aSeparatorType = new Short( ActionTriggerSeparatorType.LINE );
xSeparator.setPropertyValue( "SeparatorType", (Object)aSeparatorType );
// query sub menu for index container to get access
com.sun.star.container.XIndexContainer xSubMenuContainer =
(com.sun.star.container.XIndexContainer)UnoRuntime.queryInterface(
com.sun.star.container.XIndexContainer.class,
xMenuElementFactory.createInstance(
"com.sun.star.ui.ActionTriggerContainer" ));
// intialize root menu entry
xRootMenuEntry.setPropertyValue( "Text", new String( "Help" ));
xRootMenuEntry.setPropertyValue( "CommandURL", new String( "slot:5410" ));
xRootMenuEntry.setPropertyValue( "HelpURL", new String( "5410" ));
xRootMenuEntry.setPropertyValue( "SubContainer", (Object)xSubMenuContainer );
// create menu entries for the new sub menu
// intialize help/content menu entry
XPropertySet xMenuEntry = (XPropertySet)UnoRuntime.queryInterface(
XPropertySet.class, xMenuElementFactory.createInstance(
"com.sun.star.ui.ActionTrigger" ));
xMenuEntry.setPropertyValue( "Text", new String( "Content" ));
xMenuEntry.setPropertyValue( "CommandURL", new String( "slot:5401" ));
xMenuEntry.setPropertyValue( "HelpURL", new String( "5401" ));
// insert menu entry to sub menu
xSubMenuContainer.insertByIndex( 0, (Object)xMenuEntry );
// intialize help/help agent
xMenuEntry = (com.sun.star.beans.XPropertySet)UnoRuntime.queryInterface(
com.sun.star.beans.XPropertySet.class,
xMenuElementFactory.createInstance(
"com.sun.star.ui.ActionTrigger" ));
xMenuEntry.setPropertyValue( "Text", new String( "Help Agent" ));
xMenuEntry.setPropertyValue( "CommandURL", new String( "slot:5962" ));
xMenuEntry.setPropertyValue( "HelpURL", new String( "5962" ));
// insert menu entry to sub menu
xSubMenuContainer.insertByIndex( 1, (Object)xMenuEntry );
// intialize help/tips
xMenuEntry = (com.sun.star.beans.XPropertySet)UnoRuntime.queryInterface(
com.sun.star.beans.XPropertySet.class,
xMenuElementFactory.createInstance(
"com.sun.star.ui.ActionTrigger" ));
xMenuEntry.setPropertyValue( "Text", new String( "Tips" ));
xMenuEntry.setPropertyValue( "CommandURL", new String( "slot:5404" ));
xMenuEntry.setPropertyValue( "HelpURL", new String( "5404" ));
// insert menu entry to sub menu
xSubMenuContainer.insertByIndex( 2, (Object)xMenuEntry );
// add separator into the given context menu
xContextMenu.insertByIndex( 0, (Object)xSeparator );
// add new sub menu into the given context menu
xContextMenu.insertByIndex( 0, (Object)xRootMenuEntry );
// The controller should execute the modified context menu and stop notifying other
// interceptors.
return com.sun.star.ui.ContextMenuInterceptorAction.EXECUTE_MODIFIED;
}
}
catch ( com.sun.star.beans.UnknownPropertyException ex ) {
// do something useful
// we used a unknown property
}
catch ( com.sun.star.lang.IndexOutOfBoundsException ex ) {
// do something useful
// we used an invalid index for accessing a container
}
catch ( com.sun.star.uno.Exception ex ) {
// something strange has happend!
}
catch ( java.lang.Exception ex ) {
// catch java exceptions and something useful
}
return com.sun.star.ui.ContextMenuInterceptorAction.IGNORED;
}
}
|
package org.openlca.app.editors.graphical.model;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.GridData;
import org.eclipse.draw2d.GridLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.swt.SWT;
import org.openlca.app.util.Colors;
class IOFigure extends Figure {
private final ExchangePanel inputPanel;
private final ExchangePanel outputPanel;
IOFigure() {
var layout = new GridLayout(2, true);
layout.horizontalSpacing = 4;
layout.verticalSpacing = 4;
layout.marginHeight = 2;
layout.marginWidth = 2;
setLayoutManager(layout);
add(new Header("Input flows"),
new GridData(SWT.FILL, SWT.TOP, true, false));
add(new Header("Output flows"),
new GridData(SWT.FILL, SWT.TOP, true, false));
inputPanel = new ExchangePanel();
add(inputPanel,
new GridData(SWT.FILL, SWT.FILL, true, true));
outputPanel = new ExchangePanel();
add(outputPanel,
new GridData(SWT.FILL, SWT.FILL, true, true));
}
@Override
public void add(IFigure figure, Object constraint, int index) {
if (!(figure instanceof ExchangeFigure)) {
super.add(figure, constraint, index);
return;
}
var ef = (ExchangeFigure) figure;
if (ef.node == null || ef.node.exchange == null)
return;
var layout = new GridData(SWT.FILL, SWT.TOP, true, false);
if (ef.node.exchange.isInput) {
inputPanel.add(ef, layout);
} else {
outputPanel.add(ef, layout);
}
}
private static class Header extends Figure {
Header(String text) {
var layout = new GridLayout(1, true);
layout.marginHeight = 2;
layout.marginWidth = 5;
setLayoutManager(layout);
var label = new Label(text);
label.setForegroundColor(Colors.white());
add(label, new GridData(SWT.CENTER, SWT.TOP, true, false));
}
}
private static class ExchangePanel extends Figure {
ExchangePanel() {
var layout = new GridLayout(1, true);
layout.marginHeight = 2;
layout.marginWidth = 5;
setLayoutManager(layout);
}
@Override
protected void paintFigure(Graphics g) {
g.pushState();
g.setBackgroundColor(Figures.COLOR_LIGHT_GREY);
var location = getLocation();
var size = getSize();
g.fillRectangle(
location.x,
location.y,
size.width,
size.height);
g.popState();
super.paintFigure(g);
}
}
}
|
package com.oracle.graal.phases.schedule;
import static com.oracle.graal.api.meta.LocationIdentity.*;
import static com.oracle.graal.compiler.common.GraalOptions.*;
import static com.oracle.graal.nodes.cfg.ControlFlowGraph.*;
import java.util.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.compiler.common.cfg.*;
import com.oracle.graal.debug.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.Node.Verbosity;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.cfg.*;
import com.oracle.graal.nodes.extended.*;
import com.oracle.graal.nodes.spi.*;
import com.oracle.graal.nodes.virtual.*;
import com.oracle.graal.phases.*;
import com.oracle.graal.phases.graph.*;
import com.oracle.graal.phases.graph.ReentrantBlockIterator.BlockIteratorClosure;
import com.oracle.graal.phases.graph.ReentrantBlockIterator.LoopInfo;
import com.oracle.graal.phases.util.*;
public final class SchedulePhase extends Phase {
/**
* Error thrown when a graph cannot be scheduled.
*/
public static class SchedulingError extends Error {
private static final long serialVersionUID = 1621001069476473145L;
public SchedulingError() {
super();
}
/**
* This constructor creates a {@link SchedulingError} with a message assembled via
* {@link String#format(String, Object...)}.
*
* @param format a {@linkplain Formatter format} string
* @param args parameters to {@link String#format(String, Object...)}
*/
public SchedulingError(String format, Object... args) {
super(String.format(format, args));
}
}
public static enum SchedulingStrategy {
EARLIEST,
LATEST,
LATEST_OUT_OF_LOOPS
}
public static enum MemoryScheduling {
NONE,
OPTIMAL
}
private class KillSet implements Iterable<LocationIdentity> {
private final Set<LocationIdentity> set;
public KillSet() {
this.set = new ArraySet<>();
}
public KillSet(KillSet other) {
this.set = new HashSet<>(other.set);
}
public void add(LocationIdentity locationIdentity) {
set.add(locationIdentity);
}
public void addAll(KillSet other) {
set.addAll(other.set);
}
public Iterator<LocationIdentity> iterator() {
return set.iterator();
}
public boolean isKilled(LocationIdentity locationIdentity) {
return set.contains(locationIdentity);
}
}
private class NewMemoryScheduleClosure extends BlockIteratorClosure<KillSet> {
private Node excludeNode;
private Block upperBoundBlock;
public NewMemoryScheduleClosure(Node excludeNode, Block upperBoundBlock) {
this.excludeNode = excludeNode;
this.upperBoundBlock = upperBoundBlock;
}
public NewMemoryScheduleClosure() {
this(null, null);
}
@Override
protected KillSet getInitialState() {
return cloneState(blockToKillSet.get(getCFG().getStartBlock()));
}
@Override
protected KillSet processBlock(Block block, KillSet currentState) {
assert block != null;
currentState.addAll(computeKillSet(block, block == upperBoundBlock ? excludeNode : null));
return currentState;
}
@Override
protected KillSet merge(Block merge, List<KillSet> states) {
assert merge.getBeginNode() instanceof MergeNode;
KillSet initKillSet = new KillSet();
for (KillSet state : states) {
initKillSet.addAll(state);
}
return initKillSet;
}
@Override
protected KillSet cloneState(KillSet state) {
return new KillSet(state);
}
@Override
protected List<KillSet> processLoop(Loop<Block> loop, KillSet state) {
LoopInfo<KillSet> info = ReentrantBlockIterator.processLoop(this, loop, cloneState(state));
assert loop.header.getBeginNode() instanceof LoopBeginNode;
KillSet headerState = merge(loop.header, info.endStates);
// second iteration, for propagating information to loop exits
info = ReentrantBlockIterator.processLoop(this, loop, cloneState(headerState));
return info.exitStates;
}
}
/**
* gather all kill locations by iterating trough the nodes assigned to a block.
*
* assumptions: {@link MemoryCheckpoint MemoryCheckPoints} are {@link FixedNode FixedNodes}.
*
* @param block block to analyze
* @param excludeNode if null, compute normal set of kill locations. if != null, don't add kills
* until we reach excludeNode.
* @return all killed locations
*/
private KillSet computeKillSet(Block block, Node excludeNode) {
// cache is only valid if we don't potentially exclude kills from the set
if (excludeNode == null) {
KillSet cachedSet = blockToKillSet.get(block);
if (cachedSet != null) {
return cachedSet;
}
}
// add locations to excludedLocations until we reach the excluded node
boolean foundExcludeNode = excludeNode == null;
KillSet set = new KillSet();
KillSet excludedLocations = new KillSet();
if (block.getBeginNode() instanceof MergeNode) {
MergeNode mergeNode = (MergeNode) block.getBeginNode();
for (MemoryPhiNode phi : mergeNode.usages().filter(MemoryPhiNode.class)) {
if (foundExcludeNode) {
set.add(phi.getLocationIdentity());
} else {
excludedLocations.add(phi.getLocationIdentity());
foundExcludeNode = phi == excludeNode;
}
}
}
BeginNode startNode = cfg.getStartBlock().getBeginNode();
assert startNode instanceof StartNode;
KillSet accm = foundExcludeNode ? set : excludedLocations;
for (Node node : block.getNodes()) {
if (!foundExcludeNode && node == excludeNode) {
foundExcludeNode = true;
}
if (node == startNode) {
continue;
}
if (node instanceof MemoryCheckpoint.Single) {
LocationIdentity identity = ((MemoryCheckpoint.Single) node).getLocationIdentity();
accm.add(identity);
} else if (node instanceof MemoryCheckpoint.Multi) {
for (LocationIdentity identity : ((MemoryCheckpoint.Multi) node).getLocationIdentities()) {
accm.add(identity);
}
}
assert MemoryCheckpoint.TypeAssertion.correctType(node);
if (foundExcludeNode) {
accm = set;
}
}
// merge it for the cache entry
excludedLocations.addAll(set);
blockToKillSet.put(block, excludedLocations);
return set;
}
private KillSet computeKillSet(Block block) {
return computeKillSet(block, null);
}
private ControlFlowGraph cfg;
private NodeMap<Block> earliestCache;
/**
* Map from blocks to the nodes in each block.
*/
private BlockMap<List<ScheduledNode>> blockToNodesMap;
private BlockMap<KillSet> blockToKillSet;
private final SchedulingStrategy selectedStrategy;
private final MemoryScheduling memsched;
public SchedulePhase() {
this(OptScheduleOutOfLoops.getValue() ? SchedulingStrategy.LATEST_OUT_OF_LOOPS : SchedulingStrategy.LATEST);
}
public SchedulePhase(SchedulingStrategy strategy) {
this.memsched = MemoryAwareScheduling.getValue() ? MemoryScheduling.OPTIMAL : MemoryScheduling.NONE;
this.selectedStrategy = strategy;
}
public SchedulePhase(SchedulingStrategy strategy, MemoryScheduling memsched) {
this.selectedStrategy = strategy;
this.memsched = memsched;
}
@Override
protected void run(StructuredGraph graph) {
assert GraphOrder.assertNonCyclicGraph(graph);
cfg = ControlFlowGraph.compute(graph, true, true, true, true);
earliestCache = graph.createNodeMap();
blockToNodesMap = new BlockMap<>(cfg);
if (memsched == MemoryScheduling.OPTIMAL && selectedStrategy != SchedulingStrategy.EARLIEST && graph.getNodes(FloatingReadNode.class).isNotEmpty()) {
blockToKillSet = new BlockMap<>(cfg);
assignBlockToNodes(graph, selectedStrategy);
printSchedule("after assign nodes to blocks");
sortNodesWithinBlocks(graph, selectedStrategy);
printSchedule("after sorting nodes within blocks");
} else {
assignBlockToNodes(graph, selectedStrategy);
sortNodesWithinBlocks(graph, selectedStrategy);
}
}
private Block blockForMemoryNode(MemoryNode memory) {
MemoryNode current = memory;
while (current instanceof MemoryProxy) {
current = ((MemoryProxy) current).getOriginalMemoryNode();
}
Block b = cfg.getNodeToBlock().get(current.asNode());
assert b != null : "all lastAccess locations should have a block assignment from CFG";
return b;
}
private void printSchedule(String desc) {
if (Debug.isLogEnabled()) {
Formatter buf = new Formatter();
buf.format("=== %s / %s / %s (%s) ===%n", getCFG().getStartBlock().getBeginNode().graph(), selectedStrategy, memsched, desc);
for (Block b : getCFG().getBlocks()) {
buf.format("==== b: %s (loopDepth: %s). ", b, b.getLoopDepth());
buf.format("dom: %s. ", b.getDominator());
buf.format("post-dom: %s. ", b.getPostdominator());
buf.format("preds: %s. ", b.getPredecessors());
buf.format("succs: %s ====%n", b.getSuccessors());
BlockMap<KillSet> killSets = blockToKillSet;
if (killSets != null) {
buf.format("X block kills: %n");
if (killSets.get(b) != null) {
for (LocationIdentity locId : killSets.get(b)) {
buf.format("X %s killed by %s%n", locId, "dunno anymore");
}
}
}
if (blockToNodesMap.get(b) != null) {
for (Node n : nodesFor(b)) {
printNode(n);
}
} else {
for (Node n : b.getNodes()) {
printNode(n);
}
}
}
buf.format("%n");
Debug.log("%s", buf);
}
}
private static void printNode(Node n) {
Formatter buf = new Formatter();
buf.format("%s", n);
if (n instanceof MemoryCheckpoint.Single) {
buf.format(" // kills %s", ((MemoryCheckpoint.Single) n).getLocationIdentity());
} else if (n instanceof MemoryCheckpoint.Multi) {
buf.format(" // kills ");
for (LocationIdentity locid : ((MemoryCheckpoint.Multi) n).getLocationIdentities()) {
buf.format("%s, ", locid);
}
} else if (n instanceof FloatingReadNode) {
FloatingReadNode frn = (FloatingReadNode) n;
buf.format(" // from %s", frn.location().getLocationIdentity());
buf.format(", lastAccess: %s", frn.getLastLocationAccess());
buf.format(", object: %s", frn.object());
} else if (n instanceof GuardNode) {
buf.format(", anchor: %s", ((GuardNode) n).getAnchor());
}
Debug.log("%s", buf);
}
public ControlFlowGraph getCFG() {
return cfg;
}
/**
* Gets the map from each block to the nodes in the block.
*/
public BlockMap<List<ScheduledNode>> getBlockToNodesMap() {
return blockToNodesMap;
}
/**
* Gets the nodes in a given block.
*/
public List<ScheduledNode> nodesFor(Block block) {
return blockToNodesMap.get(block);
}
private void assignBlockToNodes(StructuredGraph graph, SchedulingStrategy strategy) {
for (Block block : cfg.getBlocks()) {
List<ScheduledNode> nodes = new ArrayList<>();
if (blockToNodesMap.get(block) != null) {
throw new SchedulingError();
}
blockToNodesMap.put(block, nodes);
for (FixedNode node : block.getNodes()) {
nodes.add(node);
}
}
for (Node n : graph.getNodes()) {
if (n instanceof ScheduledNode) {
assignBlockToNode((ScheduledNode) n, strategy);
}
}
}
/**
* Assigns a block to the given node. This method expects that PhiNodes and FixedNodes are
* already assigned to a block.
*/
private void assignBlockToNode(ScheduledNode node, SchedulingStrategy strategy) {
assert !node.isDeleted();
if (cfg.getNodeToBlock().containsKey(node)) {
return;
}
// PhiNodes, ProxyNodes and FixedNodes should already have been placed in blocks by
// ControlFlowGraph.identifyBlocks
if (node instanceof PhiNode || node instanceof ProxyNode || node instanceof FixedNode) {
throw new SchedulingError("%s should already have been placed in a block", node);
}
Block earliestBlock = earliestBlock(node);
Block block = null;
Block latest = null;
switch (strategy) {
case EARLIEST:
block = earliestBlock;
break;
case LATEST:
case LATEST_OUT_OF_LOOPS:
boolean scheduleRead = memsched == MemoryScheduling.OPTIMAL && node instanceof FloatingReadNode && ((FloatingReadNode) node).location().getLocationIdentity() != FINAL_LOCATION;
if (scheduleRead) {
FloatingReadNode read = (FloatingReadNode) node;
block = optimalBlock(read, strategy);
Debug.log("schedule for %s: %s", read, block);
assert earliestBlock.dominates(block) : String.format("%s (%s) cannot be scheduled before earliest schedule (%s). location: %s", read, block, earliestBlock,
read.getLocationIdentity());
} else {
block = latestBlock(node, strategy);
}
if (block == null) {
// handle nodes without usages
block = earliestBlock;
} else if (strategy == SchedulingStrategy.LATEST_OUT_OF_LOOPS && !(node instanceof VirtualObjectNode)) {
// schedule at the latest position possible in the outermost loop possible
latest = block;
block = scheduleOutOfLoops(node, block, earliestBlock);
}
if (assertionEnabled()) {
if (scheduleRead) {
FloatingReadNode read = (FloatingReadNode) node;
MemoryNode lastLocationAccess = read.getLastLocationAccess();
Block upperBound = blockForMemoryNode(lastLocationAccess);
assert upperBound.dominates(block) : String.format(
"out of loop movement voilated memory semantics for %s (location %s). moved to %s but upper bound is %s (earliest: %s, latest: %s)", read,
read.getLocationIdentity(), block, upperBound, earliestBlock, latest);
}
}
break;
default:
throw new GraalInternalError("unknown scheduling strategy");
}
if (!earliestBlock.dominates(block)) {
throw new SchedulingError("%s: Graph cannot be scheduled : inconsistent for %s, %d usages, (%s needs to dominate %s)", node.graph(), node, node.usages().count(), earliestBlock, block);
}
cfg.getNodeToBlock().set(node, block);
blockToNodesMap.get(block).add(node);
}
@SuppressWarnings("all")
private static boolean assertionEnabled() {
boolean enabled = false;
assert enabled = true;
return enabled;
}
/**
* this method tries to find the "optimal" schedule for a read, by pushing it down towards its
* latest schedule starting by the earliest schedule. By doing this, it takes care of memory
* dependencies using kill sets.
*
* In terms of domination relation, it looks like this:
*
* <pre>
* U upperbound block, defined by last access location of the floating read
* ∧
* E earliest block
* ∧
* O optimal block, first block that contains a kill of the read's location
* ∧
* L latest block
* </pre>
*
* i.e. <code>upperbound `dom` earliest `dom` optimal `dom` latest</code>.
*
*/
private Block optimalBlock(FloatingReadNode n, SchedulingStrategy strategy) {
assert memsched == MemoryScheduling.OPTIMAL;
LocationIdentity locid = n.location().getLocationIdentity();
assert locid != FINAL_LOCATION;
Block upperBoundBlock = blockForMemoryNode(n.getLastLocationAccess());
Block earliestBlock = earliestBlock(n);
assert upperBoundBlock.dominates(earliestBlock) : "upper bound (" + upperBoundBlock + ") should dominate earliest (" + earliestBlock + ")";
Block latestBlock = latestBlock(n, strategy);
assert latestBlock != null && earliestBlock.dominates(latestBlock) : "earliest (" + earliestBlock + ") should dominate latest block (" + latestBlock + ")";
Debug.log("processing %s (accessing %s): latest %s, earliest %s, upper bound %s (%s)", n, locid, latestBlock, earliestBlock, upperBoundBlock, n.getLastLocationAccess());
if (earliestBlock == latestBlock) {
// read is fixed to this block, nothing to schedule
return latestBlock;
}
Deque<Block> path = computePathInDominatorTree(earliestBlock, latestBlock);
Debug.log("|path| is %d: %s", path.size(), path);
// follow path, start at earliest schedule
while (path.size() > 0) {
Block currentBlock = path.pop();
Block dominatedBlock = path.size() == 0 ? null : path.peek();
if (dominatedBlock != null && !currentBlock.getSuccessors().contains(dominatedBlock)) {
// the dominated block is not a successor -> we have a split
assert dominatedBlock.getBeginNode() instanceof MergeNode;
HashSet<Block> region = computeRegion(currentBlock, dominatedBlock);
Debug.log("> merge. %s: region for %s -> %s: %s", n, currentBlock, dominatedBlock, region);
NewMemoryScheduleClosure closure = null;
if (currentBlock == upperBoundBlock) {
assert earliestBlock == upperBoundBlock;
// don't treat lastLocationAccess node as a kill for this read.
closure = new NewMemoryScheduleClosure(ValueNodeUtil.asNode(n.getLastLocationAccess()), upperBoundBlock);
} else {
closure = new NewMemoryScheduleClosure();
}
Map<FixedNode, KillSet> states;
states = ReentrantBlockIterator.apply(closure, currentBlock, new KillSet(), region);
KillSet mergeState = states.get(dominatedBlock.getBeginNode());
if (mergeState.isKilled(locid)) {
// location got killed somewhere in the branches,
// thus we've to move the read above it
return currentBlock;
}
} else {
if (currentBlock == upperBoundBlock) {
assert earliestBlock == upperBoundBlock;
KillSet ks = computeKillSet(upperBoundBlock, ValueNodeUtil.asNode(n.getLastLocationAccess()));
if (ks.isKilled(locid)) {
return upperBoundBlock;
}
} else if (dominatedBlock == null || computeKillSet(currentBlock).isKilled(locid)) {
return currentBlock;
}
}
}
throw new SchedulingError("should have found a block for " + n);
}
/**
* compute path in dominator tree from earliest schedule to latest schedule.
*
* @return the order of the stack is such as the first element is the earliest schedule.
*/
private static Deque<Block> computePathInDominatorTree(Block earliestBlock, Block latestBlock) {
Deque<Block> path = new LinkedList<>();
Block currentBlock = latestBlock;
while (currentBlock != null && earliestBlock.dominates(currentBlock)) {
path.push(currentBlock);
currentBlock = currentBlock.getDominator();
}
assert path.peek() == earliestBlock;
return path;
}
/**
* compute a set that contains all blocks in a region spanned by dominatorBlock and
* dominatedBlock (exclusive the dominatedBlock).
*/
private static HashSet<Block> computeRegion(Block dominatorBlock, Block dominatedBlock) {
HashSet<Block> region = new HashSet<>();
Queue<Block> workList = new LinkedList<>();
region.add(dominatorBlock);
workList.addAll(dominatorBlock.getSuccessors());
while (workList.size() > 0) {
Block current = workList.poll();
if (current != dominatedBlock) {
region.add(current);
for (Block b : current.getSuccessors()) {
if (!region.contains(b) && !workList.contains(b)) {
workList.offer(b);
}
}
}
}
assert !region.contains(dominatedBlock) && region.containsAll(dominatedBlock.getPredecessors());
return region;
}
/**
* Calculates the last block that the given node could be scheduled in, i.e., the common
* dominator of all usages. To do so all usages are also assigned to blocks.
*
* @param strategy
*/
private Block latestBlock(ScheduledNode node, SchedulingStrategy strategy) {
CommonDominatorBlockClosure cdbc = new CommonDominatorBlockClosure(null);
for (Node succ : node.successors().nonNull()) {
if (cfg.getNodeToBlock().get(succ) == null) {
throw new SchedulingError();
}
cdbc.apply(cfg.getNodeToBlock().get(succ));
}
ensureScheduledUsages(node, strategy);
if (node.recordsUsages()) {
for (Node usage : node.usages()) {
blocksForUsage(node, usage, cdbc, strategy);
}
}
if (assertionEnabled()) {
if (cdbc.block != null && !earliestBlock(node).dominates(cdbc.block)) {
throw new SchedulingError("failed to find correct latest schedule for %s. cdbc: %s, earliest: %s", node, cdbc.block, earliestBlock(node));
}
}
return cdbc.block;
}
/**
* A closure that will calculate the common dominator of all blocks passed to its
* {@link #apply(Block)} method.
*/
private static class CommonDominatorBlockClosure implements BlockClosure {
public Block block;
public CommonDominatorBlockClosure(Block block) {
this.block = block;
}
@Override
public void apply(Block newBlock) {
this.block = commonDominator(this.block, newBlock);
}
}
/**
* Determines the earliest block in which the given node can be scheduled.
*/
private Block earliestBlock(Node node) {
Block earliest = cfg.getNodeToBlock().get(node);
if (earliest != null) {
return earliest;
}
earliest = earliestCache.get(node);
if (earliest != null) {
return earliest;
}
/*
* All inputs must be in a dominating block, otherwise the graph cannot be scheduled. This
* implies that the inputs' blocks have a total ordering via their dominance relation. So in
* order to find the earliest block placement for this node we need to find the input block
* that is dominated by all other input blocks.
*/
if (node.predecessor() != null) {
throw new SchedulingError();
}
for (Node input : node.inputs().nonNull()) {
assert input instanceof ValueNode;
Block inputEarliest;
if (input instanceof InvokeWithExceptionNode) {
inputEarliest = cfg.getNodeToBlock().get(((InvokeWithExceptionNode) input).next());
} else {
inputEarliest = earliestBlock(input);
}
if (earliest == null) {
earliest = inputEarliest;
} else if (earliest != inputEarliest) {
// Find out whether earliest or inputEarliest is earlier.
Block a = earliest.getDominator();
Block b = inputEarliest;
while (true) {
if (a == inputEarliest || b == null) {
// Nothing to change, the previous earliest block is still earliest.
break;
} else if (b == earliest || a == null) {
// New earliest is the earliest.
earliest = inputEarliest;
break;
}
a = a.getDominator();
b = b.getDominator();
}
}
}
if (earliest == null) {
earliest = cfg.getStartBlock();
}
earliestCache.set(node, earliest);
return earliest;
}
/**
* Schedules a node out of loop based on its earliest schedule. Note that this movement is only
* valid if it's done for <b>every</b> other node in the schedule, otherwise this movement is
* not valid.
*
* @param n Node to schedule
* @param latestBlock latest possible schedule for {@code n}
* @param earliest earliest possible schedule for {@code n}
* @return block schedule for {@code n} which is not inside a loop (if possible)
*/
private static Block scheduleOutOfLoops(Node n, Block latestBlock, Block earliest) {
if (latestBlock == null) {
throw new SchedulingError("no latest : %s", n);
}
Block cur = latestBlock;
Block result = latestBlock;
while (cur.getLoop() != null && cur != earliest && cur.getDominator() != null) {
Block dom = cur.getDominator();
if (dom.getLoopDepth() < result.getLoopDepth()) {
result = dom;
}
cur = dom;
}
return result;
}
/**
* Passes all blocks that a specific usage of a node is in to a given closure. This is more
* complex than just taking the usage's block because of of PhiNodes and FrameStates.
*
* @param node the node that needs to be scheduled
* @param usage the usage whose blocks need to be considered
* @param closure the closure that will be called for each block
*/
private void blocksForUsage(ScheduledNode node, Node usage, BlockClosure closure, SchedulingStrategy strategy) {
if (node instanceof PhiNode) {
throw new SchedulingError(node.toString());
}
if (usage instanceof PhiNode) {
// An input to a PhiNode is used at the end of the predecessor block that corresponds to
// the PhiNode input.
// One PhiNode can use an input multiple times, the closure will be called for each
// usage.
PhiNode phi = (PhiNode) usage;
MergeNode merge = phi.merge();
Block mergeBlock = cfg.getNodeToBlock().get(merge);
if (mergeBlock == null) {
throw new SchedulingError("no block for merge %s", merge.toString(Verbosity.Id));
}
for (int i = 0; i < phi.valueCount(); ++i) {
if (phi.valueAt(i) == node) {
if (mergeBlock.getPredecessorCount() <= i) {
TTY.println(merge.toString());
TTY.println(phi.toString());
TTY.println(merge.cfgPredecessors().toString());
TTY.println(mergeBlock.getPredecessors().toString());
TTY.println(phi.inputs().toString());
TTY.println("value count: " + phi.valueCount());
}
closure.apply(mergeBlock.getPredecessors().get(i));
}
}
} else if (usage instanceof VirtualState) {
// The following logic does not work if node is a PhiNode, but this method is never
// called for PhiNodes.
for (Node unscheduledUsage : usage.usages()) {
if (unscheduledUsage instanceof VirtualState) {
// If a FrameState is an outer FrameState this method behaves as if the inner
// FrameState was the actual usage, by recursing.
blocksForUsage(node, unscheduledUsage, closure, strategy);
} else if (unscheduledUsage instanceof BeginNode) {
// Only FrameStates can be connected to BeginNodes.
if (!(usage instanceof FrameState)) {
throw new SchedulingError(usage.toString());
}
if (unscheduledUsage instanceof StartNode) {
closure.apply(cfg.getNodeToBlock().get(unscheduledUsage));
} else {
// If a FrameState belongs to a BeginNode then it's inputs will be placed at
// the common dominator of all EndNodes.
for (Node pred : unscheduledUsage.cfgPredecessors()) {
closure.apply(cfg.getNodeToBlock().get(pred));
}
}
} else {
// For the time being, FrameStates can only be connected to NodeWithState.
if (!(usage instanceof FrameState)) {
throw new SchedulingError(usage.toString());
}
if (!(unscheduledUsage instanceof NodeWithState)) {
throw new SchedulingError(unscheduledUsage.toString());
}
// Otherwise: Put the input into the same block as the usage.
assignBlockToNode((ScheduledNode) unscheduledUsage, strategy);
closure.apply(cfg.getNodeToBlock().get(unscheduledUsage));
}
}
} else {
// All other types of usages: Put the input into the same block as the usage.
assignBlockToNode((ScheduledNode) usage, strategy);
closure.apply(cfg.getNodeToBlock().get(usage));
}
}
private void ensureScheduledUsages(Node node, SchedulingStrategy strategy) {
if (node.recordsUsages()) {
for (Node usage : node.usages().filter(ScheduledNode.class)) {
assignBlockToNode((ScheduledNode) usage, strategy);
}
}
// now true usages are ready
}
private void sortNodesWithinBlocks(StructuredGraph graph, SchedulingStrategy strategy) {
NodeBitMap visited = graph.createNodeBitMap();
NodeBitMap beforeLastLocation = graph.createNodeBitMap();
for (Block b : cfg.getBlocks()) {
sortNodesWithinBlock(b, visited, beforeLastLocation, strategy);
assert noDuplicatedNodesInBlock(b) : "duplicated nodes in " + b;
}
}
private boolean noDuplicatedNodesInBlock(Block b) {
List<ScheduledNode> list = blockToNodesMap.get(b);
HashSet<ScheduledNode> hashset = new HashSet<>(list);
return list.size() == hashset.size();
}
private void sortNodesWithinBlock(Block b, NodeBitMap visited, NodeBitMap beforeLastLocation, SchedulingStrategy strategy) {
if (visited.isMarked(b.getBeginNode()) || cfg.blockFor(b.getBeginNode()) != b) {
throw new SchedulingError();
}
if (visited.isMarked(b.getEndNode()) || cfg.blockFor(b.getEndNode()) != b) {
throw new SchedulingError();
}
List<ScheduledNode> sortedInstructions;
switch (strategy) {
case EARLIEST:
sortedInstructions = sortNodesWithinBlockEarliest(b, visited);
break;
case LATEST:
case LATEST_OUT_OF_LOOPS:
sortedInstructions = sortNodesWithinBlockLatest(b, visited, beforeLastLocation);
break;
default:
throw new GraalInternalError("unknown scheduling strategy");
}
assert filterSchedulableNodes(blockToNodesMap.get(b)).size() == removeProxies(sortedInstructions).size() : "sorted block does not contain the same amount of nodes: " +
filterSchedulableNodes(blockToNodesMap.get(b)) + " vs. " + removeProxies(sortedInstructions);
assert sameOrderForFixedNodes(blockToNodesMap.get(b), sortedInstructions) : "fixed nodes in sorted block are not in the same order";
blockToNodesMap.put(b, sortedInstructions);
}
private static List<ScheduledNode> removeProxies(List<ScheduledNode> list) {
List<ScheduledNode> result = new ArrayList<>();
for (ScheduledNode n : list) {
if (!(n instanceof ProxyNode)) {
result.add(n);
}
}
return result;
}
private static List<ScheduledNode> filterSchedulableNodes(List<ScheduledNode> list) {
List<ScheduledNode> result = new ArrayList<>();
for (ScheduledNode n : list) {
if (!(n instanceof PhiNode)) {
result.add(n);
}
}
return result;
}
private static boolean sameOrderForFixedNodes(List<ScheduledNode> fixed, List<ScheduledNode> sorted) {
Iterator<ScheduledNode> fixedIterator = fixed.iterator();
Iterator<ScheduledNode> sortedIterator = sorted.iterator();
while (sortedIterator.hasNext()) {
ScheduledNode sortedCurrent = sortedIterator.next();
if (sortedCurrent instanceof FixedNode) {
if (!(fixedIterator.hasNext() && fixedIterator.next() == sortedCurrent)) {
return false;
}
}
}
while (fixedIterator.hasNext()) {
if (fixedIterator.next() instanceof FixedNode) {
return false;
}
}
return true;
}
/**
* Sorts the nodes within a block by adding the nodes to a list in a post-order iteration over
* all inputs. This means that a node is added to the list after all its inputs have been
* processed.
*/
private List<ScheduledNode> sortNodesWithinBlockLatest(Block b, NodeBitMap visited, NodeBitMap beforeLastLocation) {
List<ScheduledNode> instructions = blockToNodesMap.get(b);
List<ScheduledNode> sortedInstructions = new ArrayList<>(blockToNodesMap.get(b).size() + 2);
List<FloatingReadNode> reads = null;
if (memsched == MemoryScheduling.OPTIMAL) {
for (ScheduledNode i : instructions) {
if (i instanceof FloatingReadNode) {
FloatingReadNode frn = (FloatingReadNode) i;
if (frn.location().getLocationIdentity() != FINAL_LOCATION) {
if (reads == null) {
reads = new ArrayList<>();
}
reads.add(frn);
if (nodesFor(b).contains(frn.getLastLocationAccess())) {
assert !beforeLastLocation.isMarked(frn);
beforeLastLocation.mark(frn);
}
}
}
}
}
for (ScheduledNode i : instructions) {
addToLatestSorting(b, i, sortedInstructions, visited, reads, beforeLastLocation);
}
assert reads == null || reads.size() == 0 : "not all reads are scheduled";
// Make sure that last node gets really last (i.e. when a frame state successor hangs off
Node lastSorted = sortedInstructions.get(sortedInstructions.size() - 1);
if (lastSorted != b.getEndNode()) {
int idx = sortedInstructions.indexOf(b.getEndNode());
boolean canNotMove = false;
for (int i = idx + 1; i < sortedInstructions.size(); i++) {
if (sortedInstructions.get(i).inputs().contains(b.getEndNode())) {
canNotMove = true;
break;
}
}
if (canNotMove) {
if (b.getEndNode() instanceof ControlSplitNode) {
throw new GraalGraphInternalError("Schedule is not possible : needs to move a node after the last node of the block which can not be move").addContext(lastSorted).addContext(
b.getEndNode());
}
// b.setLastNode(lastSorted);
} else {
sortedInstructions.remove(b.getEndNode());
sortedInstructions.add(b.getEndNode());
}
}
return sortedInstructions;
}
private void processKillLocation(Block b, Node node, LocationIdentity identity, List<ScheduledNode> sortedInstructions, NodeBitMap visited, List<FloatingReadNode> reads,
NodeBitMap beforeLastLocation) {
for (FloatingReadNode frn : new ArrayList<>(reads)) {
LocationIdentity readLocation = frn.location().getLocationIdentity();
assert readLocation != FINAL_LOCATION;
if (frn.getLastLocationAccess() == node) {
assert identity == ANY_LOCATION || readLocation == identity : "location doesn't match: " + readLocation + ", " + identity;
beforeLastLocation.clear(frn);
} else if (!beforeLastLocation.isMarked(frn) && (readLocation == identity || (node != getCFG().graph.start() && ANY_LOCATION == identity))) {
reads.remove(frn);
addToLatestSorting(b, frn, sortedInstructions, visited, reads, beforeLastLocation);
}
}
}
private void addUnscheduledToLatestSorting(Block b, VirtualState state, List<ScheduledNode> sortedInstructions, NodeBitMap visited, List<FloatingReadNode> reads, NodeBitMap beforeLastLocation) {
if (state != null) {
// UnscheduledNodes should never be marked as visited.
if (visited.isMarked(state)) {
throw new SchedulingError();
}
for (Node input : state.inputs()) {
if (input instanceof VirtualState) {
addUnscheduledToLatestSorting(b, (VirtualState) input, sortedInstructions, visited, reads, beforeLastLocation);
} else {
addToLatestSorting(b, (ScheduledNode) input, sortedInstructions, visited, reads, beforeLastLocation);
}
}
}
}
private void addToLatestSorting(Block b, ScheduledNode i, List<ScheduledNode> sortedInstructions, NodeBitMap visited, List<FloatingReadNode> reads, NodeBitMap beforeLastLocation) {
if (i == null || visited.isMarked(i) || cfg.getNodeToBlock().get(i) != b || i instanceof PhiNode) {
return;
}
FrameState stateAfter = null;
if (i instanceof StateSplit) {
stateAfter = ((StateSplit) i).stateAfter();
}
if (i instanceof LoopExitNode) {
for (ProxyNode proxy : ((LoopExitNode) i).proxies()) {
addToLatestSorting(b, proxy, sortedInstructions, visited, reads, beforeLastLocation);
}
}
for (Node input : i.inputs()) {
if (input instanceof FrameState) {
if (input != stateAfter) {
addUnscheduledToLatestSorting(b, (FrameState) input, sortedInstructions, visited, reads, beforeLastLocation);
}
} else {
if (!(i instanceof ProxyNode && input instanceof LoopExitNode)) {
addToLatestSorting(b, (ScheduledNode) input, sortedInstructions, visited, reads, beforeLastLocation);
}
}
}
if (memsched == MemoryScheduling.OPTIMAL && reads != null) {
if (i instanceof MemoryCheckpoint.Single) {
LocationIdentity identity = ((MemoryCheckpoint.Single) i).getLocationIdentity();
processKillLocation(b, i, identity, sortedInstructions, visited, reads, beforeLastLocation);
} else if (i instanceof MemoryCheckpoint.Multi) {
for (LocationIdentity identity : ((MemoryCheckpoint.Multi) i).getLocationIdentities()) {
processKillLocation(b, i, identity, sortedInstructions, visited, reads, beforeLastLocation);
}
}
assert MemoryCheckpoint.TypeAssertion.correctType(i);
}
addToLatestSorting(b, (ScheduledNode) i.predecessor(), sortedInstructions, visited, reads, beforeLastLocation);
visited.mark(i);
addUnscheduledToLatestSorting(b, stateAfter, sortedInstructions, visited, reads, beforeLastLocation);
// Now predecessors and inputs are scheduled => we can add this node.
if (!sortedInstructions.contains(i)) {
sortedInstructions.add(i);
}
if (i instanceof FloatingReadNode) {
reads.remove(i);
}
}
/**
* Sorts the nodes within a block by adding the nodes to a list in a post-order iteration over
* all usages. The resulting list is reversed to create an earliest-possible scheduling of
* nodes.
*/
private List<ScheduledNode> sortNodesWithinBlockEarliest(Block b, NodeBitMap visited) {
List<ScheduledNode> sortedInstructions = new ArrayList<>(blockToNodesMap.get(b).size() + 2);
addToEarliestSorting(b, b.getEndNode(), sortedInstructions, visited);
Collections.reverse(sortedInstructions);
return sortedInstructions;
}
private void addToEarliestSorting(Block b, ScheduledNode i, List<ScheduledNode> sortedInstructions, NodeBitMap visited) {
ScheduledNode instruction = i;
while (true) {
if (instruction == null || visited.isMarked(instruction) || cfg.getNodeToBlock().get(instruction) != b || instruction instanceof PhiNode) {
return;
}
visited.mark(instruction);
if (instruction.recordsUsages()) {
for (Node usage : instruction.usages()) {
if (usage instanceof VirtualState) {
// only fixed nodes can have VirtualState -> no need to schedule them
} else {
if (instruction instanceof LoopExitNode && usage instanceof ProxyNode) {
// value proxies should be scheduled before the loopexit, not after
} else {
addToEarliestSorting(b, (ScheduledNode) usage, sortedInstructions, visited);
}
}
}
}
if (instruction instanceof BeginNode) {
ArrayList<ProxyNode> proxies = (instruction instanceof LoopExitNode) ? new ArrayList<>() : null;
for (ScheduledNode inBlock : blockToNodesMap.get(b)) {
if (!visited.isMarked(inBlock)) {
if (inBlock instanceof ProxyNode) {
proxies.add((ProxyNode) inBlock);
} else {
addToEarliestSorting(b, inBlock, sortedInstructions, visited);
}
}
}
sortedInstructions.add(instruction);
if (proxies != null) {
sortedInstructions.addAll(proxies);
}
break;
} else {
sortedInstructions.add(instruction);
instruction = (ScheduledNode) instruction.predecessor();
}
}
}
}
|
package eu.inloop.viewmodel;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
public class ProxyViewHelper {
private static final class ProxyDummyClass {
}
private static final ProxyDummyClass sDummyClass = new ProxyDummyClass();
private static final Class[] sInterfaces = new Class[1];
private ProxyViewHelper() {
}
@SuppressWarnings("unchecked")
@NonNull
static <T> T init(@NonNull Class<?> in) {
sInterfaces[0] = in;
return (T) Proxy.newProxyInstance(sDummyClass.getClass().getClassLoader(), sInterfaces, sInvocationHandler);
}
@Nullable
public static Class<?> getGenericType(@NonNull Class<?> in, @NonNull Class<?> whichExtends) {
final Type genericSuperclass = in.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
final Type[] typeArgs = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
for (Type arg : typeArgs) {
if (arg instanceof ParameterizedType) {
arg = ((ParameterizedType) arg).getRawType();
}
if (arg instanceof Class<?>) {
final Class<?> argClass = (Class<?>) arg;
if (whichExtends.isAssignableFrom(argClass)) {
return argClass;
}
}
}
}
return null;
}
private static final InvocationHandler sInvocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
};
}
|
package info.dourok.lruimage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView.ScaleType;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class VolleyWebImage extends LruImage {
private String url;
private static final int CONNECT_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 10000;
private final Config mDecodeConfig;
private final int mMaxWidth;
private final int mMaxHeight;
private ScaleType mScaleType;
/**
* Decoding lock so that we don't decode more than one image at a time (to avoid OOM's)
*/
private static final Object sDecodeLock = new Object();
public VolleyWebImage(String url) {
this(url, 0, 0, null, null, CACHE_LEVEL_DISK_CACHE | CACHE_LEVEL_MEMORY_CACHE);
}
public VolleyWebImage(String url, int cacheLevel) {
this(url, 0, 0, null, null, cacheLevel);
}
public VolleyWebImage(String url, int maxWidth, int maxHeight,
ScaleType scaleType, Config decodeConfig, int cacheLevel) {
mDecodeConfig = decodeConfig;
mMaxWidth = maxWidth;
mMaxHeight = maxHeight;
mScaleType = scaleType;
setCacheLevel(cacheLevel);
}
@Override
protected Bitmap loadBitmap(Context context) throws LruImageException {
synchronized (sDecodeLock) {
try {
return doParse();
} catch (OutOfMemoryError | IOException e) {
throw new LruImageException(e);
}
}
}
private URLConnection newConnection() throws IOException {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
return conn;
}
private byte[] loadData() throws IOException {
URLConnection conn = newConnection();
conn.connect();
InputStream is = conn.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte data[];
if (conn.getContentLength() > 0) {
data = new byte[conn.getContentLength()];
} else {
data = new byte[8192];
}
int n;
while ((n = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, n);
}
buffer.flush();
return buffer.toByteArray();
}
/**
* The real guts of parseNetworkResponse. Broken out for readability.
*/
private Bitmap doParse() throws IOException {
byte[] data = loadData();
BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
Bitmap bitmap = null;
if (mMaxWidth == 0 && mMaxHeight == 0) {
decodeOptions.inPreferredConfig = mDecodeConfig;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
} else {
// If we have to resize this image, first get the natural bounds.
decodeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
int actualWidth = decodeOptions.outWidth;
int actualHeight = decodeOptions.outHeight;
// Then compute the dimensions we would ideally like to decode to.
int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
actualWidth, actualHeight, mScaleType);
int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
actualHeight, actualWidth, mScaleType);
// Decode to the nearest power of two scaling factor.
decodeOptions.inJustDecodeBounds = false;
// TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?
// decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
decodeOptions.inSampleSize =
findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
Bitmap tempBitmap =
BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
// If necessary, scale down to the maximal acceptable size.
if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||
tempBitmap.getHeight() > desiredHeight)) {
bitmap = Bitmap.createScaledBitmap(tempBitmap,
desiredWidth, desiredHeight, true);
tempBitmap.recycle();
} else {
bitmap = tempBitmap;
}
}
return bitmap;
}
/**
* Scales one side of a rectangle to fit aspect ratio.
*
* @param maxPrimary Maximum size of the primary dimension (i.e. width for
* max width), or zero to maintain aspect ratio with secondary
* dimension
* @param maxSecondary Maximum size of the secondary dimension, or zero to
* maintain aspect ratio with primary dimension
* @param actualPrimary Actual size of the primary dimension
* @param actualSecondary Actual size of the secondary dimension
* @param scaleType The ScaleType used to calculate the needed image size.
*/
private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary,
int actualSecondary, ScaleType scaleType) {
// If no dominant value at all, just return the actual.
if ((maxPrimary == 0) && (maxSecondary == 0)) {
return actualPrimary;
}
// If ScaleType.FIT_XY fill the whole rectangle, ignore ratio.
if (scaleType == ScaleType.FIT_XY) {
if (maxPrimary == 0) {
return actualPrimary;
}
return maxPrimary;
}
// If primary is unspecified, scale primary to match secondary's scaling ratio.
if (maxPrimary == 0) {
double ratio = (double) maxSecondary / (double) actualSecondary;
return (int) (actualPrimary * ratio);
}
if (maxSecondary == 0) {
return maxPrimary;
}
double ratio = (double) actualSecondary / (double) actualPrimary;
int resized = maxPrimary;
// If ScaleType.CENTER_CROP fill the whole rectangle, preserve aspect ratio.
if (scaleType == ScaleType.CENTER_CROP) {
if ((resized * ratio) < maxSecondary) {
resized = (int) (maxSecondary / ratio);
}
return resized;
}
if ((resized * ratio) > maxSecondary) {
resized = (int) (maxSecondary / ratio);
}
return resized;
}
/**
* Returns the largest power-of-two divisor for use in downscaling a bitmap
* that will not result in the scaling past the desired dimensions.
*
* @param actualWidth Actual width of the bitmap
* @param actualHeight Actual height of the bitmap
* @param desiredWidth Desired width of the bitmap
* @param desiredHeight Desired height of the bitmap
*/
// Visible for testing.
static int findBestSampleSize(
int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) {
double wr = (double) actualWidth / desiredWidth;
double hr = (double) actualHeight / desiredHeight;
double ratio = Math.min(wr, hr);
float n = 1.0f;
while ((n * 2) <= ratio) {
n *= 2;
}
return (int) n;
}
@Override
public String getKey() {
String s = "Volley:" + mMaxWidth + url + mMaxWidth;
return Integer.toHexString(s.hashCode());
//s = s.replace(":", "_").replace("/", "_").replace(".", "_");
//return s.substring(s.length() > 64 ? s.length() - 64 : 0, s.length());
}
}
|
package com.iluwatar.hexagonal.service;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.domain.*;
import org.slf4j.Logger;
import java.util.HashSet;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
/**
* Console implementation for lottery console service
*/
public class LotteryConsoleServiceImpl implements LotteryConsoleService {
private final Logger logger;
/**
* Constructor
*/
public LotteryConsoleServiceImpl(Logger logger) {
this.logger = logger;
}
@Override
public void checkTicket(LotteryService service, Scanner scanner) {
logger.info( "What is the ID of the lottery ticket?" );
String id = readString( scanner );
logger.info( "Give the 4 comma separated winning numbers?" );
String numbers = readString( scanner );
try {
String[] parts = numbers.split( "," );
Set<Integer> winningNumbers = new HashSet<>();
for (int i = 0; i < 4; i++) {
winningNumbers.add( Integer.parseInt( parts[i] ) );
}
final LotteryTicketId lotteryTicketId = new LotteryTicketId( Integer.parseInt( id ) );
final LotteryNumbers lotteryNumbers = LotteryNumbers.create( winningNumbers );
LotteryTicketCheckResult result = service.checkTicketForPrize( lotteryTicketId, lotteryNumbers );
if (result.getResult().equals( LotteryTicketCheckResult.CheckResult.WIN_PRIZE )) {
logger.info( "Congratulations! The lottery ticket has won!" );
} else if (result.getResult().equals( LotteryTicketCheckResult.CheckResult.NO_PRIZE )) {
logger.info( "Unfortunately the lottery ticket did not win." );
} else {
logger.info( "Such lottery ticket has not been submitted." );
}
} catch (Exception e) {
logger.info( "Failed checking the lottery ticket - please try again." );
}
}
@Override
public void submitTicket(LotteryService service, Scanner scanner) {
logger.info( "What is your email address?" );
String email = readString( scanner );
logger.info( "What is your bank account number?" );
String account = readString( scanner );
logger.info( "What is your phone number?" );
String phone = readString( scanner );
PlayerDetails details = new PlayerDetails( email, account, phone );
logger.info( "Give 4 comma separated lottery numbers?" );
String numbers = readString( scanner );
try {
String[] parts = numbers.split( "," );
Set<Integer> chosen = new HashSet<>();
for (int i = 0; i < 4; i++) {
chosen.add( Integer.parseInt( parts[i] ) );
}
LotteryNumbers lotteryNumbers = LotteryNumbers.create( chosen );
LotteryTicket lotteryTicket = new LotteryTicket( new LotteryTicketId(), details, lotteryNumbers );
Optional<LotteryTicketId> id = service.submitTicket( lotteryTicket );
if (id.isPresent()) {
logger.info( "Submitted lottery ticket with id: {}", id.get() );
} else {
logger.info( "Failed submitting lottery ticket - please try again." );
}
} catch (Exception e) {
logger.info( "Failed submitting lottery ticket - please try again." );
}
}
@Override
public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) {
logger.info( "What is the account number?" );
String account = readString( scanner );
logger.info( "How many credits do you want to deposit?" );
String amount = readString( scanner );
bank.setFunds( account, Integer.parseInt( amount ) );
logger.info( "The account {} now has {} credits.", account, bank.getFunds( account ) );
}
@Override
public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) {
logger.info( "What is the account number?" );
String account = readString( scanner );
logger.info( "The account {} has {} credits.", account, bank.getFunds( account ) );
}
private String readString(Scanner scanner) {
System.out.print( "> " );
return scanner.next();
}
}
|
package se.emilsjolander.sprinkles;
import android.annotation.TargetApi;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
/**
* Object representing a Query that will return a single result.
*
* @param <T>
* The type of model to return
*/
public final class OneQuery<T extends QueryResult> {
/**
* Implement to get results delivered from a asynchronous query.
*
* @param <T>
* The type of model that the result will represent.
*/
public interface ResultHandler<T extends QueryResult> {
/**
* @param result
* The result of the query.
*
* @return whether or not you want updated result when something changes in the underlying data.
*
*/
boolean handleResult(T result);
}
Class<T> resultClass;
String sqlQuery;
OneQuery() {
}
/**
* Execute the query synchronously
*
* @return the result of the query.
*/
public T get() {
final SQLiteDatabase db = Sprinkles.getDatabase();
final Cursor c = db.rawQuery(sqlQuery, null);
T result = null;
if (c.moveToFirst()) {
result = Utils.getResultFromCursor(resultClass, c);
}
c.close();
return result;
}
/**
* Execute the query asynchronously
*
* @param lm
* The loader manager to use for loading the data
*
* @param handler
* The ResultHandler to notify of the query result and any updates to that result.
*
* @param respondsToUpdatedOf
* A list of models excluding the queried model that should also trigger a update to the result if they change.
*
* @return the id of the loader.
*/
@SuppressWarnings("unchecked")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getAsync(LoaderManager lm,
ResultHandler<T> handler,
Class<? extends Model>... respondsToUpdatedOf) {
if (Model.class.isAssignableFrom(resultClass)) {
respondsToUpdatedOf = Utils.concatArrays(respondsToUpdatedOf, new Class[]{resultClass});
}
final int loaderId = sqlQuery.hashCode();
lm.initLoader(loaderId, null,
getLoaderCallbacks(sqlQuery, resultClass, handler, respondsToUpdatedOf));
return loaderId;
}
/**
* Execute the query asynchronously
*
* @param lm
* The loader manager to use for loading the data
*
* @param handler
* The ResultHandler to notify of the query result and any updates to that result.
*
* @param respondsToUpdatedOf
* A list of models excluding the queried model that should also trigger a update to the result if they change.
*
* @return the id of the loader.
*/
@SuppressWarnings("unchecked")
public int getAsync(android.support.v4.app.LoaderManager lm,
ResultHandler<T> handler,
Class<? extends Model>... respondsToUpdatedOf) {
if (Model.class.isAssignableFrom(resultClass)) {
respondsToUpdatedOf = Utils.concatArrays(respondsToUpdatedOf, new Class[]{resultClass});
}
final int loaderId = sqlQuery.hashCode();
lm.initLoader(loaderId, null,
getSupportLoaderCallbacks(sqlQuery, resultClass, handler, respondsToUpdatedOf));
return loaderId;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private LoaderCallbacks<Cursor> getLoaderCallbacks(final String sqlQuery,
final Class<T> resultClass,
final ResultHandler<T> handler,
final Class<? extends Model>[] respondsToUpdatedOf) {
return new LoaderCallbacks<Cursor>() {
@Override
public void onLoaderReset(Loader<Cursor> loader) {
if (!loader.isAbandoned()) {
handler.handleResult(null);
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
T result = null;
if (c.moveToFirst()) {
result = Utils.getResultFromCursor(resultClass, c);
}
if (!handler.handleResult(result)) {
loader.abandon();
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(Sprinkles.sInstance.mContext, sqlQuery, respondsToUpdatedOf);
}
};
}
private android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor> getSupportLoaderCallbacks(
final String sqlQuery,
final Class<T> resultClass,
final ResultHandler<T> handler,
final Class<? extends Model>[] respondsToUpdatedOf) {
return new android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public void onLoaderReset(
android.support.v4.content.Loader<Cursor> loader) {
if (!loader.isAbandoned()) {
handler.handleResult(null);
}
}
@Override
public void onLoadFinished(
android.support.v4.content.Loader<Cursor> loader, Cursor c) {
T result = null;
if (c.moveToFirst()) {
result = Utils.getResultFromCursor(resultClass, c);
}
if (!handler.handleResult(result)) {
loader.abandon();
}
}
@Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(
int id, Bundle args) {
return new SupportCursorLoader(Sprinkles.sInstance.mContext, sqlQuery, respondsToUpdatedOf);
}
};
}
}
|
package org.whattf.datatype;
import org.relaxng.datatype.DatatypeException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XmlName extends AbstractDatatype {
private static final Pattern THE_PATTERN = Pattern.compile("(?:[\\u0041-\\u005A]|[\\u0061-\\u007A]|[\\u00C0-\\u00D6]|[\\u00D8-\\u00F6]|[\\u00F8-\\u00FF]|[\\u0100-\\u0131]|[\\u0134-\\u013E]|[\\u0141-\\u0148]|[\\u014A-\\u017E]|[\\u0180-\\u01C3]|[\\u01CD-\\u01F0]|[\\u01F4-\\u01F5]|[\\u01FA-\\u0217]|[\\u0250-\\u02A8]|[\\u02BB-\\u02C1]|\\u0386|[\\u0388-\\u038A]|\\u038C|[\\u038E-\\u03A1]|[\\u03A3-\\u03CE]|[\\u03D0-\\u03D6]|\\u03DA|\\u03DC|\\u03DE|\\u03E0|[\\u03E2-\\u03F3]|[\\u0401-\\u040C]|[\\u040E-\\u044F]|[\\u0451-\\u045C]|[\\u045E-\\u0481]|[\\u0490-\\u04C4]|[\\u04C7-\\u04C8]|[\\u04CB-\\u04CC]|[\\u04D0-\\u04EB]|[\\u04EE-\\u04F5]|[\\u04F8-\\u04F9]|[\\u0531-\\u0556]|\\u0559|[\\u0561-\\u0586]|[\\u05D0-\\u05EA]|[\\u05F0-\\u05F2]|[\\u0621-\\u063A]|[\\u0641-\\u064A]|[\\u0671-\\u06B7]|[\\u06BA-\\u06BE]|[\\u06C0-\\u06CE]|[\\u06D0-\\u06D3]|\\u06D5|[\\u06E5-\\u06E6]|[\\u0905-\\u0939]|\\u093D|[\\u0958-\\u0961]|[\\u0985-\\u098C]|[\\u098F-\\u0990]|[\\u0993-\\u09A8]|[\\u09AA-\\u09B0]|\\u09B2|[\\u09B6-\\u09B9]|[\\u09DC-\\u09DD]|[\\u09DF-\\u09E1]|[\\u09F0-\\u09F1]|[\\u0A05-\\u0A0A]|[\\u0A0F-\\u0A10]|[\\u0A13-\\u0A28]|[\\u0A2A-\\u0A30]|[\\u0A32-\\u0A33]|[\\u0A35-\\u0A36]|[\\u0A38-\\u0A39]|[\\u0A59-\\u0A5C]|\\u0A5E|[\\u0A72-\\u0A74]|[\\u0A85-\\u0A8B]|\\u0A8D|[\\u0A8F-\\u0A91]|[\\u0A93-\\u0AA8]|[\\u0AAA-\\u0AB0]|[\\u0AB2-\\u0AB3]|[\\u0AB5-\\u0AB9]|\\u0ABD|\\u0AE0|[\\u0B05-\\u0B0C]|[\\u0B0F-\\u0B10]|[\\u0B13-\\u0B28]|[\\u0B2A-\\u0B30]|[\\u0B32-\\u0B33]|[\\u0B36-\\u0B39]|\\u0B3D|[\\u0B5C-\\u0B5D]|[\\u0B5F-\\u0B61]|[\\u0B85-\\u0B8A]|[\\u0B8E-\\u0B90]|[\\u0B92-\\u0B95]|[\\u0B99-\\u0B9A]|\\u0B9C|[\\u0B9E-\\u0B9F]|[\\u0BA3-\\u0BA4]|[\\u0BA8-\\u0BAA]|[\\u0BAE-\\u0BB5]|[\\u0BB7-\\u0BB9]|[\\u0C05-\\u0C0C]|[\\u0C0E-\\u0C10]|[\\u0C12-\\u0C28]|[\\u0C2A-\\u0C33]|[\\u0C35-\\u0C39]|[\\u0C60-\\u0C61]|[\\u0C85-\\u0C8C]|[\\u0C8E-\\u0C90]|[\\u0C92-\\u0CA8]|[\\u0CAA-\\u0CB3]|[\\u0CB5-\\u0CB9]|\\u0CDE|[\\u0CE0-\\u0CE1]|[\\u0D05-\\u0D0C]|[\\u0D0E-\\u0D10]|[\\u0D12-\\u0D28]|[\\u0D2A-\\u0D39]|[\\u0D60-\\u0D61]|[\\u0E01-\\u0E2E]|\\u0E30|[\\u0E32-\\u0E33]|[\\u0E40-\\u0E45]|[\\u0E81-\\u0E82]|\\u0E84|[\\u0E87-\\u0E88]|\\u0E8A|\\u0E8D|[\\u0E94-\\u0E97]|[\\u0E99-\\u0E9F]|[\\u0EA1-\\u0EA3]|\\u0EA5|\\u0EA7|[\\u0EAA-\\u0EAB]|[\\u0EAD-\\u0EAE]|\\u0EB0|[\\u0EB2-\\u0EB3]|\\u0EBD|[\\u0EC0-\\u0EC4]|[\\u0F40-\\u0F47]|[\\u0F49-\\u0F69]|[\\u10A0-\\u10C5]|[\\u10D0-\\u10F6]|\\u1100|[\\u1102-\\u1103]|[\\u1105-\\u1107]|\\u1109|[\\u110B-\\u110C]|[\\u110E-\\u1112]|\\u113C|\\u113E|\\u1140|\\u114C|\\u114E|\\u1150|[\\u1154-\\u1155]|\\u1159|[\\u115F-\\u1161]|\\u1163|\\u1165|\\u1167|\\u1169|[\\u116D-\\u116E]|[\\u1172-\\u1173]|\\u1175|\\u119E|\\u11A8|\\u11AB|[\\u11AE-\\u11AF]|[\\u11B7-\\u11B8]|\\u11BA|[\\u11BC-\\u11C2]|\\u11EB|\\u11F0|\\u11F9|[\\u1E00-\\u1E9B]|[\\u1EA0-\\u1EF9]|[\\u1F00-\\u1F15]|[\\u1F18-\\u1F1D]|[\\u1F20-\\u1F45]|[\\u1F48-\\u1F4D]|[\\u1F50-\\u1F57]|\\u1F59|\\u1F5B|\\u1F5D|[\\u1F5F-\\u1F7D]|[\\u1F80-\\u1FB4]|[\\u1FB6-\\u1FBC]|\\u1FBE|[\\u1FC2-\\u1FC4]|[\\u1FC6-\\u1FCC]|[\\u1FD0-\\u1FD3]|[\\u1FD6-\\u1FDB]|[\\u1FE0-\\u1FEC]|[\\u1FF2-\\u1FF4]|[\\u1FF6-\\u1FFC]|\\u2126|[\\u212A-\\u212B]|\\u212E|[\\u2180-\\u2182]|[\\u3041-\\u3094]|[\\u30A1-\\u30FA]|[\\u3105-\\u312C]|[\\uAC00-\\uD7A3]|[\\u4E00-\\u9FA5]|\\u3007|[\\u3021-\\u3029]|_|:)(?:[\\u0030-\\u0039]|[\\u0660-\\u0669]|[\\u06F0-\\u06F9]|[\\u0966-\\u096F]|[\\u09E6-\\u09EF]|[\\u0A66-\\u0A6F]|[\\u0AE6-\\u0AEF]|[\\u0B66-\\u0B6F]|[\\u0BE7-\\u0BEF]|[\\u0C66-\\u0C6F]|[\\u0CE6-\\u0CEF]|[\\u0D66-\\u0D6F]|[\\u0E50-\\u0E59]|[\\u0ED0-\\u0ED9]|[\\u0F20-\\u0F29]|[\\u0041-\\u005A]|[\\u0061-\\u007A]|[\\u00C0-\\u00D6]|[\\u00D8-\\u00F6]|[\\u00F8-\\u00FF]|[\\u0100-\\u0131]|[\\u0134-\\u013E]|[\\u0141-\\u0148]|[\\u014A-\\u017E]|[\\u0180-\\u01C3]|[\\u01CD-\\u01F0]|[\\u01F4-\\u01F5]|[\\u01FA-\\u0217]|[\\u0250-\\u02A8]|[\\u02BB-\\u02C1]|\\u0386|[\\u0388-\\u038A]|\\u038C|[\\u038E-\\u03A1]|[\\u03A3-\\u03CE]|[\\u03D0-\\u03D6]|\\u03DA|\\u03DC|\\u03DE|\\u03E0|[\\u03E2-\\u03F3]|[\\u0401-\\u040C]|[\\u040E-\\u044F]|[\\u0451-\\u045C]|[\\u045E-\\u0481]|[\\u0490-\\u04C4]|[\\u04C7-\\u04C8]|[\\u04CB-\\u04CC]|[\\u04D0-\\u04EB]|[\\u04EE-\\u04F5]|[\\u04F8-\\u04F9]|[\\u0531-\\u0556]|\\u0559|[\\u0561-\\u0586]|[\\u05D0-\\u05EA]|[\\u05F0-\\u05F2]|[\\u0621-\\u063A]|[\\u0641-\\u064A]|[\\u0671-\\u06B7]|[\\u06BA-\\u06BE]|[\\u06C0-\\u06CE]|[\\u06D0-\\u06D3]|\\u06D5|[\\u06E5-\\u06E6]|[\\u0905-\\u0939]|\\u093D|[\\u0958-\\u0961]|[\\u0985-\\u098C]|[\\u098F-\\u0990]|[\\u0993-\\u09A8]|[\\u09AA-\\u09B0]|\\u09B2|[\\u09B6-\\u09B9]|[\\u09DC-\\u09DD]|[\\u09DF-\\u09E1]|[\\u09F0-\\u09F1]|[\\u0A05-\\u0A0A]|[\\u0A0F-\\u0A10]|[\\u0A13-\\u0A28]|[\\u0A2A-\\u0A30]|[\\u0A32-\\u0A33]|[\\u0A35-\\u0A36]|[\\u0A38-\\u0A39]|[\\u0A59-\\u0A5C]|\\u0A5E|[\\u0A72-\\u0A74]|[\\u0A85-\\u0A8B]|\\u0A8D|[\\u0A8F-\\u0A91]|[\\u0A93-\\u0AA8]|[\\u0AAA-\\u0AB0]|[\\u0AB2-\\u0AB3]|[\\u0AB5-\\u0AB9]|\\u0ABD|\\u0AE0|[\\u0B05-\\u0B0C]|[\\u0B0F-\\u0B10]|[\\u0B13-\\u0B28]|[\\u0B2A-\\u0B30]|[\\u0B32-\\u0B33]|[\\u0B36-\\u0B39]|\\u0B3D|[\\u0B5C-\\u0B5D]|[\\u0B5F-\\u0B61]|[\\u0B85-\\u0B8A]|[\\u0B8E-\\u0B90]|[\\u0B92-\\u0B95]|[\\u0B99-\\u0B9A]|\\u0B9C|[\\u0B9E-\\u0B9F]|[\\u0BA3-\\u0BA4]|[\\u0BA8-\\u0BAA]|[\\u0BAE-\\u0BB5]|[\\u0BB7-\\u0BB9]|[\\u0C05-\\u0C0C]|[\\u0C0E-\\u0C10]|[\\u0C12-\\u0C28]|[\\u0C2A-\\u0C33]|[\\u0C35-\\u0C39]|[\\u0C60-\\u0C61]|[\\u0C85-\\u0C8C]|[\\u0C8E-\\u0C90]|[\\u0C92-\\u0CA8]|[\\u0CAA-\\u0CB3]|[\\u0CB5-\\u0CB9]|\\u0CDE|[\\u0CE0-\\u0CE1]|[\\u0D05-\\u0D0C]|[\\u0D0E-\\u0D10]|[\\u0D12-\\u0D28]|[\\u0D2A-\\u0D39]|[\\u0D60-\\u0D61]|[\\u0E01-\\u0E2E]|\\u0E30|[\\u0E32-\\u0E33]|[\\u0E40-\\u0E45]|[\\u0E81-\\u0E82]|\\u0E84|[\\u0E87-\\u0E88]|\\u0E8A|\\u0E8D|[\\u0E94-\\u0E97]|[\\u0E99-\\u0E9F]|[\\u0EA1-\\u0EA3]|\\u0EA5|\\u0EA7|[\\u0EAA-\\u0EAB]|[\\u0EAD-\\u0EAE]|\\u0EB0|[\\u0EB2-\\u0EB3]|\\u0EBD|[\\u0EC0-\\u0EC4]|[\\u0F40-\\u0F47]|[\\u0F49-\\u0F69]|[\\u10A0-\\u10C5]|[\\u10D0-\\u10F6]|\\u1100|[\\u1102-\\u1103]|[\\u1105-\\u1107]|\\u1109|[\\u110B-\\u110C]|[\\u110E-\\u1112]|\\u113C|\\u113E|\\u1140|\\u114C|\\u114E|\\u1150|[\\u1154-\\u1155]|\\u1159|[\\u115F-\\u1161]|\\u1163|\\u1165|\\u1167|\\u1169|[\\u116D-\\u116E]|[\\u1172-\\u1173]|\\u1175|\\u119E|\\u11A8|\\u11AB|[\\u11AE-\\u11AF]|[\\u11B7-\\u11B8]|\\u11BA|[\\u11BC-\\u11C2]|\\u11EB|\\u11F0|\\u11F9|[\\u1E00-\\u1E9B]|[\\u1EA0-\\u1EF9]|[\\u1F00-\\u1F15]|[\\u1F18-\\u1F1D]|[\\u1F20-\\u1F45]|[\\u1F48-\\u1F4D]|[\\u1F50-\\u1F57]|\\u1F59|\\u1F5B|\\u1F5D|[\\u1F5F-\\u1F7D]|[\\u1F80-\\u1FB4]|[\\u1FB6-\\u1FBC]|\\u1FBE|[\\u1FC2-\\u1FC4]|[\\u1FC6-\\u1FCC]|[\\u1FD0-\\u1FD3]|[\\u1FD6-\\u1FDB]|[\\u1FE0-\\u1FEC]|[\\u1FF2-\\u1FF4]|[\\u1FF6-\\u1FFC]|\\u2126|[\\u212A-\\u212B]|\\u212E|[\\u2180-\\u2182]|[\\u3041-\\u3094]|[\\u30A1-\\u30FA]|[\\u3105-\\u312C]|[\\uAC00-\\uD7A3]|[\\u4E00-\\u9FA5]|\\u3007|[\\u3021-\\u3029]|_|\\.|-|[\\u0300-\\u0345]|[\\u0360-\\u0361]|[\\u0483-\\u0486]|[\\u0591-\\u05A1]|[\\u05A3-\\u05B9]|[\\u05BB-\\u05BD]|\\u05BF|[\\u05C1-\\u05C2]|\\u05C4|[\\u064B-\\u0652]|\\u0670|[\\u06D6-\\u06DC]|[\\u06DD-\\u06DF]|[\\u06E0-\\u06E4]|[\\u06E7-\\u06E8]|[\\u06EA-\\u06ED]|[\\u0901-\\u0903]|\\u093C|[\\u093E-\\u094C]|\\u094D|[\\u0951-\\u0954]|[\\u0962-\\u0963]|[\\u0981-\\u0983]|\\u09BC|\\u09BE|\\u09BF|[\\u09C0-\\u09C4]|[\\u09C7-\\u09C8]|[\\u09CB-\\u09CD]|\\u09D7|[\\u09E2-\\u09E3]|\\u0A02|\\u0A3C|\\u0A3E|\\u0A3F|[\\u0A40-\\u0A42]|[\\u0A47-\\u0A48]|[\\u0A4B-\\u0A4D]|[\\u0A70-\\u0A71]|[\\u0A81-\\u0A83]|\\u0ABC|[\\u0ABE-\\u0AC5]|[\\u0AC7-\\u0AC9]|[\\u0ACB-\\u0ACD]|[\\u0B01-\\u0B03]|\\u0B3C|[\\u0B3E-\\u0B43]|[\\u0B47-\\u0B48]|[\\u0B4B-\\u0B4D]|[\\u0B56-\\u0B57]|[\\u0B82-\\u0B83]|[\\u0BBE-\\u0BC2]|[\\u0BC6-\\u0BC8]|[\\u0BCA-\\u0BCD]|\\u0BD7|[\\u0C01-\\u0C03]|[\\u0C3E-\\u0C44]|[\\u0C46-\\u0C48]|[\\u0C4A-\\u0C4D]|[\\u0C55-\\u0C56]|[\\u0C82-\\u0C83]|[\\u0CBE-\\u0CC4]|[\\u0CC6-\\u0CC8]|[\\u0CCA-\\u0CCD]|[\\u0CD5-\\u0CD6]|[\\u0D02-\\u0D03]|[\\u0D3E-\\u0D43]|[\\u0D46-\\u0D48]|[\\u0D4A-\\u0D4D]|\\u0D57|\\u0E31|[\\u0E34-\\u0E3A]|[\\u0E47-\\u0E4E]|\\u0EB1|[\\u0EB4-\\u0EB9]|[\\u0EBB-\\u0EBC]|[\\u0EC8-\\u0ECD]|[\\u0F18-\\u0F19]|\\u0F35|\\u0F37|\\u0F39|\\u0F3E|\\u0F3F|[\\u0F71-\\u0F84]|[\\u0F86-\\u0F8B]|[\\u0F90-\\u0F95]|\\u0F97|[\\u0F99-\\u0FAD]|[\\u0FB1-\\u0FB7]|\\u0FB9|[\\u20D0-\\u20DC]|\\u20E1|[\\u302A-\\u302F]|\\u3099|\\u309A|\\u00B7|\\u02D0|\\u02D1|\\u0387|\\u0640|\\u0E46|\\u0EC6|\\u3005|[\\u3031-\\u3035]|[\\u309D-\\u309E]|[\\u30FC-\\u30FE]|:)*");
/**
* The singleton instance.
*/
public static final XmlName THE_INSTANCE = new XmlName();
private XmlName() {
}
@Override
public void checkValid(CharSequence literal) throws DatatypeException {
Matcher m = THE_PATTERN.matcher(literal);
if (!m.matches()) {
throw newDatatypeException("Not a valid XML 1.0 name.");
}
}
@Override
public String getName() {
return "XML name";
}
}
|
package algorithms.imageProcessing.util;
import algorithms.util.PolygonAndPointPlotter;
import algorithms.util.ResourceFinder;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Logger;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.ejml.simple.*;
/**
*
* @author nichole
*/
public class MatrixUtilTest extends TestCase {
private Logger log = Logger.getLogger(this.getClass().getName());
public MatrixUtilTest() {
}
public void testDot() throws Exception {
double[][] m1 = new double[2][3];
m1[0] = new double[]{0, 1, 0};
m1[1] = new double[]{1000, 100, 10};
double[][] m2 = new double[3][2];
m2[0] = new double[]{2, 1};
m2[1] = new double[]{3, 0};
m2[2] = new double[]{4, 0};
/*
0 1 0 2 1
1000 100 10 3 0
4 0
0*2 + 1*3 + 0*0 0*1 + 1*0 + 0*0
1000*2 + 100*3 + 10*4 1000*1 + 100*0 + 10*0
*/
double[][] m = MatrixUtil.dot(new SimpleMatrix(m1),
new SimpleMatrix(m2));
assertTrue(m.length == 2);
assertTrue(m[0].length == 2);
assertTrue(m[1].length == 2);
assertTrue(m[0][0] == 3);
assertTrue(m[1][0] == 2340);
assertTrue(m[0][1] == 0);
assertTrue(m[1][1] == 1000);
}
public void testMultiply() throws Exception {
double[][] a = new double[2][3];
a[0] = new double[]{1, 2, 3};
a[1] = new double[]{2, 3, 4};
double[] b = new double[]{4, 3};
double[] m = MatrixUtil.multiply(a, b);
assertTrue( m[0] == 10 );
assertTrue( m[1] == 17 );
assertTrue( m[2] == 24 );
double[][] c = new double[3][];
for (int i = 0; i < 3; i++) {
c[i] = new double[3];
for (int j = 0; j < 3; j++) {
c[i][j] = 1;
}
}
c[1][2] = 0;
/*
a b c p0 p1 p2
d e f p3 p4 p5
p6 p7 p8
a*p0+... a*p a*p
d*p0+... d*p d*p
1 2 3 1 1 1
2 3 4 1 1 0
1 1 1
(1*1 + 2*1 + 3*1) (1*1 + 2*1 + 3*1) (1*1 + 0 + 3*1)
(2*1 + 3*1 + 4*1) (2*1 + 3*1 + 4*1) (2*1 + 0 + 4*1)
6 6 4
9 9 6
*/
double[][] d = MatrixUtil.multiply(a, c);
assertTrue(d[0][0] == 6);
assertTrue(d[0][1] == 6);
assertTrue(d[0][2] == 4);
assertTrue(d[1][0] == 9);
assertTrue(d[1][1] == 9);
assertTrue(d[1][2] == 6);
/*
example: m is 1 2 3
4 5 6
7 8 9
n is 100 101 1
200 201 1
multiply m by transpose of n:
1 2 3 100 200
4 5 6 101 201
7 8 9 1 1
(1*100 + 2*101 + 3*1) (1*200 + 2*201 + 3*1) 305 605
(4*100 + 5*101 + 6*1) (4*200 + 5*201 + 6*1) = 911 1811
(7*100 + 8*101 + 9*1) (7*200 + 8*201 + 9*1) 1517 3017
*/
double[][] aa = new double[3][];
aa[0] = new double[]{1, 2, 3};
aa[1] = new double[]{4, 5, 6};
aa[2] = new double[]{7, 8, 9};
double[][] bb = new double[2][];
bb[0] = new double[]{100, 101, 1};
bb[1] = new double[]{200, 201, 1};
double[][] cc = MatrixUtil.multiplyByTranspose(aa, bb);
assertTrue(cc[0][0] == 305);
assertTrue(cc[0][1] == 605);
assertTrue(cc[1][0] == 911);
assertTrue(cc[1][1] == 1811);
assertTrue(cc[2][0] == 1517);
assertTrue(cc[2][1] == 3017);
int[] z = new int[]{0, 1, 2, 3};
int factor = 2;
int[] expectedZ = new int[]{0, 2, 4, 6};
MatrixUtil.multiply(z, factor);
for (int i = 0; i < z.length; i++) {
assertTrue(z[i] == expectedZ[i]);
}
}
public void testAdd() throws Exception {
double[] a = new double[]{1, 2, 3, 4};
double[] b = new double[]{100, 100, 100, 100};
double[] expected = new double[]{101, 102, 103, 104};
double[] c = MatrixUtil.add(a, b);
assertTrue(Arrays.equals(expected, c));
}
public void testAdd2() throws Exception {
float[] a = new float[]{1, 2, 3, 4};
float[] b = new float[]{100, 100, 100, 100};
float[] expected = new float[]{101, 102, 103, 104};
float[] c = MatrixUtil.add(a, b);
assertTrue(Arrays.equals(expected, c));
}
public void testAdd3() throws Exception {
int[] a = new int[]{1, 2, 3, 4};
int add = -1;
int[] expected = new int[]{0, 1, 2, 3};
MatrixUtil.add(a, add);
assertTrue(Arrays.equals(expected, a));
}
public void testSubtract() throws Exception {
float[] a = new float[]{100, 100, 100, 100};
float[] b = new float[]{1, 2, 3, 4};
float[] expected = new float[]{99, 98, 97, 96};
float[] c = MatrixUtil.subtract(a, b);
assertTrue(Arrays.equals(expected, c));
}
public void testTranspose() throws Exception {
/*
100 101 1 100 200
200 201 1 101 201
1 1
*/
float[][] bb = new float[2][];
bb[0] = new float[]{100, 101, 1};
bb[1] = new float[]{200, 201, 1};
float[][] expected = new float[3][];
expected[0] = new float[]{100, 200};
expected[1] = new float[]{101, 201};
expected[2] = new float[]{1, 1};
float[][] cc = MatrixUtil.transpose(bb);
for (int i = 0; i < cc.length; i++) {
for (int j = 0; j < cc[i].length; j++) {
assertTrue(expected[i][j] == cc[i][j]);
}
}
float[][] dd = MatrixUtil.transpose(cc);
for (int i = 0; i < dd.length; i++) {
for (int j = 0; j < dd[i].length; j++) {
assertTrue(bb[i][j] == dd[i][j]);
}
}
}
public void testScaleToUnitVariance() throws Exception {
SimpleMatrix[] dataAndClasses = readIrisDataset();
double v0 = dataAndClasses[0].get(0, 0);
double v1 = dataAndClasses[0].get(1, 0);
double v2 = dataAndClasses[0].get(2, 0);
double v3 = dataAndClasses[0].get(3, 0);
double[] expected = new double[]{5.1,3.5,1.4,0.2};
assertTrue(Math.abs(v0 - expected[0]) < 0.05*Math.abs(expected[0]));
assertTrue(Math.abs(v1 - expected[1]) < 0.05*Math.abs(expected[1]));
assertTrue(Math.abs(v2 - expected[2]) < 0.05*Math.abs(expected[2]));
assertTrue(Math.abs(v3 - expected[3]) < 0.05*Math.abs(expected[3]));
SimpleMatrix normData = MatrixUtil.scaleToUnitStandardDeviation(
dataAndClasses[0]);
/*
assert first 4
[ -9.0068e-01 1.0321e+00 -1.3413e+00 -1.3130e+00]
[ -1.1430e+00 -1.2496e-01 -1.3413e+00 -1.3130e+00]
[ -1.3854e+00 3.3785e-01 -1.3981e+00 -1.3130e+00]
[ -1.5065e+00 1.0645e-01 -1.2844e+00 -1.3130e+00]
[ -1.0218e+00 1.2635e+00 -1.3413e+00 -1.3130e+00]
*/
v0 = normData.get(0, 0);
v1 = normData.get(1, 0);
v2 = normData.get(2, 0);
v3 = normData.get(3, 0);
expected = new double[]{-9.0068e-01, 1.0321e+00, -1.3413e+00, -1.3130e+00};
assertTrue(Math.abs(v0 - expected[0]) < 0.05*Math.abs(expected[0]));
assertTrue(Math.abs(v1 - expected[1]) < 0.05*Math.abs(expected[1]));
assertTrue(Math.abs(v2 - expected[2]) < 0.05*Math.abs(expected[2]));
assertTrue(Math.abs(v3 - expected[3]) < 0.05*Math.abs(expected[3]));
// assert mean = 0
// assert var = 1
int n = normData.numCols();
int nRows = normData.numRows();
double[] mean = new double[nRows];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < nRows; ++j) {
mean[j] += normData.get(j, i);
}
}
for (int j = 0; j < nRows; ++j) {
mean[j] /= (double)n;
assertTrue(Math.abs(mean[j]) < 0.1);
}
double[] stdev = new double[nRows];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < nRows; ++j) {
double d = normData.get(j, i) - mean[j];
stdev[j] += (d * d);
}
}
for (int j = 0; j < nRows; ++j) {
stdev[j] = Math.sqrt(stdev[j]/(double)(n - 1));
assertTrue(Math.abs(stdev[j] - 1.) < 0.1);
}
}
public void testCreateLDATrasformation() throws Exception {
SimpleMatrix[] dataAndClasses = readIrisDataset();
SimpleMatrix classes = dataAndClasses[1].copy();
SimpleMatrix w = MatrixUtil.createLDATransformation(dataAndClasses[0],
dataAndClasses[1]);
assertEquals(2, w.numRows());
assertEquals(4, w.numCols());
assertTrue(Math.abs(w.get(0, 0) - 0.15) < 0.01);
assertTrue(Math.abs(w.get(0, 1) - 0.148) < 0.01);
assertTrue(Math.abs(w.get(0, 2) - -0.851) < 0.01);
assertTrue(Math.abs(w.get(0, 3) - -0.481) < 0.01);
assertTrue(Math.abs(w.get(1, 0) - 0.010) < 0.01);
assertTrue(Math.abs(w.get(1, 1) - 0.327) < 0.01);
assertTrue(Math.abs(w.get(1, 2) - -0.575) < 0.01);
assertTrue(Math.abs(w.get(1, 3) - 0.750) < 0.01);
SimpleMatrix normData = MatrixUtil.scaleToUnitStandardDeviation(dataAndClasses[0]);
// transforms from integer classes to zero based counting with delta of 1
// for example: [1, 2, 5, ...] becomes [0, 1, 2, ...]
int nClasses = MatrixUtil.transformToZeroBasedClasses(classes);
SimpleMatrix w2 = MatrixUtil.createLDATransformation2(normData, classes, nClasses);
assertEquals(2, w2.numRows());
assertEquals(4, w2.numCols());
assertTrue(Math.abs(w2.get(0, 0) - 0.15) < 0.01);
assertTrue(Math.abs(w2.get(0, 1) - 0.148) < 0.01);
assertTrue(Math.abs(w2.get(0, 2) - -0.851) < 0.01);
assertTrue(Math.abs(w2.get(0, 3) - -0.481) < 0.01);
assertTrue(Math.abs(w2.get(1, 0) - 0.010) < 0.01);
assertTrue(Math.abs(w2.get(1, 1) - 0.327) < 0.01);
assertTrue(Math.abs(w2.get(1, 2) - -0.575) < 0.01);
assertTrue(Math.abs(w2.get(1, 3) - 0.750) < 0.01);
int nr = w2.numRows();
int nc = w2.numCols();
int nr2 = normData.numRows();
int nc2 = normData.numCols();
// 2 X 150
SimpleMatrix dataTransformed = new SimpleMatrix(MatrixUtil.dot(w, normData));
float minX = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float minY = Float.MAX_VALUE;
float maxY = Float.MIN_VALUE;
int[] countClasses = new int[nClasses];
for (int col = 0; col < dataTransformed.numCols(); ++col) {
int k = (int)Math.round(classes.get(0, col));
countClasses[k]++;
float x = (float)dataTransformed.get(0, col);
float y = (float)dataTransformed.get(1, col);
if (x < minX) {
minX = x;
}
if (y < minY) {
minY = y;
}
if (x > maxX) {
maxX = x;
}
if (y > maxY) {
maxY = y;
}
}
PolygonAndPointPlotter plotter = new PolygonAndPointPlotter(minX, maxX,
minY, maxY);
for (int k = 0; k < nClasses; ++k) {
float[] xPoint = new float[countClasses[k]];
float[] yPoint = new float[countClasses[k]];
int count = 0;
for (int col = 0; col < dataTransformed.numCols(); ++col) {
if ((int)Math.round(classes.get(0, col)) != k) {
continue;
}
xPoint[count] = (float)dataTransformed.get(0, col);
yPoint[count] = (float)dataTransformed.get(1, col);
count++;
}
float[] xPoly = null;
float[] yPoly = null;
plotter.addPlot(xPoint, yPoint, xPoly, yPoly, "class " + k);
}
String file1 = plotter.writeFile();
/*System.out.println(String.format("(%.3f, %.3f)",
(float)dataTransformed.get(0, 0),
(float)dataTransformed.get(1, 0)));
System.out.println(String.format("(%.3f, %.3f)",
(float)dataTransformed.get(0, 1),
(float)dataTransformed.get(1, 1)));
System.out.println(String.format("(%.3f, %.3f)",
(float)dataTransformed.get(0, 2),
(float)dataTransformed.get(1, 2)));*/
assertTrue(Math.abs(dataTransformed.get(0, 0) - 1.791) < 0.01);
assertTrue(Math.abs(dataTransformed.get(1, 0) - 0.115) < 0.01);
assertTrue(Math.abs(dataTransformed.get(0, 1) - 1.583) < 0.01);
assertTrue(Math.abs(dataTransformed.get(1, 1) - -0.265) < 0.01);
assertTrue(Math.abs(dataTransformed.get(0, 2) - 1.664) < 0.01);
assertTrue(Math.abs(dataTransformed.get(1, 2) - -0.084) < 0.01);
SimpleMatrix w3 = MatrixUtil.createLDATransformation(
dataAndClasses[0], dataAndClasses[1]);
SimpleMatrix dataTransformed3 = new SimpleMatrix(MatrixUtil.dot(w3,
dataAndClasses[0]));
minX = Float.MAX_VALUE;
maxX = Float.MIN_VALUE;
minY = Float.MAX_VALUE;
maxY = Float.MIN_VALUE;
countClasses = new int[nClasses];
for (int col = 0; col < dataTransformed3.numCols(); ++col) {
int k = (int)Math.round(classes.get(0, col));
countClasses[k]++;
float x = (float)dataTransformed3.get(0, col);
float y = (float)dataTransformed3.get(1, col);
if (x < minX) {
minX = x;
}
if (y < minY) {
minY = y;
}
if (x > maxX) {
maxX = x;
}
if (y > maxY) {
maxY = y;
}
}
PolygonAndPointPlotter plotter2 = new PolygonAndPointPlotter(minX, maxX,
minY, maxY);
for (int k = 0; k < nClasses; ++k) {
float[] xPoint = new float[countClasses[k]];
float[] yPoint = new float[countClasses[k]];
int count = 0;
for (int col = 0; col < dataTransformed3.numCols(); ++col) {
if ((int)Math.round(classes.get(0, col)) != k) {
continue;
}
xPoint[count] = (float)dataTransformed3.get(0, col);
yPoint[count] = (float)dataTransformed3.get(1, col);
count++;
}
float[] xPoly = null;
float[] yPoly = null;
plotter2.addPlot(xPoint, yPoint, xPoly, yPoly, "class " + k);
}
String file2 = plotter2.writeFile2();
}
private SimpleMatrix[] readIrisDataset() throws Exception {
BufferedReader bReader = null;
FileReader reader = null;
String filePath = ResourceFinder.findFileInTestResources("iris.data");
try {
reader = new FileReader(new File(filePath));
bReader = new BufferedReader(reader);
SimpleMatrix data = new SimpleMatrix(4, 150);
SimpleMatrix classes = new SimpleMatrix(1, 150);
String line = bReader.readLine();
int count = 0;
while (line != null) {
String[] items = line.split(",");
if (items.length != 5) {
throw new IllegalStateException("expecting 5 items in a line");
}
for (int j = 0; j < 4; ++j) {
data.set(j, count, Double.valueOf(items[j]));
}
double classValue = 4;
if (items[4].equals("Iris-setosa")) {
classValue = 1;
} else if (items[4].equals("Iris-versicolor")) {
classValue = 2;
}
//Iris-virginica
classes.set(count, classValue);
line = bReader.readLine();
count++;
}
return new SimpleMatrix[]{data, classes};
} catch (IOException e) {
log.severe(e.getMessage());
} finally {
if (reader == null) {
reader.close();
}
if (bReader == null) {
bReader.close();
}
}
return null;
}
}
|
package com.apptentive.android.sdk;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import com.apptentive.android.sdk.comm.ApptentiveClient;
import com.apptentive.android.sdk.comm.ApptentiveHttpResponse;
import com.apptentive.android.sdk.model.*;
import com.apptentive.android.sdk.module.engagement.EngagementModule;
import com.apptentive.android.sdk.module.engagement.interaction.InteractionManager;
import com.apptentive.android.sdk.module.messagecenter.MessageManager;
import com.apptentive.android.sdk.module.messagecenter.MessagePollingWorker;
import com.apptentive.android.sdk.module.messagecenter.UnreadMessagesListener;
import com.apptentive.android.sdk.lifecycle.ActivityLifecycleManager;
import com.apptentive.android.sdk.module.messagecenter.model.CompoundMessage;
import com.apptentive.android.sdk.module.metric.MetricModule;
import com.apptentive.android.sdk.module.rating.IRatingProvider;
import com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener;
import com.apptentive.android.sdk.storage.*;
import com.apptentive.android.sdk.util.Constants;
import com.apptentive.android.sdk.util.Util;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
/**
* This class contains the complete API for accessing Apptentive features from within your app.
*
* @author Sky Kelsey
*/
public class Apptentive {
private Apptentive() {
}
// DELEGATE METHODS
/**
* A reference count of the number of Activities that are started. If the count drops to zero, then no Activities are currently running.
* Any threads or receivers that are spawned by Apptentive should exit or stop listening when runningActivities == 0.
*/
private static int runningActivities;
/**
* Call this method from each of your Activities' onStart() methods. Must be called before using other Apptentive APIs
* methods
*
* @param activity The Activity from which this method is called.
*/
public static void onStart(Activity activity) {
try {
init(activity);
ActivityLifecycleManager.activityStarted(activity);
if (runningActivities == 0) {
PayloadSendWorker.appWentToForeground(activity.getApplicationContext());
MessagePollingWorker.appWentToForeground(activity.getApplicationContext());
}
runningActivities++;
MessageManager.setCurrentForgroundActivity(activity);
} catch (Exception e) {
Log.w("Error starting Apptentive Activity.", e);
MetricModule.sendError(activity.getApplicationContext(), e, null, null);
}
}
/**
* Call this method from each of your Activities' onStop() methods.
*
* @param activity The Activity from which this method is called.
*/
public static void onStop(Activity activity) {
try {
ActivityLifecycleManager.activityStopped(activity);
runningActivities
if (runningActivities < 0) {
Log.e("Incorrect number of running Activities encountered. Resetting to 0. Did you make sure to call Apptentive.onStart() and Apptentive.onStop() in all your Activities?");
runningActivities = 0;
}
// If there are no running activities, wake the thread so it can stop immediately and gracefully.
if (runningActivities == 0) {
PayloadSendWorker.appWentToBackground();
MessagePollingWorker.appWentToBackground();
}
MessageManager.setCurrentForgroundActivity(null);
} catch (Exception e) {
Log.w("Error stopping Apptentive Activity.", e);
MetricModule.sendError(activity.getApplicationContext(), e, null, null);
}
}
// GLOBAL DATA METHODS
/**
* Sets the user's email address. This email address will be sent to the Apptentive server to allow out of app
* communication, and to help provide more context about this user. This email will be the definitive email address
* for this user, unless one is provided directly by the user through an Apptentive UI. Calls to this method are
* idempotent. Calls to this method will overwrite any previously entered email, so if you don't want to overwrite
* the email provided by the user, make sure to check the value with {@link #getPersonEmail(Context)} before you call this method.
*
* @param context The Context from which this method is called.
* @param email The user's email address.
*/
public static void setPersonEmail(Context context, String email) {
PersonManager.storePersonEmail(context, email);
}
/**
* Retrieves the user's email address. This address may be set via {@link #setPersonEmail(Context, String)},
* or by the user through Message Center.
*
* @param context The Context from which this method is called.
* @return The person's email if set, else null.
*/
public static String getPersonEmail(Context context) {
return PersonManager.loadPersonEmail(context);
}
/**
* Sets the user's name. This name will be sent to the Apptentive server and displayed in conversations you have
* with this person. This name will be the definitive username for this user, unless one is provided directly by the
* user through an Apptentive UI. Calls to this method are idempotent. Calls to this method will overwrite any
* previously entered email, so if you don't want to overwrite the email provided by the user, make sure to check
* the value with {@link #getPersonName(Context)} before you call this method.
*
* @param context The context from which this method is called.
* @param name The user's name.
*/
public static void setPersonName(Context context, String name) {
PersonManager.storePersonName(context, name);
}
/**
* Retrieves the user's name. This name may be set via {@link #setPersonName(Context, String)},
* or by the user through Message Center.
*
* @param context The Context from which this method is called.
* @return The person's name if set, else null.
*/
public static String getPersonName(Context context) {
return PersonManager.loadPersonName(context);
}
/**
* <p>Allows you to pass arbitrary string data to the server along with this device's info. This method will replace all
* custom device data that you have set for this app. Calls to this method are idempotent.</p>
* <p>To add a single piece of custom device data, use {@link #addCustomDeviceData}</p>
* <p>To remove a single piece of custom device data, use {@link #removeCustomDeviceData}</p>
*
* @param context The context from which this method is called.
* @param customDeviceData A Map of key/value pairs to send to the server.
* @deprecated
*/
public static void setCustomDeviceData(Context context, Map<String, String> customDeviceData) {
try {
CustomData customData = new CustomData();
for (String key : customDeviceData.keySet()) {
customData.put(key, customDeviceData.get(key));
}
DeviceManager.storeCustomDeviceData(context, customData);
} catch (JSONException e) {
Log.w("Unable to set custom device data.", e);
}
}
/**
* Add a custom data String to the Device. Custom data will be sent to the server, is displayed
* in the Conversation view, and can be used in Interaction targeting. Calls to this method are
* idempotent.
*
* @param context The context from which this method is called.
* @param key The key to store the data under.
* @param value A String value.
*/
public static void addCustomDeviceData(Context context, String key, String value) {
if (value != null) {
value = value.trim();
}
ApptentiveInternal.addCustomDeviceData(context, key, value);
}
/**
* Add a custom data Number to the Device. Custom data will be sent to the server, is displayed
* in the Conversation view, and can be used in Interaction targeting. Calls to this method are
* idempotent.
*
* @param context The context from which this method is called.
* @param key The key to store the data under.
* @param value A Number value.
*/
public static void addCustomDeviceData(Context context, String key, Number value) {
ApptentiveInternal.addCustomDeviceData(context, key, value);
}
/**
* Add a custom data Boolean to the Device. Custom data will be sent to the server, is displayed
* in the Conversation view, and can be used in Interaction targeting. Calls to this method are
* idempotent.
*
* @param context The context from which this method is called.
* @param key The key to store the data under.
* @param value A Boolean value.
*/
public static void addCustomDeviceData(Context context, String key, Boolean value) {
ApptentiveInternal.addCustomDeviceData(context, key, value);
}
private static void addCustomDeviceData(Context context, String key, Version version) {
ApptentiveInternal.addCustomDeviceData(context, key, version);
}
private static void addCustomDeviceData(Context context, String key, DateTime dateTime) {
ApptentiveInternal.addCustomDeviceData(context, key, dateTime);
}
/**
* Remove a piece of custom data from the device. Calls to this method are idempotent.
*
* @param context The context from which this method is called.
* @param key The key to remove.
*/
public static void removeCustomDeviceData(Context context, String key) {
CustomData customData = DeviceManager.loadCustomDeviceData(context);
if (customData != null) {
customData.remove(key);
DeviceManager.storeCustomDeviceData(context, customData);
}
}
/**
* <p>Allows you to pass arbitrary string data to the server along with this person's info. This method will replace all
* custom person data that you have set for this app. Calls to this method are idempotent.</p>
* <p>To add a single piece of custom person data, use {@link #addCustomPersonData}</p>
* <p>To remove a single piece of custom person data, use {@link #removeCustomPersonData}</p>
*
* @param context The context from which this method is called.
* @param customPersonData A Map of key/value pairs to send to the server.
* @deprecated
*/
public static void setCustomPersonData(Context context, Map<String, String> customPersonData) {
Log.w("Setting custom person data: %s", customPersonData.toString());
try {
CustomData customData = new CustomData();
for (String key : customPersonData.keySet()) {
customData.put(key, customPersonData.get(key));
}
PersonManager.storeCustomPersonData(context, customData);
} catch (JSONException e) {
Log.e("Unable to set custom person data.", e);
}
}
/**
* Add a custom data String to the Person. Custom data will be sent to the server, is displayed
* in the Conversation view, and can be used in Interaction targeting. Calls to this method are
* idempotent.
*
* @param context The context from which this method is called.
* @param key The key to store the data under.
* @param value A String value.
*/
public static void addCustomPersonData(Context context, String key, String value) {
if (value != null) {
value = value.trim();
}
ApptentiveInternal.addCustomPersonData(context, key, value);
}
/**
* Add a custom data Number to the Person. Custom data will be sent to the server, is displayed
* in the Conversation view, and can be used in Interaction targeting. Calls to this method are
* idempotent.
*
* @param context The context from which this method is called.
* @param key The key to store the data under.
* @param value A Number value.
*/
public static void addCustomPersonData(Context context, String key, Number value) {
ApptentiveInternal.addCustomPersonData(context, key, value);
}
/**
* Add a custom data Boolean to the Person. Custom data will be sent to the server, is displayed
* in the Conversation view, and can be used in Interaction targeting. Calls to this method are
* idempotent.
*
* @param context The context from which this method is called.
* @param key The key to store the data under.
* @param value A Boolean value.
*/
public static void addCustomPersonData(Context context, String key, Boolean value) {
ApptentiveInternal.addCustomPersonData(context, key, value);
}
private static void addCustomPersonData(Context context, String key, Version version) {
ApptentiveInternal.addCustomPersonData(context, key, version);
}
private static void addCustomPersonData(Context context, String key, DateTime dateTime) {
ApptentiveInternal.addCustomPersonData(context, key, dateTime);
}
/**
* Remove a piece of custom data from the Person. Calls to this method are idempotent.
*
* @param context The context from which this method is called.
* @param key The key to remove.
*/
public static void removeCustomPersonData(Context context, String key) {
CustomData customData = PersonManager.loadCustomPersonData(context);
if (customData != null) {
customData.remove(key);
PersonManager.storeCustomPersonData(context, customData);
}
}
// THIRD PARTY INTEGRATIONS
private static final String INTEGRATION_APPTENTIVE_PUSH = "apptentive_push";
private static final String INTEGRATION_PARSE = "parse";
private static final String INTEGRATION_URBAN_AIRSHIP = "urban_airship";
private static final String INTEGRATION_AWS_SNS = "aws_sns";
private static final String INTEGRATION_PUSH_TOKEN = "token";
private static void addIntegration(Context context, String integration, Map<String, String> config) {
if (integration == null || config == null) {
return;
}
CustomData integrationConfig = DeviceManager.loadIntegrationConfig(context);
try {
JSONObject configJson = null;
if (!integrationConfig.isNull(integration)) {
configJson = integrationConfig.getJSONObject(integration);
} else {
configJson = new JSONObject();
integrationConfig.put(integration, configJson);
}
for (String key : config.keySet()) {
configJson.put(key, config.get(key));
}
Log.d("Adding integration config: %s", config.toString());
DeviceManager.storeIntegrationConfig(context, integrationConfig);
syncDevice(context);
} catch (JSONException e) {
Log.e("Error adding integration: %s, %s", e, integration, config.toString());
}
}
/**
* Call {@link #setPushNotificationIntegration(Context, int, String)} with this value to allow Apptentive to send pushes
* to this device without a third party push provider. Requires a valid GCM configuration.
*/
public static final int PUSH_PROVIDER_APPTENTIVE = 0;
/**
* Call {@link #setPushNotificationIntegration(Context, int, String)} with this value to allow Apptentive to send pushes
* to this device through your existing Parse Push integration. Requires a valid Parse integration.
*/
public static final int PUSH_PROVIDER_PARSE = 1;
/**
* Call {@link #setPushNotificationIntegration(Context, int, String)} with this value to allow Apptentive to send pushes
* to this device through your existing Urban Airship Push integration. Requires a valid Urban
* Airship Push integration.
*/
public static final int PUSH_PROVIDER_URBAN_AIRSHIP = 2;
/**
* Call {@link #setPushNotificationIntegration(Context, int, String)} with this value to allow Apptentive to send pushes
* to this device through your existing Amazon AWS SNS integration. Requires a valid Amazon AWS SNS
* integration.
*/
public static final int PUSH_PROVIDER_AMAZON_AWS_SNS = 3;
public static void setPushNotificationIntegration(Context context, int pushProvider, String token) {
try {
CustomData integrationConfig = getIntegrationConfigurationWithoutPushProviders(context);
JSONObject pushObject = new JSONObject();
pushObject.put(INTEGRATION_PUSH_TOKEN, token);
switch (pushProvider) {
case PUSH_PROVIDER_APPTENTIVE:
integrationConfig.put(INTEGRATION_APPTENTIVE_PUSH, pushObject);
break;
case PUSH_PROVIDER_PARSE:
integrationConfig.put(INTEGRATION_PARSE, pushObject);
break;
case PUSH_PROVIDER_URBAN_AIRSHIP:
integrationConfig.put(INTEGRATION_URBAN_AIRSHIP, pushObject);
break;
case PUSH_PROVIDER_AMAZON_AWS_SNS:
integrationConfig.put(INTEGRATION_AWS_SNS, pushObject);
break;
default:
Log.e("Invalid pushProvider: %d", pushProvider);
return;
}
DeviceManager.storeIntegrationConfig(context, integrationConfig);
syncDevice(context);
} catch (JSONException e) {
Log.e("Error setting push integration.", e);
return;
}
}
private static CustomData getIntegrationConfigurationWithoutPushProviders(Context context) {
CustomData integrationConfig = DeviceManager.loadIntegrationConfig(context);
if (integrationConfig != null) {
integrationConfig.remove(INTEGRATION_APPTENTIVE_PUSH);
integrationConfig.remove(INTEGRATION_PARSE);
integrationConfig.remove(INTEGRATION_URBAN_AIRSHIP);
integrationConfig.remove(INTEGRATION_AWS_SNS);
}
return integrationConfig;
}
// PUSH NOTIFICATIONS
/**
* Determines whether this Intent is a push notification sent from Apptentive.
*
* @param intent The opened push notification Intent you received in your BroadcastReceiver.
* @return True if the Intent contains Apptentive push information.
*/
public static boolean isApptentivePushNotification(Intent intent) {
return ApptentiveInternal.getApptentivePushNotificationData(intent) != null;
}
/**
* Determines whether this Bundle came from an Apptentive push notification. This method is used with Urban Airship
* integrations.
*
* @param bundle The Extra data from an opened push notification.
* @return True if the Intent contains Apptentive push information.
*/
public static boolean isApptentivePushNotification(Bundle bundle) {
return ApptentiveInternal.getApptentivePushNotificationData(bundle) != null;
}
/**
* <p>Saves Apptentive specific data from a push notification Intent. In your BroadcastReceiver, if the push notification
* came from Apptentive, it will have data that needs to be saved before you launch your Activity. You must call this
* method <strong>every time</strong> you get a push opened Intent, and before you launch your Activity. If the push
* notification did not come from Apptentive, this method has no effect.</p>
* <p>Use this method when using Parse and Amazon SNS as push providers.</p>
*
* @param context The Context from which this method is called.
* @param intent The Intent that you received when the user opened a push notification.
* @return true if the push data came from Apptentive.
*/
public static boolean setPendingPushNotification(Context context, Intent intent) {
String apptentive = ApptentiveInternal.getApptentivePushNotificationData(intent);
if (apptentive != null) {
return ApptentiveInternal.setPendingPushNotification(context, apptentive);
}
return false;
}
/**
* Saves off the data contained in a push notification sent to this device from Apptentive. Use
* this method when a push notification is opened, and you only have access to a push data
* Bundle containing an "apptentive" key. This will generally be used with direct Apptentive Push
* notifications, or when using Urban Airship as a push provider. Calling this method for a push
* that did not come from Apptentive has no effect.
*
* @param context The context from which this method was called.
* @param data A Bundle containing the GCM data object from the push notification.
* @return true if the push data came from Apptentive.
*/
public static boolean setPendingPushNotification(Context context, Bundle data) {
String apptentive = ApptentiveInternal.getApptentivePushNotificationData(data);
if (apptentive != null) {
return ApptentiveInternal.setPendingPushNotification(context, apptentive);
}
return false;
}
/**
* Launches Apptentive features based on a push notification Intent. Before you call this, you
* must call {@link #setPendingPushNotification(Context, Intent)} or
* {@link #setPendingPushNotification(Context, Bundle)} in your Broadcast receiver when
* a push notification is opened by the user. This method must be called from the Activity that
* you launched from the BroadcastReceiver. This method will only handle Apptentive originated
* push notifications, so you can and should call it any time your push notification launches an
* Activity.
*
* @param activity The Activity from which this method is called.
* @return True if a call to this method resulted in Apptentive displaying a View.
*/
public static boolean handleOpenedPushNotification(Activity activity) {
SharedPreferences prefs = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
String pushData = prefs.getString(Constants.PREF_KEY_PENDING_PUSH_NOTIFICATION, null);
prefs.edit().remove(Constants.PREF_KEY_PENDING_PUSH_NOTIFICATION).apply(); // Remove our data so this won't run twice.
if (pushData != null) {
Log.i("Handling opened Apptentive push notification.");
try {
JSONObject pushJson = new JSONObject(pushData);
ApptentiveInternal.PushAction action = ApptentiveInternal.PushAction.unknown;
if (pushJson.has(ApptentiveInternal.PUSH_ACTION)) {
action = ApptentiveInternal.PushAction.parse(pushJson.getString(ApptentiveInternal.PUSH_ACTION));
}
switch (action) {
case pmc:
Apptentive.showMessageCenter(activity);
return true;
default:
Log.v("Unknown Apptentive push notification action: \"%s\"", action.name());
}
} catch (JSONException e) {
Log.w("Error parsing JSON from push notification.", e);
MetricModule.sendError(activity.getApplicationContext(), e, "Parsing Push notification", pushData);
}
}
return false;
}
// RATINGS
/**
* Use this to choose where to send the user when they are prompted to rate the app. This should be the same place
* that the app was downloaded from.
*
* @param ratingProvider A {@link IRatingProvider} value.
*/
public static void setRatingProvider(IRatingProvider ratingProvider) {
ApptentiveInternal.setRatingProvider(ratingProvider);
}
/**
* If there are any properties that your {@link IRatingProvider} implementation requires, populate them here. This
* is not currently needed with the Google Play and Amazon Appstore IRatingProviders.
*
* @param key A String
* @param value A String
*/
public static void putRatingProviderArg(String key, String value) {
ApptentiveInternal.putRatingProviderArg(key, value);
}
// MESSAGE CENTER
/**
* Opens the Apptentive Message Center UI Activity
*
* @param activity The Activity from which to launch the Message Center
* @return true if Message Center was shown, else false.
*/
public static boolean showMessageCenter(Activity activity) {
return showMessageCenter(activity, null);
}
/**
* Opens the Apptentive Message Center UI Activity, and allows custom data to be sent with the next message the user
* sends. If the user sends multiple messages, this data will only be sent with the first message sent after this
* method is invoked. Additional invocations of this method with custom data will repeat this process.
*
* @param activity The Activity from which to launch the Message Center
* @param customData A Map of String keys to Object values. Objects may be Strings, Numbers, or Booleans.
* If any message is sent by the Person, this data is sent with it, and then
* cleared. If no message is sent, this data is discarded.
* @return true if Message Center was shown, else false.
*/
public static boolean showMessageCenter(Activity activity, Map<String, Object> customData) {
try {
return ApptentiveInternal.showMessageCenterInternal(activity, customData);
} catch (Exception e) {
Log.w("Error starting Apptentive Activity.", e);
MetricModule.sendError(activity.getApplicationContext(), e, null, null);
}
return false;
}
/**
* Our SDK must connect to our server at least once to download initial configuration for Message
* Center. Call this method to see whether or not Message Center can be displayed.
*
* @param context The context from which this method is called.
* @return true if a call to {@link #showMessageCenter(Activity)} will display Message Center, else false.
*/
public static boolean canShowMessageCenter(Context context) {
return ApptentiveInternal.canShowMessageCenterInternal(context);
}
/**
* Set a listener to be notified when the number of unread messages in the Message Center changes.
*
* @param listener An UnreadMessageListener that you instantiate.
* @deprecated use {@link #addUnreadMessagesListener(UnreadMessagesListener)} instead.
*/
@Deprecated
public static void setUnreadMessagesListener(UnreadMessagesListener listener) {
MessageManager.setHostUnreadMessagesListener(listener);
}
/**
* Add a listener to be notified when the number of unread messages in the Message Center changes.
*
* @param listener An UnreadMessageListener that you instantiate. Do not pass in an anonymous class.
* Instead, create your listener as an instance variable and pass that in. This
* allows us to keep a weak reference to avoid memory leaks.
*/
public static void addUnreadMessagesListener(UnreadMessagesListener listener) {
MessageManager.addHostUnreadMessagesListener(listener);
}
/**
* Returns the number of unread messages in the Message Center.
*
* @param context The Context from which this method is called.
* @return The number of unread messages.
*/
public static int getUnreadMessageCount(Context context) {
try {
return MessageManager.getUnreadMessageCount(context);
} catch (Exception e) {
MetricModule.sendError(context.getApplicationContext(), e, null, null);
}
return 0;
}
/**
* Sends a text message to the server. This message will be visible in the conversation view on the server, but will
* not be shown in the client's Message Center.
*
* @param context The Context from which this method is called.
* @param text The message you wish to send.
*/
public static void sendAttachmentText(Context context, String text) {
try {
CompoundMessage message = new CompoundMessage();
message.setBody(text);
message.setRead(true);
message.setHidden(true);
message.setSenderId(GlobalInfo.getPersonId(context.getApplicationContext()));
message.setAssociatedFiles(context, null);
MessageManager.sendMessage(context.getApplicationContext(), message);
} catch (Exception e) {
Log.w("Error sending attachment text.", e);
MetricModule.sendError(context, e, null, null);
}
}
/**
* Sends a file to the server. This file will be visible in the conversation view on the server, but will not be shown
* in the client's Message Center. A local copy of this file will be made until the message is transmitted, at which
* point the temporary file will be deleted.
*
* @param context The Context from which this method was called.
* @param uri The URI of the local resource file.
*/
public static void sendAttachmentFile(Context context, String uri) {
try {
if (TextUtils.isEmpty(uri)) {
return;
}
CompoundMessage message = new CompoundMessage();
// No body, just attachment
message.setBody(null);
message.setRead(true);
message.setHidden(true);
message.setSenderId(GlobalInfo.getPersonId(context.getApplicationContext()));
ArrayList<StoredFile> attachmentStoredFiles = new ArrayList<StoredFile>();
/* Make a local copy in the cache dir. By default the file name is "apptentive-api-file + nonce"
* If original uri is known, the name will be taken from the original uri
*/
String localFilePath = Util.generateCacheFilePathFromNonceOrPrefix(context, message.getNonce(), Uri.parse(uri).getLastPathSegment());
String mimeType = Util.getMimeTypeFromUri(context, Uri.parse(uri));
MimeTypeMap mime = MimeTypeMap.getSingleton();
String extension = mime.getExtensionFromMimeType(mimeType);
// If we can't get the mime type from the uri, try getting it from the extension.
if (extension == null) {
extension = MimeTypeMap.getFileExtensionFromUrl(uri);
}
if (mimeType == null && extension != null) {
mimeType = mime.getMimeTypeFromExtension(extension);
}
if (!TextUtils.isEmpty(extension)) {
localFilePath += "." + extension;
}
StoredFile storedFile = Util.createLocalStoredFile(context, uri, localFilePath, mimeType);
if (storedFile == null) {
return;
}
storedFile.setId(message.getNonce());
attachmentStoredFiles.add(storedFile);
message.setAssociatedFiles(context, attachmentStoredFiles);
MessageManager.sendMessage(context.getApplicationContext(), message);
} catch (Exception e) {
Log.w("Error sending attachment file.", e);
MetricModule.sendError(context, e, null, null);
}
}
/**
* Sends a file to the server. This file will be visible in the conversation view on the server, but will not be shown
* in the client's Message Center. A local copy of this file will be made until the message is transmitted, at which
* point the temporary file will be deleted.
*
* @param context The Context from which this method was called.
* @param content A byte array of the file contents.
* @param mimeType The mime type of the file.
*/
public static void sendAttachmentFile(Context context, byte[] content, String mimeType) {
ByteArrayInputStream is = null;
try {
is = new ByteArrayInputStream(content);
sendAttachmentFile(context, is, mimeType);
} finally {
Util.ensureClosed(is);
}
}
/**
* Sends a file to the server. This file will be visible in the conversation view on the server, but will not be shown
* in the client's Message Center. A local copy of this file will be made until the message is transmitted, at which
* point the temporary file will be deleted.
*
* @param context The Context from which this method was called.
* @param is An InputStream from the desired file.
* @param mimeType The mime type of the file.
*/
public static void sendAttachmentFile(Context context, InputStream is, String mimeType) {
try {
if (is == null) {
return;
}
CompoundMessage message = new CompoundMessage();
// No body, just attachment
message.setBody(null);
message.setRead(true);
message.setHidden(true);
message.setSenderId(GlobalInfo.getPersonId(context.getApplicationContext()));
ArrayList<StoredFile> attachmentStoredFiles = new ArrayList<StoredFile>();
String localFilePath = Util.generateCacheFilePathFromNonceOrPrefix(context, message.getNonce(), null);
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
if (!TextUtils.isEmpty(extension)) {
localFilePath += "." + extension;
}
// When created from InputStream, there is no source file uri or path, thus just use the cache file path
StoredFile storedFile = Util.createLocalStoredFile(is, localFilePath, localFilePath, mimeType);
if (storedFile == null) {
return;
}
storedFile.setId(message.getNonce());
attachmentStoredFiles.add(storedFile);
message.setAssociatedFiles(context, attachmentStoredFiles);
MessageManager.sendMessage(context.getApplicationContext(), message);
} catch (Exception e) {
Log.w("Error sending attachment file.", e);
MetricModule.sendError(context, e, null, null);
}
}
/**
* This method takes a unique event string, stores a record of that event having been visited, figures out
* if there is an interaction that is able to run for this event, and then runs it. If more than one interaction
* can run, then the most appropriate interaction takes precedence. Only one interaction at most will run per
* invocation of this method.
*
* @param activity The Activity from which this method is called.
* @param event A unique String representing the line this method is called on. For instance, you may want to have
* the ability to target interactions to run after the user uploads a file in your app. You may then
* call <strong><code>engage(activity, "finished_upload");</code></strong>
* @return true if the an interaction was shown, else false.
*/
public static synchronized boolean engage(Activity activity, String event) {
return EngagementModule.engage(activity, "local", "app", null, event, null, null, (ExtendedData[]) null);
}
/**
* This method takes a unique event string, stores a record of that event having been visited, figures out
* if there is an interaction that is able to run for this event, and then runs it. If more than one interaction
* can run, then the most appropriate interaction takes precedence. Only one interaction at most will run per
* invocation of this method.
*
* @param activity The Activity from which this method is called.
* @param event A unique String representing the line this method is called on. For instance, you may want to have
* the ability to target interactions to run after the user uploads a file in your app. You may then
* call <strong><code>engage(activity, "finished_upload");</code></strong>
* @param customData A Map of String keys to Object values. Objects may be Strings, Numbers, or Booleans. This data
* is sent to the server for tracking information in the context of the engaged Event.
* @return true if the an interaction was shown, else false.
*/
public static synchronized boolean engage(Activity activity, String event, Map<String, Object> customData) {
return EngagementModule.engage(activity, "local", "app", null, event, null, customData, (ExtendedData[]) null);
}
/**
* This method takes a unique event string, stores a record of that event having been visited, figures out
* if there is an interaction that is able to run for this event, and then runs it. If more than one interaction
* can run, then the most appropriate interaction takes precedence. Only one interaction at most will run per
* invocation of this method.
*
* @param activity The Activity from which this method is called.
* @param event A unique String representing the line this method is called on. For instance, you may want to have
* the ability to target interactions to run after the user uploads a file in your app. You may then
* call <strong><code>engage(activity, "finished_upload");</code></strong>
* @param customData A Map of String keys to Object values. Objects may be Strings, Numbers, or Booleans. This data
* is sent to the server for tracking information in the context of the engaged Event.
* @param extendedData An array of ExtendedData objects. ExtendedData objects used to send structured data that has
* specific meaning to the server. By using an {@link ExtendedData} object instead of arbitrary
* customData, special meaning can be derived. Supported objects include {@link TimeExtendedData},
* {@link LocationExtendedData}, and {@link CommerceExtendedData}. Include each type only once.
* @return true if the an interaction was shown, else false.
*/
public static synchronized boolean engage(Activity activity, String event, Map<String, Object> customData, ExtendedData... extendedData) {
return EngagementModule.engage(activity, "local", "app", null, event, null, customData, extendedData);
}
/**
* @param context The Context from which this method is called.
* @param event A unique String representing the line this method is called on. For instance, you may want to have
* the ability to target interactions to run after the user uploads a file in your app. You may then
* call <strong><code>engage(activity, "finished_upload");</code></strong>
* @return true if an immediate call to engage() with the same event name would result in an Interaction being displayed, otherwise false.
* @deprecated Use {@link #canShowInteraction(Context, String)}() instead. The behavior is identical. Only the name has changed.
*/
public static synchronized boolean willShowInteraction(Context context, String event) {
return canShowInteraction(context, event);
}
/**
* This method can be used to determine if a call to one of the <strong><code>engage()</code></strong> methods such as
* {@link #engage(Activity, String)} using the same event name will
* result in the display of an Interaction. This is useful if you need to know whether an Interaction will be
* displayed before you create a UI Button, etc.
*
* @param context The Context from which this method is called.
* @param event A unique String representing the line this method is called on. For instance, you may want to have
* the ability to target interactions to run after the user uploads a file in your app. You may then
* call <strong><code>engage(activity, "finished_upload");</code></strong>
* @return true if an immediate call to engage() with the same event name would result in an Interaction being displayed, otherwise false.
*/
public static synchronized boolean canShowInteraction(Context context, String event) {
try {
return EngagementModule.canShowInteraction(context, "local", "app", event);
} catch (Exception e) {
MetricModule.sendError(context, e, null, null);
}
return false;
}
/**
* Pass in a listener. The listener will be called whenever a survey is finished.
*
* @param listener The {@link com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener} listener to call when the survey is finished.
*/
public static void setOnSurveyFinishedListener(OnSurveyFinishedListener listener) {
ApptentiveInternal.setOnSurveyFinishedListener(listener);
}
// INTERNAL METHODS
private static void init(Activity activity) {
// First, initialize data relies on synchronous reads from local resources.
final Context appContext = activity.getApplicationContext();
if (!GlobalInfo.initialized) {
SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
// First, Get the api key, and figure out if app is debuggable.
GlobalInfo.isAppDebuggable = false;
String apiKey = prefs.getString(Constants.PREF_KEY_API_KEY, null);
boolean apptentiveDebug = false;
String logLevelOverride = null;
try {
ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), PackageManager.GET_META_DATA);
Bundle metaData = ai.metaData;
if (metaData != null) {
if (apiKey == null) {
apiKey = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY);
Log.d("Saving API key for the first time: %s", apiKey);
prefs.edit().putString(Constants.PREF_KEY_API_KEY, apiKey).apply();
} else {
Log.d("Using cached API Key: %s", apiKey);
}
logLevelOverride = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL);
apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
ApptentiveClient.useStagingServer = metaData.getBoolean(Constants.MANIFEST_KEY_USE_STAGING_SERVER);
}
if (apptentiveDebug) {
Log.i("Apptentive debug logging set to VERBOSE.");
ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
} else if (logLevelOverride != null) {
Log.i("Overriding log level: %s", logLevelOverride);
ApptentiveInternal.setMinimumLogLevel(Log.Level.parse(logLevelOverride));
} else {
GlobalInfo.isAppDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
if (GlobalInfo.isAppDebuggable) {
ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
}
}
} catch (Exception e) {
Log.e("Unexpected error while reading application info.", e);
}
Log.i("Debug mode enabled? %b", GlobalInfo.isAppDebuggable);
// If we are in debug mode, but no api key is found, throw an exception. Otherwise, just assert log. We don't want to crash a production app.
String errorString = "No Apptentive api key specified. Please make sure you have specified your api key in your AndroidManifest.xml";
if ((Util.isEmpty(apiKey))) {
if (GlobalInfo.isAppDebuggable) {
AlertDialog alertDialog = new AlertDialog.Builder(activity)
.setTitle("Error")
.setMessage(errorString)
.setPositiveButton("OK", null)
.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
Log.e(errorString);
}
GlobalInfo.apiKey = apiKey;
Log.i("API Key: %s", GlobalInfo.apiKey);
// Grab app info we need to access later on.
GlobalInfo.appPackage = appContext.getPackageName();
GlobalInfo.androidId = Settings.Secure.getString(appContext.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
// Check the host app version, and notify modules if it's changed.
try {
PackageManager packageManager = appContext.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(appContext.getPackageName(), 0);
Integer currentVersionCode = packageInfo.versionCode;
String currentVersionName = packageInfo.versionName;
VersionHistoryStore.VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore.getLastVersionSeen(appContext);
if (lastVersionEntrySeen == null) {
onVersionChanged(appContext, null, currentVersionCode, null, currentVersionName);
} else {
if (!currentVersionCode.equals(lastVersionEntrySeen.versionCode) || !currentVersionName.equals(lastVersionEntrySeen.versionName)) {
onVersionChanged(appContext, lastVersionEntrySeen.versionCode, currentVersionCode, lastVersionEntrySeen.versionName, currentVersionName);
}
}
GlobalInfo.appDisplayName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0)).toString();
} catch (PackageManager.NameNotFoundException e) {
// Nothing we can do then.
GlobalInfo.appDisplayName = "this app";
}
String lastSeenSdkVersion = prefs.getString(Constants.PREF_KEY_LAST_SEEN_SDK_VERSION, "");
if (!lastSeenSdkVersion.equals(Constants.APPTENTIVE_SDK_VERSION)) {
onSdkVersionChanged(appContext, lastSeenSdkVersion, Constants.APPTENTIVE_SDK_VERSION);
}
GlobalInfo.initialized = true;
Log.v("Done initializing...");
} else {
Log.v("Already initialized...");
}
// Initialize the Conversation Token, or fetch if needed. Fetch config it the token is available.
if (GlobalInfo.getConversationToken(appContext) == null || GlobalInfo.getPersonId(appContext) == null) {
asyncFetchConversationToken(appContext);
} else {
asyncFetchAppConfiguration(appContext);
InteractionManager.asyncFetchAndStoreInteractions(appContext);
}
// TODO: Do this on a dedicated thread if it takes too long. Some devices are slow to read device data.
syncDevice(appContext);
syncSdk(appContext);
syncPerson(appContext);
Log.d("Default Locale: %s", Locale.getDefault().toString());
Log.d("Conversation id: %s", appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE).getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
}
private static void onVersionChanged(Context context, Integer previousVersionCode, Integer currentVersionCode, String previousVersionName, String currentVersionName) {
Log.i("Version changed: Name: %s => %s, Code: %d => %d", previousVersionName, currentVersionName, previousVersionCode, currentVersionCode);
VersionHistoryStore.updateVersionHistory(context, currentVersionCode, currentVersionName);
AppRelease appRelease = AppReleaseManager.storeAppReleaseAndReturnDiff(context);
if (appRelease != null) {
Log.d("App release was updated.");
ApptentiveDatabase.getInstance(context).addPayload(appRelease);
}
invalidateCaches(context);
}
private static void onSdkVersionChanged(Context context, String previousSdkVersion, String currentSdkVersion) {
Log.i("Sdk version changed: %s => %s", previousSdkVersion, currentSdkVersion);
context.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE).edit().putString(Constants.PREF_KEY_LAST_SEEN_SDK_VERSION, currentSdkVersion).apply();
invalidateCaches(context);
}
/**
* We want to make sure the app is using the latest configuration from the server if the app or sdk version changes.
*
* @param context
*/
private static void invalidateCaches(Context context) {
InteractionManager.updateCacheExpiration(context, 0);
Configuration config = Configuration.load(context);
config.setConfigurationCacheExpirationMillis(System.currentTimeMillis());
config.save(context);
}
private synchronized static void asyncFetchConversationToken(final Context context) {
Thread thread = new Thread() {
@Override
public void run() {
fetchConversationToken(context);
}
};
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Log.w("Caught UncaughtException in thread \"%s\"", throwable, thread.getName());
MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
}
};
thread.setUncaughtExceptionHandler(handler);
thread.setName("Apptentive-FetchConversationToken");
thread.start();
}
/**
* First looks to see if we've saved the ConversationToken in memory, then in SharedPreferences, and finally tries to get one
* from the server.
*/
private static void fetchConversationToken(Context context) {
// Try to fetch a new one from the server.
ConversationTokenRequest request = new ConversationTokenRequest();
// Send the Device and Sdk now, so they are available on the server from the start.
request.setDevice(DeviceManager.storeDeviceAndReturnIt(context));
request.setSdk(SdkManager.storeSdkAndReturnIt(context));
request.setPerson(PersonManager.storePersonAndReturnIt(context));
// TODO: Allow host app to send a user id, if available.
ApptentiveHttpResponse response = ApptentiveClient.getConversationToken(context, request);
if (response == null) {
Log.w("Got null response fetching ConversationToken.");
return;
}
if (response.isSuccessful()) {
try {
JSONObject root = new JSONObject(response.getContent());
String conversationToken = root.getString("token");
Log.d("ConversationToken: " + conversationToken);
String conversationId = root.getString("id");
Log.d("New Conversation id: %s", conversationId);
if (conversationToken != null && !conversationToken.equals("")) {
GlobalInfo.setConversationToken(context, conversationToken);
GlobalInfo.setConversationId(context, conversationId);
}
String personId = root.getString("person_id");
Log.d("PersonId: " + personId);
if (personId != null && !personId.equals("")) {
GlobalInfo.setPersonId(context, personId);
}
// Try to fetch app configuration, since it depends on the conversation token.
asyncFetchAppConfiguration(context);
InteractionManager.asyncFetchAndStoreInteractions(context);
} catch (JSONException e) {
Log.e("Error parsing ConversationToken response json.", e);
}
}
}
/**
* Fetches the global app configuration from the server and stores the keys into our SharedPreferences.
*/
private static void fetchAppConfiguration(Context context) {
boolean force = GlobalInfo.isAppDebuggable;
// Don't get the app configuration unless forced, or the cache has expired.
if (force || Configuration.load(context).hasConfigurationCacheExpired()) {
Log.i("Fetching new Configuration.");
ApptentiveHttpResponse response = ApptentiveClient.getAppConfiguration(context);
try {
Map<String, String> headers = response.getHeaders();
if (headers != null) {
String cacheControl = headers.get("Cache-Control");
Integer cacheSeconds = Util.parseCacheControlHeader(cacheControl);
if (cacheSeconds == null) {
cacheSeconds = Constants.CONFIG_DEFAULT_APP_CONFIG_EXPIRATION_DURATION_SECONDS;
}
Log.d("Caching configuration for %d seconds.", cacheSeconds);
Configuration config = new Configuration(response.getContent());
config.setConfigurationCacheExpirationMillis(System.currentTimeMillis() + cacheSeconds * 1000);
config.save(context);
}
} catch (JSONException e) {
Log.e("Error parsing app configuration from server.", e);
}
} else {
Log.v("Using cached Configuration.");
}
}
private static void asyncFetchAppConfiguration(final Context context) {
Thread thread = new Thread() {
public void run() {
fetchAppConfiguration(context);
}
};
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Log.e("Caught UncaughtException in thread \"%s\"", throwable, thread.getName());
MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
}
};
thread.setUncaughtExceptionHandler(handler);
thread.setName("Apptentive-FetchAppConfiguration");
thread.start();
}
/**
* Sends current Device to the server if it differs from the last time it was sent.
*
* @param context
*/
private static void syncDevice(Context context) {
Device deviceInfo = DeviceManager.storeDeviceAndReturnDiff(context);
if (deviceInfo != null) {
Log.d("Device info was updated.");
Log.v(deviceInfo.toString());
ApptentiveDatabase.getInstance(context).addPayload(deviceInfo);
} else {
Log.d("Device info was not updated.");
}
}
/**
* Sends current Sdk to the server if it differs from the last time it was sent.
*
* @param context
*/
private static void syncSdk(Context context) {
Sdk sdk = SdkManager.storeSdkAndReturnDiff(context);
if (sdk != null) {
Log.d("Sdk was updated.");
Log.v(sdk.toString());
ApptentiveDatabase.getInstance(context).addPayload(sdk);
} else {
Log.d("Sdk was not updated.");
}
}
/**
* Sends current Person to the server if it differs from the last time it was sent.
*
* @param context
*/
private static void syncPerson(Context context) {
Person person = PersonManager.storePersonAndReturnDiff(context);
if (person != null) {
Log.d("Person was updated.");
Log.v(person.toString());
ApptentiveDatabase.getInstance(context).addPayload(person);
} else {
Log.d("Person was not updated.");
}
}
public static class Version extends JSONObject implements Comparable<Version> {
public static final String KEY_TYPE = "_type";
public static final String TYPE = "version";
public Version() {
}
public Version(String json) throws JSONException {
super(json);
}
public Version(long version) {
super();
setVersion(version);
}
public void setVersion(String version) {
try {
put(KEY_TYPE, TYPE);
put(TYPE, version);
} catch (JSONException e) {
Log.e("Error creating Apptentive.Version.", e);
}
}
public void setVersion(long version) {
setVersion(Long.toString(version));
}
public String getVersion() {
return optString(TYPE, null);
}
@Override
public int compareTo(Version other) {
String thisVersion = getVersion();
String thatVersion = other.getVersion();
String[] thisArray = thisVersion.split("\\.");
String[] thatArray = thatVersion.split("\\.");
int maxParts = Math.max(thisArray.length, thatArray.length);
for (int i = 0; i < maxParts; i++) {
// If one SemVer has more parts than another, treat pad out the short one with zeros in each slot.
long left = 0;
if (thisArray.length > i) {
left = Long.parseLong(thisArray[i]);
}
long right = 0;
if (thatArray.length > i) {
right = Long.parseLong(thatArray[i]);
}
if (left < right) {
return -1;
} else if (left > right) {
return 1;
}
}
return 0;
}
@Override
public String toString() {
return getVersion();
}
}
public static class DateTime extends JSONObject implements Comparable<DateTime> {
public static final String KEY_TYPE = "_type";
public static final String TYPE = "datetime";
public static final String SEC = "sec";
public DateTime(String json) throws JSONException {
super(json);
}
public DateTime(double dateTime) {
super();
setDateTime(dateTime);
}
public void setDateTime(double dateTime) {
try {
put(KEY_TYPE, TYPE);
put(SEC, dateTime);
} catch (JSONException e) {
Log.e("Error creating Apptentive.DateTime.", e);
}
}
public double getDateTime() {
return optDouble(SEC);
}
@Override
public String toString() {
return Double.toString(getDateTime());
}
@Override
public int compareTo(DateTime other) {
double thisDateTime = getDateTime();
double thatDateTime = other.getDateTime();
return Double.compare(thisDateTime, thatDateTime);
}
}
}
|
package org.jgroups.tests;
import junit.framework.TestCase;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.debug.Simulator;
import org.jgroups.protocols.BARRIER;
import org.jgroups.protocols.PING;
import org.jgroups.protocols.VIEW_SYNC;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Util;
import java.util.Vector;
/**
* Tests the BARRIER protocol
* @author Bela Ban
* @version $Id: BARRIERTest.java,v 1.2 2008/02/28 13:28:12 belaban Exp $
*/
public class BARRIERTest extends TestCase {
IpAddress a1;
Vector<Address> members;
View v;
Simulator s;
BARRIER barrier_prot=new BARRIER();
PING bottom_prot;
public BARRIERTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
a1=new IpAddress(1111);
members=new Vector<Address>();
members.add(a1);
v=new View(a1, 1, members);
s=new Simulator();
s.setLocalAddress(a1);
s.setView(v);
s.addMember(a1);
bottom_prot=new PING();
Protocol[] stack=new Protocol[]{new VIEW_SYNC(), barrier_prot, bottom_prot};
s.setProtocolStack(stack);
s.start();
}
public void tearDown() throws Exception {
super.tearDown();
s.stop();
}
public void testBlocking() {
assertFalse(barrier_prot.isClosed());
s.send(new Event(Event.CLOSE_BARRIER));
assertTrue(barrier_prot.isClosed());
s.send(new Event(Event.OPEN_BARRIER));
assertFalse(barrier_prot.isClosed());
}
public void testThreadsBlockedOnBarrier() {
MyReceiver receiver=new MyReceiver();
s.setReceiver(receiver);
s.send(new Event(Event.CLOSE_BARRIER));
for(int i=0; i < 5; i++) {
new Thread() {
public void run() {
bottom_prot.up(new Event(Event.MSG, new Message(null, null, null)));
}
}.start();
}
Util.sleep(500);
int num_in_flight_threads=barrier_prot.getNumberOfInFlightThreads();
assertEquals(0, num_in_flight_threads);
s.send(new Event(Event.OPEN_BARRIER));
Util.sleep(500);
num_in_flight_threads=barrier_prot.getNumberOfInFlightThreads();
assertEquals(0, num_in_flight_threads);
assertEquals(5, receiver.getNumberOfReceivedMessages());
}
public void testThreadsBlockedOnMutex() throws InterruptedException {
BlockingReceiver receiver=new BlockingReceiver();
s.setReceiver(receiver);
Thread thread=new Thread() {
public void run() {bottom_prot.up(new Event(Event.MSG, new Message()));}
};
Thread thread2=new Thread() {
public void run() {bottom_prot.up(new Event(Event.MSG, new Message()));}
};
thread.start();
thread2.start();
thread.join();
thread2.join();
}
static class MyReceiver implements Simulator.Receiver {
int num_mgs_received=0;
public void receive(Event evt) {
if(evt.getType() == Event.MSG) {
num_mgs_received++;
if(num_mgs_received % 1000 == 0)
System.out.println("<== " + num_mgs_received);
}
}
public int getNumberOfReceivedMessages() {
return num_mgs_received;
}
}
class BlockingReceiver implements Simulator.Receiver {
public void receive(Event evt) {
System.out.println("Thread " + Thread.currentThread().getId() + " receive() called - about to enter mutex");
synchronized(this) {
System.out.println("Thread " + Thread.currentThread().getId() + " entered mutex");
Util.sleep(2000);
System.out.println("Thread " + Thread.currentThread().getId() + " closing barrier");
s.send(new Event(Event.CLOSE_BARRIER));
System.out.println("Thread " + Thread.currentThread().getId() + " closed barrier");
}
}
}
}
|
package org.granitemc.granite.api.entity;
import org.granitemc.granite.api.Player;
import org.granitemc.granite.api.item.ItemStack;
import org.granitemc.granite.api.world.Location;
import org.granitemc.granite.api.world.World;
import java.util.UUID;
public interface Entity {
/**
* Returns the entity ID
*/
int getEntityId();
//TODO: this is new in 1.8
/*void G();*/
boolean equals(Object object);
/**
* Sets the entity to be dead
*/
void setDead();
/**
* Sets the size of this entity
* @param width The width in blocks
* @param height The height in blocks
*/
// TODO: check if this actually does anything
void setSize(float width, float height);
/**
* Sets this entity on fire
* @param seconds The amount of seconds
*/
void setFire(int seconds);
/**
* Extinguishes any fire
*/
void extinguish();
/**
* Kills this entity
*/
void kill();
//TODO: What does this do?
/*void m();*/
//TODO: What does this do?
/*void Q();*/
//TODO: What does this do?
/*void a(dt var1, atr var2);*/
/**
* Plays a sound to the entity
* @param soundName The name of the sound played
* @param volume The volume of the sound to be played, where 1.0F is normal
* @param pitch The pitch of the sound to be played, where 1.0F is normal
*/
void playSound(String soundName, float volume, float pitch);
/**
* Returns whether the entity is immune to fire
*/
boolean isImmuneToFire();
/**
* Returns whether the entity is wet
*/
boolean isWet();
/**
* Returns whether the entity is in water
*/
// TODO: Check if this is the same as #isWet
boolean isInWater();
//TODO: What does this do?
//void X();
//TODO: What does this do?
//void Y();
String getSplashSound();
//TODO: Work out what var1 (class bof) is
//boolean isInsideOfMaterial(bof var1);*/
//String getSplashSound();
/**
* Sets the {@link org.granitemc.granite.api.world.World} this entity is in
* @param world The world
*/
void setWorld(World world);
//TODO: Work out what class dt is
/*void a(dt var1, float var2, float var3);*/
/**
* Returns the distance to another entity
* @param entity The other entity
*/
float getDistanceToEntity(Entity entity);
//TODO: Find out what class dt is
/*double b(dt var1);*/
//TODO: Find out what class dt is
/*double c(dt var1);*/
/**
* Returns the squared distance to another entity, this is much faster than {@link #getDistanceToEntity(Entity)}
* @param entity The other entity
*/
double getDistanceSqToEntity(Entity entity);
/**
* Adds velocity to this entity
* @param x X velocity
* @param y Y velocity
* @param z Z velocity
*/
void addVelocity(double x, double y, double z);
/**
* Returns whether this entity can be collided with
*/
boolean canBeCollidedWith();
/**
* Returns whether this entity can be pushed
*/
boolean canBePushed();
String getEntityString();
//TODO: find out what adw and alq class is
//TODO: find a good name for functions
//TODO: what do the vars do?
/*adw s(alq var1, int var2);*/
//TODO: find out what adw and alq class is
//TODO: find a good name for functions
//TODO: what do the vars do?
/*adw a(alq var1, int var2, float var3);*/
//TODO: find out what adw is
//TODO: what do the var2 does?
/*adw entityDropItem(ItemStack itemStack, float var2);*/
/**
* Returns whether this entity is alive
*/
boolean isEntityAlive();
/**
* Returns whether this entity is inside an opaque block
*/
boolean isEntityInsideOpaqueBlock();
/**
* Mounts this entity on top of another entity
* @param entity The other entity
*/
void mountEntity(Entity entity);
/**
* Returns whether this entity is eating
*/
boolean isEating();
/**
* Sets whether this entity is eating
* @param eating Whether this entity is eating
*/
void setEating(boolean eating);
//TODO: add this later
/*ItemStack[] getInventory();*/
/**
* Sets an inventory or armor slot
* @param inventoryIndex The index to set
* @param itemStack The {@link org.granitemc.granite.api.item.ItemStack} to set to
*/
// TODO: explain index or change
void setCurrentItemOrArmor(int inventoryIndex, ItemStack itemStack);
/**
* Returns whether this entity is currently burning
*/
boolean isBurning();
/**
* Returns whether this entity is currently riding another entity
*/
boolean isRiding();
/**
* Returns whether this entity is currently sneaking
*/
boolean isSneaking();
/**
* Sets whether this entity is sneaking
* @param sneaking Whether this entity is sneaking
*/
void setSneaking(boolean sneaking);
/**
* Returns whether this entity is sprinting
*/
boolean isSprinting();
/**
* Sets whether this entity is sneaking
* @param sprinting Whether this entity is sneaking
*/
void setSprinting(boolean sprinting);
/**
* Returns whether this entity is invisible
*/
boolean isInvisible();
/**
* Sets whether this entity is invisible
* @param invisible Whether this entity is invisible
*/
void setInvisible(boolean invisible);
//TODO: Work out what the flags are?
/*boolean getFlag(int flag);*/
/*void setFlag(int flag, boolean var2);*/
/**
* Returns how much air this entity has left
*/
int getAir();
/**
* Sets how much air this entity has left
* @param amount How much air this entity has left
*/
void setAir(int amount);
//TODO: Find out what class ads is
/*void onStruckByLightning(ads var1);*/
//TODO: Work out a suitable name and what the vars do
/*boolean j(double var1, double var2, double var3);*/
/**
* Sets this entity to be in a web
*/
void setInWeb();
/**
* Returns the command sender name of this entity
*/
String getCommandSenderName();
/**
* Returns the parts of this entity
*/
// TODO: figure out what this thing
Entity[] getParts();
/**
* Returns whether this entity is equal to another entity
* @param entity The other entity
*/
boolean isEntityEqual(Entity entity);
/**
* Returns whether this entity can attack with an item
*/
boolean canAttackWithItem();
//TODO: Find suitable name and work out what the vars do and their classes
/*float a(aqo var1, World world, dt var3, bec var4);*/
//TODO: Find suitable name and work out what the vars do and their classes
/*boolean a(aqo var1, World world, dt var3, bec var4, float var5);*/
//TODO: Figure out what this does
int getTeleportDirection();
boolean doesEntityNotTriggerPressurePlate();
/**
* Returns the UUID of this entity
*/
UUID getUniqueID();
/**
* Returns whether this entity is currently being pushed by water
*/
boolean isPushedByWater();
//TODO: Find Suitable name and get ho class
/*ho e_();*/
/**
* Returns the {@link org.granitemc.granite.api.world.World} this entity is in
*/
World getWorld();
/**
* Teleports the entity to a player
* @param player The player to teleport to
*/
void teleportToPlayer(Player player);
/**
* Returns the distance to a {@link org.granitemc.granite.api.world.Location}
* @param location The location
*/
double getDistanceToLocation(Location location);
/**
* Returns the squared distance to a location, this is much faster than {@link #getDistanceToLocation(org.granitemc.granite.api.world.Location)}
* @param location The location
*/
double getDistanceSqToLocation(Location location);
/**
* Returns the location of this entity
*/
Location getLocation();
void setLocation(Location location);
double getX();
void setX(double x);
double getY();
void setY(double y);
double getZ();
void setZ(double z);
float getPitch();
void setPitch(float pitch);
float getYaw();
void setYaw(float yaw);
/**
* Returns the entity currently riding this entity (or null)
*/
// TODO: rename this so it makes more sense
Entity riddenByEntity();
/**
* Returns the entity we are currently riding (or null)
*/
// TODO: rename this so it makes more sense
Entity ridingEntity();
}
|
package uk.co.buildergenerator;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BuilderGenerator {
/**
* The default output directory where generated builder sources will be
* written.
*
* This is the current directory the Java process is executed from.
*/
public static final String DEFAULT_OUTPUT_DIRECTORY = ".";
/**
* Generate builders for an object graph whose graph root is
* <code>rootClassName</code>.
* <p>
* Use this utility method when the default builder package and default
* output directory are sufficient.
* </p>
* See: <br/>
* {@link #setOutputDirectory(String) setOutputDirectory}
* {@link #setBuilderPackage(String) setBuilderPackage}
*
* @param rootClassName
* the object graph root class name
* @throws ClassNotFoundException if the root class cannot be found on the classpath
*/
public static void generateBuilders(String rootClassName)
throws ClassNotFoundException {
new BuilderGenerator(rootClassName).generateBuilders();
}
/**
* Generate builders for an object graph whose graph root is
* <code>rootClass</code>.
* <p>
* Use this utility method when the default builder package and default
* output directory are sufficient.
* </p>
* See: <br/>
* {@link #setOutputDirectory(String) setOutputDirectory}
* {@link #setBuilderPackage(String) setBuilderPackage}
*
* @param rootClass
* the object graph root class
*/
public static void generateBuilders(Class<?> rootClass) {
new BuilderGenerator(rootClass).generateBuilders();
}
private final Class<?> rootClass;
private final BuilderWriter builderWriter;
private final FileUtils fileUtils;
private final PropertiesToIgnore propertiesToIgnore = new PropertiesToIgnore();
private final ClassesToIgnore classesToIgnore = new ClassesToIgnore();
private final Map<String, String> builderSuperClass = new HashMap<String, String>();
private String builderPackage;
private String outputDirectory;
private boolean generationGap;
private String generationGapBaseBuilderPackage;
/**
* Construct a <code>BuilderGenerator</code> for an object graph whose graph
* root is <code>rootClassName</code>.
*
* @param rootClassName
* the object graph root class name
* @throws ClassNotFoundException if the root class cannot be found on the classpath
*/
public BuilderGenerator(String rootClassName) throws ClassNotFoundException {
this(Class.forName(rootClassName));
}
/**
* Construct a <code>BuilderGenerator</code> for an object graph whose graph
* root is <code>rootClass</code>.
*
* @param rootClass
* the object graph root class
*/
public BuilderGenerator(Class<?> rootClass) {
this(rootClass, new BuilderWriter(new FileUtils()), new FileUtils());
}
BuilderGenerator(Class<?> rootClass, BuilderWriter builderWriter, FileUtils fileUtils) {
this.rootClass = rootClass;
this.builderWriter = builderWriter;
this.fileUtils = fileUtils;
setBuilderPackage(deriveDefaultBuilderPackage(rootClass));
setOutputDirectory(DEFAULT_OUTPUT_DIRECTORY);
}
private String deriveDefaultBuilderPackage(Class<?> rootClass) {
return rootClass.getPackage().getName() + "builder";
}
/**
* Generate the builders.
*/
public void generateBuilders() {
File outputDirectoryFile = fileUtils.newFile(getOutputDirectory());
fileUtils.createDirectoriesIfNotExists(outputDirectoryFile);
BuilderTemplateMapCollector builderTemplateMapCollector = new BuilderTemplateMapCollector(getRootClass(), getBuilderPackage(), propertiesToIgnore, classesToIgnore);
List<BuilderTemplateMap> builderTemplateMapList = builderTemplateMapCollector.collectBuilderTemplateMaps();
for (BuilderTemplateMap builderTemplateMap : builderTemplateMapList) {
builderTemplateMap.setSuperClass(builderSuperClass.get(builderTemplateMap.getFullyQualifiedTargetClassName()));
if (generationGap) {
String baseBuilderPackage = getGenerationGapBaseBuilderPackage() != null ? getGenerationGapBaseBuilderPackage() : getBuilderPackage();
builderWriter.generateBuilderWithGenerationGap(builderTemplateMap, outputDirectoryFile, baseBuilderPackage);
} else {
builderWriter.generateBuilder(builderTemplateMap, outputDirectoryFile);
}
}
}
Class<?> getRootClass() {
return rootClass;
}
String getBuilderPackage() {
return builderPackage;
}
String getOutputDirectory() {
return outputDirectory;
}
String getGenerationGapBaseBuilderPackage() {
return generationGapBaseBuilderPackage;
}
/**
* Override the default builder package by calling this method.
*
* @param builderPackage
* the package that generated builders will be written to.
*/
public void setBuilderPackage(String builderPackage) {
this.builderPackage = builderPackage;
}
/**
* Override the default output directory by calling this method.
*
* @param outputDirectory
* the output directory that generated builders will be written
* to.
*/
public void setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
}
/**
* @deprecated see {@link #addPropertyToIgnore(String, String) addPropertyToIgnore}
*
* @param targetClassName the name of the class in which the property is to be ignored
* @param propertyName the name of the property in the target class to ignore
* @throws ClassNotFoundException if the target class cannot be found on the classpath
*/
@Deprecated
public void setPropertyToIgnore(String targetClassName, String propertyName) throws ClassNotFoundException {
addPropertyToIgnore(targetClassName, propertyName);
}
/**
* Specify a property to ignore in a given class.
*
* Ignored properties will not appear in the generated builder.
*
* @param targetClassName the name of the class in which the property is to be ignored
* @param propertyName the name of the property in the target class to ignore
* @throws ClassNotFoundException if the target class cannot be found on the classpath
*/
public void addPropertyToIgnore(String targetClassName, String propertyName) throws ClassNotFoundException {
addPropertyToIgnore(Class.forName(targetClassName), propertyName);
}
/**
* @deprecated see {@link #addPropertyToIgnore(Class, String) addPropertyToIgnore}
*
* @param targetClass the class in which the property is to be ignored
* @param propertyName the name of the property in the target class to ignore
*/
@Deprecated
public void setPropertyToIgnore(Class<?> targetClass, String propertyName) {
addPropertyToIgnore(targetClass, propertyName);
}
/**
* Specify a property to ignore in a given class.
*
* Ignored properties will not appear in the generated builder.
*
* @param targetClass the class in which the property is to be ignored
* @param propertyName the name of the property in the target class to ignore
*/
public void addPropertyToIgnore(Class<?> targetClass, String propertyName) {
propertiesToIgnore.addPropertyToIgnore(targetClass, propertyName);
}
/**
* Add classes that <code>BuilderGenerator</code> will ignore. I.e. no builder will
* be generated for the given class.
* <p>
* Classes with properties of the ignored types will still have a <code>with<i>Property</i></code> method generated
* to set the property, but the parameter to the <code>with<i>Property</i></code> method will be the property type,
* not a builder.
*
* @param classToIgnore class to ignore
*/
public void addClassToIgnore(Class<?> classToIgnore) {
addClassToIgnore(classToIgnore.getCanonicalName());
}
/**
* Add classes that <code>BuilderGenerator</code> will ignore. I.e. no builder will
* be generated for the given class.
* <p>
* Classes with properties of the ignored types will still have a <code>with<i>Property</i></code> method generated
* to set the property, but the parameter to the <code>with<i>Property</i></code> method will be the property type,
* not a builder.
* <p>
* Wild cards can be used to ignore groups of classes or entire packages (and sub packages), e.g:
* <p>
* <code>com.example.MyCla*</code> - will ignore all classes starting with com.example.MyCla<br>
* <code>com.example*</code> - will ignore all classes in the com.example package (and sub packages)<br>
*
* @param classNameToIgnore The class name (with or without trailing wild card) to ignore
*/
public void addClassToIgnore(String classNameToIgnore) {
classesToIgnore.add(classNameToIgnore);
}
public void setGenerationGap(boolean generationGap) {
this.generationGap = generationGap;
}
/**
* Set the package of the base builders when building using the Generation Gap pattern.
*
* @param generationGapBaseBuilderPackage
* the package that generated base builders will be written to.
*/
public void setGenerationGapBaseBuilderPackage(String generationGapBaseBuilderPackage) {
this.generationGapBaseBuilderPackage = generationGapBaseBuilderPackage;
}
public void addBuilderSuperClass(Class<?> targetClass, String superClassStatement) {
builderSuperClass.put(targetClass.getName(), superClassStatement);
}
public void addBuilderSuperClass(Class<?> targetClass, Class<?> superClass) {
if (generationGap) {
addBuilderSuperClass(targetClass, superClass.getName() + "<T>");
} else {
addBuilderSuperClass(targetClass, superClass.getName() + "<" + targetClass.getSimpleName() +"Builder>");
}
}
}
|
package com.sun.star.comp.bridge;
import com.sun.star.bridge.XBridge;
import com.sun.star.bridge.XBridgeFactory;
import com.sun.star.bridge.XInstanceProvider;
import com.sun.star.uno.XComponentContext;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.container.XSet;
import com.sun.star.loader.XImplementationLoader;
import com.sun.star.connection.Acceptor;
import com.sun.star.connection.XAcceptor;
import com.sun.star.connection.XConnection;
import com.sun.star.uno.UnoRuntime;
public class TestComponentMain
{
static class InstanceProvider implements XInstanceProvider {
XComponentContext ctx;
public InstanceProvider( XComponentContext ctx )
{
this.ctx = ctx;
}
public Object getInstance( String sInstanceName )
throws com.sun.star.container.NoSuchElementException, com.sun.star.uno.RuntimeException
{
Object o =null;
try
{
o = ctx.getServiceManager().createInstanceWithContext(
"com.sun.star.comp.bridge.TestComponent$_TestObject" , ctx );
}
catch( com.sun.star.uno.Exception e )
{
System.out.println( "error during instantiation" + e );
}
return o;
}
}
static public void main(String args[]) throws Exception, com.sun.star.uno.Exception {
if(args.length != 1) {
System.err.println("usage : com.sun.star.comp.bridge.TestComponentMain uno:connection;protocol;objectName");
System.exit(-1);
}
String conDcp = null;
String protDcp = null;
String rootOid = null;
String dcp = args[0];
int index = dcp.indexOf(':');
String url = dcp.substring(0, index).trim();
dcp = dcp.substring(index + 1).trim();
index = dcp.indexOf(';');
conDcp = dcp.substring(0, index).trim();
dcp = dcp.substring(index + 1).trim();
index = dcp.indexOf(';');
protDcp = dcp.substring(0, index).trim();
dcp = dcp.substring(index + 1).trim();
rootOid = dcp.trim().trim();
XComponentContext ctx = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null );
XMultiComponentFactory smgr = ctx.getServiceManager();
XMultiServiceFactory oldsmgr = (XMultiServiceFactory)
UnoRuntime.queryInterface( XMultiServiceFactory.class, smgr );
// prepare servicemanager
XSet set = (XSet) UnoRuntime.queryInterface(XSet.class, smgr);
Object o = com.sun.star.comp.bridge.TestComponent.__getServiceFactory(
"com.sun.star.comp.bridge.TestComponent$_TestObject", oldsmgr,null );
set.insert(o);
XAcceptor xAcceptor = Acceptor.create(ctx);
System.err.println("waiting for connect...");
while( true )
{
XConnection xConnection = xAcceptor.accept(conDcp);
XBridgeFactory xBridgeFactory = (XBridgeFactory)UnoRuntime.queryInterface(
XBridgeFactory.class,
smgr.createInstanceWithContext("com.sun.star.bridge.BridgeFactory",ctx));
XBridge xBridge = xBridgeFactory.createBridge(
"", protDcp, xConnection, new InstanceProvider(ctx));
}
}
}
|
package fitnesse.slim.fixtureInteraction;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class CachedInteraction extends DefaultInteraction {
private static final Constructor<?> noConstructor = NotExisting.class.getConstructors()[0];
private static final Method noMethod = NotExisting.class.getDeclaredMethods()[0];
private final Map<String, Constructor<?>> constructorsByClassAndArgs = new HashMap<>();
private final Map<String, Class<?>> classCache = new HashMap<>();
private final Map<MethodKey, Method> methodsByNameAndArgs = new HashMap<>();
@Override
protected Constructor<?> getConstructor(Class<?> clazz,
Object[] args) {
String key = String.format("%s_%d", clazz.getName(), args.length);
Constructor<?> cached = constructorsByClassAndArgs.get(key);
if (cached == noConstructor) return null;
if (cached != null) return cached;
Constructor<?> constructor = handleConstructorCacheMiss(clazz, args);
if (constructor == null) {
constructorsByClassAndArgs.put(key, noConstructor);
} else {
constructorsByClassAndArgs.put(key, constructor);
}
return constructor;
}
@Override
protected Class<?> getClass(String className) {
Class<?> k = classCache.get(className);
if (k == NotExisting.class) return null;
if (k != null) return k;
k = handleClassCacheMiss(className);
if (k == null) {
classCache.put(className, NotExisting.class);
} else {
classCache.put(className, k);
}
return k;
}
@Override
protected Method findMatchingMethod(String methodName, Class<?> k, int nArgs) {
MethodKey key = new MethodKey(k, methodName, nArgs);
Method cached = this.methodsByNameAndArgs.get(key);
if (cached == noMethod) return null;
if (cached != null) return cached;
Method method = handleMethodCacheMiss(methodName, k, nArgs);
if (method == null) {
methodsByNameAndArgs.put(key, noMethod);
} else {
methodsByNameAndArgs.put(key, method);
}
return method;
}
protected Constructor<?> handleConstructorCacheMiss(Class<?> clazz, Object[] args) {
return super.getConstructor(clazz, args);
}
protected Class<?> handleClassCacheMiss(String className) {
return super.getClass(className);
}
protected Method handleMethodCacheMiss(String methodName, Class<?> k, int nArgs) {
return super.findMatchingMethod(methodName, k, nArgs);
}
private static class MethodKey {
final String k;
final String method;
final int nArgs;
public MethodKey(Class<?> k, String method, int nArgs) {
this.k = k.getSimpleName();
this.method = method;
this.nArgs = nArgs;
}
public int hashCode() {
return nArgs * 31 + method.hashCode() + 31 * k.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MethodKey)) return false;
MethodKey m = (MethodKey) o;
if (m.nArgs != nArgs) return false;
if (!m.k.equals(k)) return false;
return m.method.equals(method);
}
}
private static final class NotExisting {
public NotExisting() {}
public void doIt() {}
}
}
|
package org.voltcore.network;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLEngine;
import org.voltcore.logging.VoltLogger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.FlexibleSemaphore;
import org.voltcore.utils.Pair;
import org.voltcore.utils.ssl.SSLBufferDecrypter;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
import io.netty_voltpatches.buffer.ByteBuf;
import io.netty_voltpatches.buffer.CompositeByteBuf;
import io.netty_voltpatches.buffer.Unpooled;
import io.netty_voltpatches.util.IllegalReferenceCountException;
public class TLSDecryptionAdapter {
public final static int TLS_HEADER_SIZE = 5;
private final static int MAX_READ = CipherExecutor.FRAME_SIZE << 1; //32 KB
private final static int NOT_AVAILABLE = -1;
protected static final VoltLogger networkLog = new VoltLogger("NETWORK");
private final SSLEngine m_sslEngine;
private final SSLBufferDecrypter m_decrypter;
private final ConcurrentLinkedDeque<ExecutionException> m_exceptions = new ConcurrentLinkedDeque<>();
private final ConcurrentLinkedDeque<ByteBuffer> m_decrypted = new ConcurrentLinkedDeque<>();
private final FlexibleSemaphore m_inFlight = new FlexibleSemaphore(1);
private final CipherExecutor m_ce;
private final DecryptionGateway m_dcryptgw;
private final Connection m_connection;
private final InputHandler m_inputHandler;
private volatile boolean m_isDead;
private int m_needed = NOT_AVAILABLE;
public TLSDecryptionAdapter(Connection connection, InputHandler handler, SSLEngine sslEngine, CipherExecutor cipherExecutor) {
m_connection = connection;
m_inputHandler = handler;
m_ce = cipherExecutor;
m_sslEngine = sslEngine;
m_decrypter = new SSLBufferDecrypter(sslEngine);
m_dcryptgw = new DecryptionGateway();
}
/**
* this values may change if a TLS session renegotiates its cipher suite
*/
private int applicationBufferSize() {
return m_sslEngine.getSession().getApplicationBufferSize();
}
void die() {
m_isDead = true;
m_dcryptgw.die();
int waitFor = 1 - m_inFlight.availablePermits();
for (int i = 0; i < waitFor; ++i) {
try {
if (m_inFlight.tryAcquire(1, TimeUnit.SECONDS)) {
m_inFlight.release();
break;
}
} catch (InterruptedException e) {
break;
}
}
m_inFlight.drainPermits();
m_inFlight.release();
}
private boolean isDead() {
return m_isDead;
}
public Pair<Integer, Integer> handleInputStreamMessages(boolean doRead, NIOReadStream readStream, SocketChannel fromChannel, NetworkDBBPool toPool)
throws IOException {
checkForGatewayExceptions();
int readBytes = 0;
/* Have the read stream fill from the network */
if (doRead) {
final int maxRead = getMaxRead(readStream);
if (maxRead > 0) {
readBytes = readStream.read(fromChannel, maxRead, toPool);
if (readBytes == -1) {
throw new EOFException();
}
if (readBytes > 0) {
ByteBuf frameHeader = Unpooled.wrappedBuffer(new byte[TLS_HEADER_SIZE]);
while (readStream.dataAvailable() >= TLS_HEADER_SIZE) {
readStream.peekBytes(frameHeader.array());
m_needed = frameHeader.getShort(3) + TLS_HEADER_SIZE;
if (readStream.dataAvailable() < m_needed) break;
m_dcryptgw.offer(readStream.getSlice(m_needed));
m_needed = NOT_AVAILABLE;
}
}
}
}
/**
TODO: Moving this stopping check to TLSVoltPort after this method is called.
This means that handleMessages will be done before this check. Any adverse effects?
if (m_network.isStopping() || m_isShuttingDown) {
waitForPendingDecrypts();
}
*/
int numMessages = 0;
ByteBuffer message = null;
while ((message = pollDecryptedQueue()) != null) {
++numMessages;
m_inputHandler.handleMessage(message, m_connection);
}
return new Pair<Integer, Integer>(readBytes, numMessages);
}
private final int getMaxRead(NIOReadStream readStream) {
return m_inputHandler.getMaxRead() == 0 ? 0 // in back pressure
: m_needed == NOT_AVAILABLE ? MAX_READ :
readStream.dataAvailable() > m_needed ? 0 : m_needed - readStream.dataAvailable();
}
ByteBuffer pollDecryptedQueue() {
return m_decrypted.poll();
}
void releaseDecryptedBuffer() {
m_dcryptgw.releaseDecryptedBuffer();
}
void checkForGatewayExceptions() throws IOException {
ExecutionException ee = m_exceptions.poll();
if (ee != null) {
IOException ioe = TLSException.ioCause(ee.getCause());
if (ioe == null) {
ioe = new IOException("decrypt task failed", ee.getCause());
}
throw ioe;
}
}
void waitForPendingDecrypts() throws IOException {
boolean acquired;
do {
int waitFor = 1 - m_inFlight.availablePermits();
acquired = waitFor == 0;
for (int i = 0; i < waitFor && !acquired; ++i) {
checkForGatewayExceptions();
try {
acquired = m_inFlight.tryAcquire(1, TimeUnit.SECONDS);
if (acquired) {
m_inFlight.release();
}
} catch (InterruptedException e) {
throw new IOException("interrupted while waiting for pending decrypts", e);
}
}
} while (!acquired);
}
String dumpState() {
return new StringBuilder(256).append("TLSPortAdapter[")
.append("gateway=").append(m_dcryptgw.dumpState())
.append(", decrypted.isEmpty()= ").append(m_decrypted.isEmpty())
.append(", exceptions.isEmpty()= ").append(m_exceptions.isEmpty())
.append(", inFlight=").append(m_inFlight.availablePermits())
.append("]").toString();
}
class ExceptionListener implements Runnable {
private final ListenableFuture<?> m_fut;
private ExceptionListener(ListenableFuture<?> fut) {
m_fut = fut;
}
@Override
public void run() {
if (isDead()) return;
try {
m_fut.get();
} catch (InterruptedException notPossible) {
} catch (ExecutionException e) {
m_inFlight.release();
networkLog.error("unexpect fault occurred in decrypt task", e.getCause());
m_exceptions.offer(e);
}
}
}
/**
* Construct used to serialize all the decryption tasks for this port.
* it takes a view of the incoming queued buffers (that may span two BBContainers)
* and decrypts them. It uses the assembler to gather all frames that comprise
* a frame spanning message, otherwise it will enqueue decrypted messages to
* the m_descrypted queue.
*/
class DecryptionGateway implements Runnable {
private final byte [] m_overlap = new byte[CipherExecutor.FRAME_SIZE + 2048];
private final ConcurrentLinkedDeque<NIOReadStream.Slice> m_q = new ConcurrentLinkedDeque<>();
private final CompositeByteBuf m_msgbb = Unpooled.compositeBuffer();
synchronized void offer(NIOReadStream.Slice slice) {
if (isDead()) {
slice.markConsumed().discard();
return;
}
final boolean wasEmpty = m_q.isEmpty();
m_q.offer(slice);
if (wasEmpty) {
submitSelf();
}
m_inFlight.reducePermits(1);
}
synchronized void die() {
NIOReadStream.Slice slice = null;
while ((slice=m_q.poll()) != null) {
slice.markConsumed().discard();
}
releaseDecryptedBuffer();
}
synchronized boolean isEmpty() {
return m_q.isEmpty();
}
String dumpState() {
return new StringBuilder(256).append("DecryptionGateway[isEmpty()=").append(isEmpty())
.append(", isDead()=").append(isDead())
.append(", msgbb=").append(m_msgbb)
.append("]").toString();
}
void releaseDecryptedBuffer() {
if (m_msgbb.refCnt() > 0) try {
m_msgbb.release();
} catch (IllegalReferenceCountException ignoreIt) {
}
}
@Override
public void run() {
final NIOReadStream.Slice slice = m_q.peek();
if (slice == null) return;
ByteBuf src = slice.bb;
if (isDead()) synchronized(this) {
slice.markConsumed().discard();
m_q.poll();
releaseDecryptedBuffer();
return;
}
ByteBuffer [] slicebbarr = slice.bb.nioBuffers();
// if frame overlaps two buffers then copy it to the overlap buffer
// and use that instead for the unwrap src buffer
if (slicebbarr.length > 1) {
src = Unpooled.wrappedBuffer(m_overlap).clear();
slice.bb.readBytes(src, slice.bb.readableBytes());
slicebbarr[0] = src.nioBuffer();
}
final int appBuffSz = applicationBufferSize();
ByteBuf dest = m_ce.allocator().buffer(appBuffSz).writerIndex(appBuffSz);
ByteBuffer destjbb = dest.nioBuffer();
int decryptedBytes = 0;
int srcBBLength = slicebbarr[0].remaining();
try {
decryptedBytes = m_decrypter.tlsunwrap(slicebbarr[0], destjbb);
} catch (TLSException e) {
m_inFlight.release(); dest.release();
m_exceptions.offer(new ExecutionException("fragment decrypt task failed", e));
networkLog.error("fragment decrypt task failed", e);
networkLog.error("isDead()=" + isDead() + ", Src buffer original length: " + srcBBLength +
", Length after decrypt operation: " + slicebbarr[0].remaining());
m_connection.enableWriteSelection();
return;
}
assert !slicebbarr[0].hasRemaining() : "decrypter did not wholly consume the source buffer";
// src buffer is wholly consumed
if (!isDead()) {
if (decryptedBytes > 0) {
dest.writerIndex(destjbb.limit());
m_msgbb.addComponent(true, dest);
} else {
// the TLS frame was consumed by the call to engines unwrap but it
// did not yield any content
dest.release();
}
int read = 0;
while (m_msgbb.readableBytes() >= getNeededBytes()) {
ByteBuffer bb = null;
try {
bb = m_inputHandler.retrieveNextMessage(m_msgbb);
// All of the message bytes are not available yet
if (bb==null) continue;
} catch(IOException e) {
m_inFlight.release(); m_msgbb.release();
m_exceptions.offer(new ExecutionException("failed message length check", e));
networkLog.error("failed message length check", e);
m_connection.enableWriteSelection();
continue;
}
m_decrypted.offer((ByteBuffer)bb.flip());
++read;
}
if (read > 0) {
m_msgbb.discardReadComponents();
m_connection.enableWriteSelection();
}
} else { // it isDead()
dest.release();
releaseDecryptedBuffer();
}
synchronized(this) {
m_q.poll();
slice.markConsumed().discard();
m_inFlight.release();
if (m_q.peek() != null) {
submitSelf();
}
}
}
void submitSelf() {
ListenableFuture<?> fut = m_ce.submit(this);
fut.addListener(new ExceptionListener(fut), CoreUtils.LISTENINGSAMETHREADEXECUTOR);
}
private int getNeededBytes() {
int nextLength = m_inputHandler.getNextMessageLength();
return nextLength == 0 ? 4 : nextLength;
}
}
/** The distinct exception class allows better logging of these unexpected errors. */
static class BadMessageLength extends IOException {
private static final long serialVersionUID = 8547352379044459911L;
public BadMessageLength(String string) {
super(string);
}
}
}
|
package hm.binkley.util.logging.osi;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.rules.ExpectedException;
import org.slf4j.LoggerFactory;
import static hm.binkley.util.logging.osi.OSI.SystemProperty.LOGBACK_CONFIGURATION_FILE;
import static hm.binkley.util.logging.osi.OSI.SystemProperty.LOGBACK_JANSI;
import static hm.binkley.util.logging.osi.OSI.SystemProperty.LOGBACK_STYLE;
import static hm.binkley.util.logging.osi.OSI.SystemProperty.resetForTesting;
import static java.lang.System.getProperty;
import static java.lang.System.setProperty;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.rules.ExpectedException.none;
/**
* {@code OSITest} tests {@link OSI}.
*
* @author <a href="mailto:Brian.Oxley@macquarie.com">Brian Oxley</a>
* @todo StandardOutputStreamLog still prints to sout/serr
* @todo StandardOutputStreamLog does not process into List of String
*/
public final class OSITest {
@Rule
public final ExpectedException thrown = none();
@Rule
public final StandardOutputStreamLog sout = new StandardOutputStreamLog();
@Before
public void setUpOSITest() {
asList(OSI.SystemProperty.values()).stream().
map(OSI.SystemProperty::key).
filter(key -> null != getProperty(key)).
forEach(System::clearProperty);
}
@After
public void tearDownOSITest() {
resetForTesting();
}
@Test
public void shouldSetUnset() {
assertThat(getProperty("logback.configurationFile"), is(nullValue()));
final String configurationFile = "ignored";
LOGBACK_CONFIGURATION_FILE.set(configurationFile, false);
assertThat(getProperty("logback.configurationFile"), is(equalTo(configurationFile)));
LOGBACK_CONFIGURATION_FILE.unset();
assertThat(getProperty("logback.configurationFile"), is(nullValue()));
}
@Test
public void shouldThrowIfUnsetWithoutSet() {
thrown.expect(IllegalStateException.class);
LOGBACK_CONFIGURATION_FILE.unset();
}
@Test
public void shouldThrowIfSetTwice() {
thrown.expect(IllegalStateException.class);
LOGBACK_CONFIGURATION_FILE.set("ignored", false);
LOGBACK_CONFIGURATION_FILE.set("ignored", false);
}
@Test
public void shouldNotThrowIfSetTwiceWithOverride() {
LOGBACK_CONFIGURATION_FILE.set("ignored", false);
final String configurationFile = "other ignored";
LOGBACK_CONFIGURATION_FILE.set(configurationFile, true);
assertThat(getProperty(LOGBACK_CONFIGURATION_FILE.key()), is(equalTo(configurationFile)));
}
@Test
public void shouldIgnoreIfSystemPropertyExistsAndNotOverride() {
setProperty(LOGBACK_CONFIGURATION_FILE.key(), "ignored");
assertThat(LOGBACK_CONFIGURATION_FILE.set("ignored", false), is(false));
}
@Test
public void shouldReturnTrueIfSystemPropertyExistsWithOverride() {
setProperty(LOGBACK_CONFIGURATION_FILE.key(), "ignored");
final String configurationFile = "other ignored";
LOGBACK_CONFIGURATION_FILE.set(configurationFile, true);
assertThat(getProperty(LOGBACK_CONFIGURATION_FILE.key()), is(equalTo(configurationFile)));
}
@Test
public void shouldIncludeApplicationName() {
OSI.enable("MyApp");
LoggerFactory.getLogger("bob").error("ouch");
assertThat(sout.getLog(), containsString("MyApp"));
}
@Test
public void shouldIncludeAnsiEscapes() {
setProperty(LOGBACK_JANSI.key(), "true");
setProperty(LOGBACK_STYLE.key(), "%black(%message)");
resetForTesting();
LoggerFactory.getLogger("bob").error("broke");
assertThat(sout.getLog(), is(equalTo("broke")));
}
}
|
package org.pentaho.di.trans.steps.constant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.trans.RowStepCollector;
import org.pentaho.di.trans.StepLoader;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.rowgenerator.RowGeneratorMeta;
/**
* Test class for the Constant step.
*
* @author Sven Boden
*/
public class ConstantTest extends TestCase
{
public RowMetaInterface createResultRowMetaInterface()
{
RowMetaInterface rm = new RowMeta();
ValueMetaInterface valuesMeta[] = {
new ValueMeta("boolean1", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("boolean2", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("boolean3", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("boolean4", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("boolean5", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("boolean6", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("boolean7", ValueMeta.TYPE_BOOLEAN),
new ValueMeta("string1", ValueMeta.TYPE_STRING),
new ValueMeta("string2", ValueMeta.TYPE_STRING),
new ValueMeta("string3", ValueMeta.TYPE_STRING),
new ValueMeta("integer1", ValueMeta.TYPE_INTEGER),
new ValueMeta("integer2", ValueMeta.TYPE_INTEGER),
new ValueMeta("integer3", ValueMeta.TYPE_INTEGER),
new ValueMeta("integer4", ValueMeta.TYPE_INTEGER),
new ValueMeta("number1", ValueMeta.TYPE_NUMBER),
new ValueMeta("number2", ValueMeta.TYPE_NUMBER),
new ValueMeta("number3", ValueMeta.TYPE_NUMBER),
new ValueMeta("number4", ValueMeta.TYPE_NUMBER),
};
for (int i=0; i < valuesMeta.length; i++ )
{
rm.addValueMeta(valuesMeta[i]);
}
return rm;
}
public List<RowMetaAndData> createResultData1()
{
List<RowMetaAndData> list = new ArrayList<RowMetaAndData>();
RowMetaInterface rm = createResultRowMetaInterface();
Object[] r1 = new Object[] { Boolean.TRUE, Boolean.FALSE, Boolean.FALSE,
Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, null,
"AAAAAAAAAAAAAA", " ", null,
Long.valueOf(-100L), Long.valueOf(0L), Long.valueOf(212L), null,
new Double(-100.2), new Double(0.0), new Double(212.23), null};
list.add(new RowMetaAndData(rm, r1));
return list;
}
/**
* Check the 2 lists comparing the rows in order.
* If they are not the same fail the test.
*/
public void checkRows(List<RowMetaAndData> rows1, List<RowMetaAndData> rows2)
{
int idx = 1;
if ( rows1.size() != rows2.size() )
{
fail("Number of rows is not the same: " +
rows1.size() + " and " + rows2.size());
}
Iterator<RowMetaAndData> it1 = rows1.iterator();
Iterator<RowMetaAndData> it2 = rows2.iterator();
while ( it1.hasNext() && it2.hasNext() )
{
RowMetaAndData rm1 = it1.next();
RowMetaAndData rm2 = it2.next();
Object[] r1 = rm1.getData();
Object[] r2 = rm2.getData();
if ( rm1.size() != rm2.size() )
{
fail("row nr " + idx + " is not equal");
}
int fields[] = new int[rm1.size()];
for ( int ydx = 0; ydx < rm1.size(); ydx++ )
{
fields[ydx] = ydx;
}
try {
if ( rm1.getRowMeta().compare(r1, r2, fields) != 0 )
{
fail("row nr " + idx + " is not equal");
}
} catch (KettleValueException e) {
fail("row nr " + idx + " is not equal");
}
idx++;
}
}
/**
* Test case for Constant step. Row generator attached to a constant step.
*/
public void testConstant1() throws Exception
{
EnvUtil.environmentInit();
// Create a new transformation...
TransMeta transMeta = new TransMeta();
transMeta.setName("constanttest1");
StepLoader steploader = StepLoader.getInstance();
// create a row generator step...
String rowGeneratorStepname = "row generator step";
RowGeneratorMeta rm = new RowGeneratorMeta();
// Set the information of the row generator.
String rowGeneratorPid = steploader.getStepPluginID(rm);
StepMeta rowGeneratorStep = new StepMeta(rowGeneratorPid, rowGeneratorStepname, (StepMetaInterface)rm);
transMeta.addStep(rowGeneratorStep);
// Generate 1 empty row
String fieldName[] = { };
String type[] = { };
String value[] = { };
String fieldFormat[] = { };
String group[] = { };
String decimal[] = { };
int intDummies[] = { };
rm.setDefault();
rm.setFieldName(fieldName);
rm.setFieldType(type);
rm.setValue(value);
rm.setFieldLength(intDummies);
rm.setFieldPrecision(intDummies);
rm.setRowLimit("1");
rm.setFieldFormat(fieldFormat);
rm.setGroup(group);
rm.setDecimal(decimal);
// Add constant step.
String constStepname1 = "constant 1";
ConstantMeta cnst1 = new ConstantMeta();
String fieldName1[] = { "boolean1",
"boolean2",
"boolean3",
"boolean4",
"boolean5",
"boolean6",
"boolean7",
"string1",
"string2",
"string3",
"integer1",
"integer2",
"integer3",
"integer4",
"number1",
"number2",
"number3",
"number4",
};
String type1[] = { "boolean",
"Boolean",
"bOOLEAN",
"BOOLEAN",
"boolean",
"boolean",
"boolean",
"string",
"string",
"String",
"integer",
"integer",
"integer",
"integer",
"number",
"number",
"number",
"number"};
String value1[] = { "Y",
"T",
"a",
"TRUE",
"0",
"9",
"",
"AAAAAAAAAAAAAA",
" ",
"",
"-100", "0", "212", "",
"-100.2", "0.0", "212.23", ""};
String fieldFormat1[] = { "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", ""};
String group1[] = { "", "", "", "", "", "", "", "", "", "",
"", "", "", "", ",", ",", ",", ","};
String decimal1[] = { "", "", "", "", "", "", "", "", "", "",
"", "", "", "", ".", ".", ".", "."};
String currency[] = { "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", ""};
int intDummies1[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
cnst1.setFieldName(fieldName1);
cnst1.setFieldType(type1);
cnst1.setValue(value1);
cnst1.setFieldLength(intDummies1);
cnst1.setFieldPrecision(intDummies1);
cnst1.setFieldFormat(fieldFormat1);
cnst1.setGroup(group1);
cnst1.setDecimal(decimal1);
cnst1.setCurrency(currency);
String addSeqPid1 = steploader.getStepPluginID(cnst1);
StepMeta addSeqStep1 = new StepMeta(addSeqPid1, constStepname1, (StepMetaInterface)cnst1);
transMeta.addStep(addSeqStep1);
TransHopMeta hi1 = new TransHopMeta(rowGeneratorStep, addSeqStep1);
transMeta.addTransHop(hi1);
// Now execute the transformation...
Trans trans = new Trans(transMeta);
trans.prepareExecution(null);
StepInterface si = trans.getStepInterface(constStepname1, 0);
RowStepCollector endRc = new RowStepCollector();
si.addRowListener(endRc);
trans.startThreads();
trans.waitUntilFinished();
// Now check whether the output is still as we expect.
List<RowMetaAndData> goldenImageRows = createResultData1();
List<RowMetaAndData> resultRows1 = endRc.getRowsWritten();
checkRows(resultRows1, goldenImageRows);
}
}
|
package soot.jimple.infoflow.test.securibench;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.BeforeClass;
import soot.jimple.infoflow.Infoflow;
import soot.jimple.infoflow.InfoflowResults;
import soot.jimple.infoflow.taintWrappers.EasyTaintWrapper;
public abstract class JUnitTests {
protected static String path;
protected static List<String> sources;
protected static List<String> sinks;
protected static final String[] sinkArray = new String[]{ "<java.io.PrintWriter: void println(java.lang.String)>",
"<java.io.PrintWriter: void println(java.lang.Object)>",
"<java.sql.Connection: java.sql.PreparedStatement prepareStatement(java.lang.String)>",
"<java.sql.Statement: boolean execute(java.lang.String)>",
"<java.sql.Statement: int executeUpdate(java.lang.String)>",
"<java.sql.Statement: int executeUpdate(java.lang.String,int)>",
"<java.sql.Statement: int executeUpdate(java.lang.String,java.lang.String[])>",
"<java.sql.Statement: java.sql.ResultSet executeQuery(java.lang.String)>"};
protected static final String[] sourceArray = new String[]{"<javax.servlet.ServletRequest: java.lang.String getParameter(java.lang.String)>",
"<javax.servlet.ServletRequest: java.lang.String[] getParameterValues(java.lang.String)>",
"<javax.servlet.ServletConfig: java.lang.String getInitParameter(java.lang.String)>",
"<javax.servlet.ServletConfig: java.util.Enumeration getInitParameterNames()>",
"<javax.servlet.http.HttpServletRequest: java.lang.String getParameter(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.lang.String[] getParameterValues(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.util.Map getParameterMap()>",
"<javax.servlet.http.HttpServletRequest: javax.servlet.http.Cookie[] getCookies()>",
"<javax.servlet.http.HttpServletRequest: java.lang.String getHeader(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.util.Enumeration getHeaders(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.util.Enumeration getHeaderNames()>"};
protected static final String[] refinedSourceArray = new String[]{"<javax.servlet.ServletRequest: java.lang.String getParameter(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.lang.String getParameter(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.lang.String[] getParameterValues(java.lang.String)>",
"<javax.servlet.ServletConfig: java.lang.String getInitParameter(java.lang.String)>",
"<javax.servlet.ServletConfig: java.util.Enumeration getInitParameterNames()>",
"<javax.servlet.http.HttpServletRequest: java.util.Map getParameterMap()>",
"<javax.servlet.http.HttpServletRequest: javax.servlet.http.Cookie[] getCookies()>",
"<javax.servlet.http.HttpServletRequest: java.lang.String getHeader(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.util.Enumeration getHeaders(java.lang.String)>",
"<javax.servlet.http.HttpServletRequest: java.util.Enumeration getHeaderNames()>"};
protected static boolean local = false;
protected static boolean taintWrapper = false;
@BeforeClass
public static void setUp() throws IOException
{
File f = new File(".");
path = //System.getProperty("java.home")+ File.separator + "lib"+File.separator + "jce.jar" + System.getProperty("path.separator") +
System.getProperty("java.home")+ File.separator + "lib"+File.separator + "rt.jar"+ System.getProperty("path.separator") +
f.getCanonicalPath() + File.separator + "bin"+ System.getProperty("path.separator") +
f.getCanonicalPath()+ File.separator+ "lib"+ File.separator+ "servlet-api.jar";
System.out.println("Using following locations as sources for classes: " + path);
sources = Arrays.asList(sourceArray);
sinks = Arrays.asList(sinkArray);
}
@Before
public void resetSootAndStream() throws IOException{
soot.G.reset();
System.gc();
}
protected void checkInfoflow(Infoflow infoflow){
if(infoflow.isResultAvailable()){
InfoflowResults map = infoflow.getResults();
boolean containsSink = false;
List<String> actualSinkStrings = new LinkedList<String>();
for(String sink : sinkArray){
if(map.containsSinkMethod(sink)){
containsSink = true;
actualSinkStrings.add(sink);
}
}
assertTrue(containsSink);
boolean onePathFound = false;
for(String sink : actualSinkStrings){
boolean hasPath = false;
for(String source : refinedSourceArray){
if(map.isPathBetweenMethods(sink, source)){
hasPath = true;
break;
}
}
if(hasPath){
onePathFound = true;
}
}
assertTrue(onePathFound);
}else{
fail("result is not available");
}
}
protected void negativeCheckInfoflow(Infoflow infoflow){
if(infoflow.isResultAvailable()){
InfoflowResults map = infoflow.getResults();
for(String sink : sinkArray){
if(map.containsSinkMethod(sink)){
fail("sink is reached: " +sink);
}
}
}else{
fail("result is not available");
}
}
protected Infoflow initInfoflow(){
Infoflow result = new Infoflow();
result.setLocalInfoflow(local);
SootConfigSecuriBench testConfig = new SootConfigSecuriBench();
result.setSootConfig(testConfig);
if(taintWrapper){
EasyTaintWrapper easyWrapper;
try {
easyWrapper = new EasyTaintWrapper(new File("EasyTaintWrapperSource.txt"));
result.setTaintWrapper(easyWrapper);
} catch (IOException e) {
System.err.println("Could not initialize Taintwrapper:");
e.printStackTrace();
}
}
return result;
}
}
|
package asteroid.utils;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.stmt.BlockStatement;
/**
* General utility methods to deal with {@link ASTNode} instances
*
* @since 0.1.4
* @see asteroid.Utils
*/
public class NodeUtils {
/**
* Utility method to make your transformation code more compile
* static compliant when getting a method node code block. Many
* times you may want to deal with it as if it were a {@link
* BlockStatement}.
*
* @param methodNode the method we want the code from
* @return the method code as a {@link BlockStatement}
*/
public BlockStatement getCodeBlock(final MethodNode methodNode) {
return (BlockStatement) methodNode.getCode();
}
}
|
package gov.nih.nci.calab.ui.submit;
/**
* This class sets up input form for size characterization.
*
* @author pansu
*/
/* CVS $Id: NanoparticleSizeAction.java,v 1.7 2006-10-16 16:28:14 chand Exp $ */
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.dto.characterization.CharacterizationFileBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.dto.characterization.SizeBean;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.File;
public class NanoparticleSizeAction extends AbstractDispatchAction {
private static Logger logger = Logger.getLogger(NanoparticleSizeAction.class);
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
SizeBean sizeChar=(SizeBean) theForm.get("achar");
String viewTitle = (String) theForm.get("viewTitle");
String description = (String) theForm.get("description");
String characterizationSource = (String) theForm.get("characterizationSource");
sizeChar.setCharacterizationSource(characterizationSource);
sizeChar.setDescription(description);
sizeChar.setViewTitle(viewTitle);
if (sizeChar.getId() == null || sizeChar.getId() == "") {
sizeChar.setId( (String) theForm.get("characterizationId") );
}
int fileNumber = 0;
for (DerivedBioAssayDataBean obj : sizeChar.getDerivedBioAssayData()) {
CharacterizationFileBean fileBean = (CharacterizationFileBean) request.getSession().getAttribute("characterizationFile" + fileNumber);
if (fileBean != null) {
obj.setFile(fileBean);
}
fileNumber++;
}
// set createdBy and createdDate for the composition
UserBean user = (UserBean) request.getSession().getAttribute("user");
Date date = new Date();
sizeChar.setCreatedBy(user.getLoginName());
sizeChar.setCreatedDate(date);
request.getSession().setAttribute("newCharacterizationCreated", "true");
SubmitNanoparticleService service = new SubmitNanoparticleService();
service.addParticleSize(particleType, particleName, sizeChar);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addParticleSize");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return forward;
}
/**
* Set up the input forms for adding data
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
initSetup(request, theForm);
return mapping.getInputForward();
}
private void clearMap(HttpSession session, DynaValidatorForm theForm,
ActionMapping mapping) throws Exception {
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
// clear session data from the input forms
theForm.getMap().clear();
theForm.set("particleName", particleName);
theForm.set("particleType", particleType);
theForm.set("achar", new SizeBean());
}
private void initSetup(HttpServletRequest request, DynaValidatorForm theForm)
throws Exception {
HttpSession session = request.getSession();
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
InitSessionSetup.getInstance().setAllInstrumentTypes(session);
InitSessionSetup.getInstance().setAllSizeDistributionGraphTypes(session);
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
InitSessionSetup.getInstance().setManufacturerPerType(session);
}
/**
* Set up the input forms for updating data
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String compositionId = (String) theForm.get("characterizationId");
SearchNanoparticleService service = new SearchNanoparticleService();
Characterization aChar = service.getCharacterizationAndTableBy(compositionId);
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
theForm.set("characterizationId", compositionId);
theForm.set("characterizationSource", aChar.getSource());
theForm.set("viewTitle", aChar.getIdentificationName());
theForm.set("description", aChar.getDescription());
int fileNumber = 0;
for (DerivedBioAssayData obj : aChar.getDerivedBioAssayDataCollection()) {
if (obj.getFile() != null) {
CharacterizationFileBean fileBean = new CharacterizationFileBean();
fileBean.setName(this.getName(obj.getFile()));
fileBean.setPath(this.getPath(obj.getFile()));
fileBean.setId(Integer.toString(fileNumber));
request.getSession().setAttribute("characterizationFile" + fileNumber,
fileBean);
} else {
request.getSession().removeAttribute("characterizationFile" + fileNumber);
}
fileNumber++;
}
SizeBean sChar = new SizeBean(aChar);
theForm.set("achar", sChar);
initSetup(request, theForm);
return mapping.getInputForward();
}
/**
* Set up the input fields for read only view data
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward view(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String particleName = (String) theForm.get("particleName");
SizeBean achar = (SizeBean) theForm.get("achar");
updateCharacterizationTables(achar);
theForm.set("achar", achar);
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return mapping.getInputForward();
}
/**
* Set up information needed for loading a characterization file
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward loadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleName=(String)theForm.get("particleName");
String fileNumber=(String)theForm.get("fileNumber");
request.setAttribute("particleName", particleName);
request.setAttribute("fileNumber", fileNumber);
request.setAttribute("loadFileForward", "sizeInputForm");
return mapping.findForward("loadFile");
}
public void updateCharacterizationTables(SizeBean achar) {
String numberOfCharacterizationTables = achar.getNumberOfDerivedBioAssayData();
int tableNum = Integer.parseInt(numberOfCharacterizationTables);
List<DerivedBioAssayDataBean> origTables = achar.getDerivedBioAssayData();
int origNum = (origTables == null) ? 0 : origTables
.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
// create new ones
if (origNum == 0) {
for (int i = 0; i < tableNum; i++) {
DerivedBioAssayDataBean table = new DerivedBioAssayDataBean();
tables.add(table);
}
}
// use keep original table info
else if (tableNum <= origNum) {
for (int i = 0; i < tableNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
} else {
for (int i = 0; i < origNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
for (int i = origNum; i < tableNum; i++) {
tables.add(new DerivedBioAssayDataBean());
}
}
achar.setDerivedBioAssayData(tables);
}
public boolean loginRequired() {
return true;
}
/**
* Download action to handle download characterization file
* @param
* @return
*/
public ActionForward download (ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String fileId=request.getParameter("fileId");
/*
String filename = null;
SizeBean aChar=(SizeBean) theForm.get("achar");
for (CharacterizationTableBean obj : aChar.getCharacterizationTables()) {
if (obj.getId().toString().equals(fileId)) {
filename = obj.getFile().getName();
}
}
*/
CharacterizationFileBean fileBean = (CharacterizationFileBean) request.getSession().getAttribute("characterizationFile" + fileId);
String filename = fileBean.getPath() + fileBean.getName();
logger.info("*************filename=" + filename);
File dFile = new File(filename);
if (dFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + this.getName(filename));
response.setHeader("Cache-Control", "no-cache");
java.io.InputStream in = new FileInputStream (dFile);
java.io.OutputStream out = response.getOutputStream();
byte[] bytes = new byte[32768];
int numRead = 0;
while ((numRead = in.read(bytes)) > 0) {
out.write(bytes, 0, numRead);
}
out.close();
} else {
throw new Exception ("ERROR: file not found.");
}
return null;
}
/**
* Retrieve the file name from the full path
* @param fullPath
* @return
*/
private String getName(String fullPath) {
String rv = null;
String separator = fullPath.indexOf('/') < 0 ? "\\" : "/";
int idx = fullPath.lastIndexOf(separator);
if (idx >= 0)
rv = fullPath.substring(idx+1);
else
rv = fullPath;
return rv;
}
/**
* Retrieve the path from the full path
* @param fullPath
* @return
*/
private String getPath(String fullPath) {
String rv = null;
String separator = fullPath.indexOf('/') < 0 ? "\\" : "/";
int idx = fullPath.lastIndexOf(separator);
if (idx >= 0)
rv = fullPath.substring(0, idx+1);
else
rv = fullPath;
return rv;
}
}
|
/*
* $Log: DB2XMLWriter.java,v $
* Revision 1.15 2008-05-14 09:21:40 europe\L190409
* return null for LOBs when no LOB found
* improved logging
*
* Revision 1.14 2007/07/17 11:00:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* separate function to get single row
*
* Revision 1.13 2007/02/12 14:09:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Logger from LogUtil
*
* Revision 1.12 2006/12/13 16:31:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added blobCharset attribute
*
* Revision 1.11 2005/12/29 15:34:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added support for clobs
*
* Revision 1.10 2005/10/17 11:24:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added blobs and warnings
*
* Revision 1.9 2005/10/03 13:17:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added attribute trimSpaces, default=true
*
* Revision 1.8 2005/09/29 13:57:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made null an attribute of each field, where applicable
*
* Revision 1.7 2005/07/28 07:42:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* return a value for CLOBs too;
* catch numberFormatException for precision
*
* Revision 1.6 2005/06/13 11:52:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* cosmetic changes
*
*/
package nl.nn.adapterframework.util;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import nl.nn.adapterframework.core.SenderException;
import nl.nn.adapterframework.jdbc.JdbcException;
import org.apache.log4j.Logger;
/**
* Transforms a java.sql.Resultset to a XML stream.
* Example of a result:
* <code><pre>
* <result>
<fielddefinition>
<field name="fieldname"
type="columnType"
columnDisplaySize=""
precision=""
scale=""
isCurrency=""
columnTypeName=""
columnClassName=""/>
<field ...../>
</fielddefinition>
<rowset>
<row number="1">
<field name="fieldname">value</field>
<field name="fieldname" null="true" ></field>
<field name="fieldname">value</field>
<field name="fieldname">value</field>
</row>
</rowset>
</result>
</pre></code>
*
* @author Johan Verrips
* @version Id
**/
public class DB2XMLWriter {
public static final String version="$RCSfile: DB2XMLWriter.java,v $ $Revision: 1.15 $ $Date: 2008-05-14 09:21:40 $";
protected static Logger log = LogUtil.getLogger(DB2XMLWriter.class);
private String docname = new String("result");
private String recordname = new String("rowset");
private String nullValue = "";
private boolean trimSpaces=true;
private boolean decompressBlobs=false;
private String blobCharset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
public static String getFieldType (int type) {
switch (type) {
case Types.INTEGER : return ("INTEGER");
case Types.NUMERIC : return ("NUMERIC");
case Types.CHAR : return ("CHAR");
case Types.DATE : return ("DATE");
case Types.TIMESTAMP : return ("TIMESTAMP");
case Types.DOUBLE : return ("DOUBLE");
case Types.FLOAT : return ("FLOAT");
case Types.ARRAY : return ("ARRAY");
case Types.BLOB : return ("BLOB");
case Types.CLOB : return ("CLOB");
case Types.DISTINCT : return ("DISTINCT");
case Types.LONGVARBINARY : return ("LONGVARBINARY");
case Types.VARBINARY : return ("VARBINARY");
case Types.BINARY : return ("BINARY");
case Types.REF : return ("REF");
case Types.STRUCT : return ("STRUCT");
case Types.JAVA_OBJECT : return ("JAVA_OBJECT");
case Types.VARCHAR : return ("VARCHAR");
case Types.TINYINT: return ("TINYINT");
case Types.TIME: return ("TIME");
case Types.REAL: return ("REAL");
}
return ("Unknown");
}
/**
* This method gets the value of the specified column
*/
private static String getValue(final ResultSet rs, int colNum, int type, String blobCharset, boolean decompressBlobs, String nullValue, boolean trimSpaces) throws JdbcException, IOException, SQLException
{
switch(type)
{
// return "undefined" for types that cannot be rendered to strings easily
case Types.BLOB :
try {
return JdbcUtil.getBlobAsString(rs,colNum,blobCharset,false,decompressBlobs);
} catch (JdbcException e) {
log.debug("Caught JdbcException, assuming no blob found",e);
return nullValue;
}
case Types.CLOB :
try {
return JdbcUtil.getClobAsString(rs,colNum,false);
} catch (JdbcException e) {
log.debug("Caught JdbcException, assuming no clob found",e);
return nullValue;
}
case Types.ARRAY :
case Types.DISTINCT :
case Types.LONGVARBINARY :
case Types.VARBINARY :
case Types.BINARY :
case Types.REF :
case Types.STRUCT :
return "undefined";
default :
{
String value = rs.getString(colNum);
if(value == null)
return nullValue;
else
if (trimSpaces) {
value.trim();
}
return value;
}
}
}
/**
* Retrieve the Resultset as a well-formed XML string
*/
public synchronized String getXML(ResultSet rs) {
return getXML(rs, Integer.MAX_VALUE);
}
/**
* Retrieve the Resultset as a well-formed XML string
*/
public synchronized String getXML(ResultSet rs, int maxlength) {
if (null == rs)
return "";
if (maxlength < 0)
maxlength = Integer.MAX_VALUE;
XmlBuilder mainElement = new XmlBuilder(docname);
Statement stmt=null;
try {
stmt = rs.getStatement();
if (stmt!=null) {
JdbcUtil.warningsToXml(stmt.getWarnings(),mainElement);
}
} catch (SQLException e1) {
log.warn("exception obtaining statement warnings", e1);
}
int rowCounter=0;
try {
ResultSetMetaData rsmeta = rs.getMetaData();
int nfields = rsmeta.getColumnCount();
XmlBuilder fields = new XmlBuilder("fielddefinition");
for (int j = 1; j <= nfields; j++) {
XmlBuilder field = new XmlBuilder("field");
field.addAttribute("name", "" + rsmeta.getColumnName(j));
//Not every JDBC implementation implements these attributes!
try {
field.addAttribute("type", "" + getFieldType(rsmeta.getColumnType(j)));
} catch (SQLException e) {
log.debug("Could not determine columnType",e);
}
try {
field.addAttribute("columnDisplaySize", "" + rsmeta.getColumnDisplaySize(j));
} catch (SQLException e) {
log.debug("Could not determine columnDisplaySize",e);
}
try {
field.addAttribute("precision", "" + rsmeta.getPrecision(j));
} catch (SQLException e) {
log.warn("Could not determine precision",e);
} catch (NumberFormatException e2) {
log.debug("Could not determine precision",e2);
}
try {
field.addAttribute("scale", "" + rsmeta.getScale(j));
} catch (SQLException e) {
log.debug("Could not determine scale",e);
}
try {
field.addAttribute("isCurrency", "" + rsmeta.isCurrency(j));
} catch (SQLException e) {
log.debug("Could not determine isCurrency",e);
}
try {
field.addAttribute("columnTypeName", "" + rsmeta.getColumnTypeName(j));
} catch (SQLException e) {
log.debug("Could not determine columnTypeName",e);
}
try {
field.addAttribute("columnClassName", "" + rsmeta.getColumnClassName(j));
} catch (SQLException e) {
log.debug("Could not determine columnClassName",e);
}
fields.addSubElement(field);
}
mainElement.addSubElement(fields);
// Process result rows
XmlBuilder queryresult = new XmlBuilder(recordname);
while (rs.next() & rowCounter < maxlength) {
XmlBuilder row = getRowXml(rs,rowCounter,rsmeta,getBlobCharset(),decompressBlobs,nullValue,trimSpaces);
queryresult.addSubElement(row);
rowCounter++;
}
mainElement.addSubElement(queryresult);
} catch (Exception e) {
log.error("Error occured at row: " + rowCounter, e);
}
String answer = mainElement.toXML();
return answer;
}
public static XmlBuilder getRowXml(ResultSet rs, int rowNumber, ResultSetMetaData rsmeta, String blobCharset, boolean decompressBlobs, String nullValue, boolean trimSpaces) throws SenderException, SQLException {
XmlBuilder row = new XmlBuilder("row");
row.addAttribute("number", "" + rowNumber);
for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
XmlBuilder resultField = new XmlBuilder("field");
resultField.addAttribute("name", "" + rsmeta.getColumnName(i));
try {
String value = getValue(rs, i, rsmeta.getColumnType(i), blobCharset, decompressBlobs, nullValue, trimSpaces);
if (rs.wasNull()) {
resultField.addAttribute("null","true");
}
resultField.setValue(value);
} catch (Exception e) {
throw new SenderException("error getting fieldvalue column ["+i+"] fieldType ["+getFieldType(rsmeta.getColumnType(i))+ "]", e);
}
row.addSubElement(resultField);
}
JdbcUtil.warningsToXml(rs.getWarnings(),row);
return row;
}
public void setDocumentName(String s) {
docname = s;
}
public void setRecordName(String s) {
recordname = s;
}
/**
* Set the presentation of a <code>Null</code> value
**/
public void setNullValue(String s) {
nullValue=s;
}
/**
* Get the presentation of a <code>Null</code> value
**/
public String getNullValue () {
return nullValue;
}
public void setTrimSpaces(boolean b) {
trimSpaces = b;
}
public boolean isTrimSpaces() {
return trimSpaces;
}
public void setDecompressBlobs(boolean b) {
decompressBlobs = b;
}
public boolean isDecompressBlobs() {
return decompressBlobs;
}
public String getBlobCharset() {
return blobCharset;
}
public void setBlobCharset(String string) {
blobCharset = string;
}
}
|
package test.ccn.security.crypto;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.util.Random;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.security.KeyLocator;
import com.parc.ccn.data.security.PublisherPublicKeyDigest;
import com.parc.ccn.data.security.Signature;
import com.parc.ccn.data.security.SignedInfo;
import com.parc.ccn.data.util.DataUtils;
import com.parc.ccn.library.profiles.SegmentationProfile;
import com.parc.ccn.library.profiles.VersioningProfile;
import com.parc.ccn.security.crypto.CCNDigestHelper;
import com.parc.ccn.security.crypto.CCNMerkleTree;
public class CCNMerkleTreeTest {
protected static Random _rand = new Random(); // don't need SecureRandom
protected static KeyPair _pair = null;
static ContentName keyname = ContentName.fromNative(new String[]{"test","keys","treeKey"});
static ContentName baseName = ContentName.fromNative(new String[]{"test","data","treeTest"});
static KeyPair pair = null;
static PublisherPublicKeyDigest publisher = null;
static KeyLocator keyLoc = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
Security.addProvider(new BouncyCastleProvider());
// generate key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512); // go for fast
pair = kpg.generateKeyPair();
publisher = new PublisherPublicKeyDigest(pair.getPublic());
keyLoc = new KeyLocator(pair.getPublic());
} catch (Exception e) {
System.out.println("Exception in test setup: " + e.getMessage());
e.printStackTrace();
throw e;
}
}
@Test
public void testMerkleTree() throws Exception {
int [] sizes = new int[]{128,256,512,4096};
try {
testTree(0, sizes[0], false);
Assert.fail("CCNMerkleTree should throw an exception for tree sizes < 2.");
} catch (IllegalArgumentException e) {
}
try {
testTree(1, sizes[0], false);
Assert.fail("CCNMerkleTree should throw an exception for tree sizes < 2.");
} catch (IllegalArgumentException e) {
}
System.out.println("Testing small trees, fixed block widths.");
for (int i=2; i < 515; ++i) {
testTree(i,sizes[i%sizes.length],false);
}
System.out.println("Testing large trees, fixed block widths.");
int [] nodecounts = new int[]{1000,1001,1025,1098,1536,1575,2053,5147,8900,9998};
// int [] nodecounts = new int[]{1000,1001,1025,1098,1536,1575,2053,5147,8900,9998,9999,10000};
for (int i=0; i < nodecounts.length; ++i) {
testTreeWrapper(nodecounts[i],sizes[i%sizes.length],false);
}
}
@Test
public void testMerkleTreeBuf() {
int [] sizes = new int[]{128,256,512,4096};
System.out.println("Testing small trees, random block widths.");
for (int i=10; i < 515; ++i) {
testTreeWrapper(i,sizes[i%sizes.length], true);
}
}
public static void testTreeWrapper(int testNodeCount, int blockWidth, boolean randomWidths) {
try {
testTree(testNodeCount, blockWidth, randomWidths);
} catch (Exception e) {
System.out.println("Building tree of " + testNodeCount + " nodes, random widths? " + randomWidths + ". Caught a " + e.getClass().getName() + " exception: " + e.getMessage());
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() + " in testTreeWrapper.");
}
}
public static ContentObject [] makeContent(ContentName rootName, int numNodes, int maxLength, boolean randLengths) {
ContentObject [] cos = new ContentObject[numNodes];
byte [][] bufs = new byte[numNodes][];
SignedInfo si = new SignedInfo(publisher, keyLoc);
for (int i=0; i < numNodes; ++i) {
int blockLen = 0;
if (randLengths) {
while (blockLen == 0) {
blockLen = Math.abs(_rand.nextInt(maxLength));
}
} else {
blockLen = maxLength;
}
bufs[i] = new byte[blockLen];
_rand.nextBytes(bufs[i]);
cos[i] =
new ContentObject(
SegmentationProfile.segmentName(rootName, (i + SegmentationProfile.baseSegment())),
si, bufs[i], (Signature)null);
}
return cos;
}
public static void testTree(int nodeCount, int blockWidth, boolean randomWidths) throws Exception {
int version = _rand.nextInt(1000);
ContentName theName = ContentName.fromNative(baseName, "testDocBuffer.txt");
theName = VersioningProfile.versionName(theName, version);
try {
ContentObject [] cos = makeContent(theName, nodeCount, blockWidth, randomWidths);
// TODO DKS Need to do offset versions with different ranges of fragments
// Generate a merkle tree. Verify each path for the content.
CCNMerkleTree tree = new CCNMerkleTree(cos,
pair.getPrivate());
tree.setSignatures();
System.out.println("Constructed tree of numleaves: " +
tree.numLeaves() + " max pathlength: " + tree.maxDepth());
ContentObject block;
for (int i=0; i < tree.numLeaves()-1; ++i) {
block = cos[i];
boolean result = block.verify(pair.getPublic());
if (!result) {
System.out.println("Block name: " + tree.blockName(i) + " num " + i + " verified? " + result + ", content: " + DataUtils.printBytes(block.contentDigest()));
byte [] digest = CCNDigestHelper.digest(block.encode());
byte [] tbsdigest =
CCNDigestHelper.digest(ContentObject.prepareContent(block.name(), block.signedInfo(), block.content()));
System.out.println("Raw content digest: " + DataUtils.printBytes(CCNDigestHelper.digest(block.content())) +
" object content digest: " + DataUtils.printBytes(CCNDigestHelper.digest(block.content())));
System.out.println("Block: " + block.name() + " timestamp: " + block.signedInfo().getTimestamp() + " encoded digest: " + DataUtils.printBytes(digest) + " tbs content: " + DataUtils.printBytes(tbsdigest));
} else if (i % 100 == 0) {
System.out.println("Block name: " + tree.blockName(i) + " num " + i + " verified? " + result + ", content: " + DataUtils.printBytes(block.contentDigest()));
}
Assert.assertTrue("Path " + i + " failed to verify.", result);
}
tree = null;
} catch (Exception e) {
System.out.println("Exception in testTree: " + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
throw(e); // must re-throw rather than assert fail; one test actually expects an exception
}
}
}
|
package io.mangoo.cache;
import java.net.URI;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import org.ehcache.CacheManager;
import org.ehcache.PersistentCacheManager;
import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.core.spi.service.StatisticsService;
import org.ehcache.core.statistics.CacheStatistics;
import org.ehcache.core.statistics.DefaultStatisticsService;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.mangoo.core.Config;
import io.mangoo.enums.CacheName;
import io.mangoo.enums.Required;
/**
*
* @author svenkubiak
*
*/
@Singleton
public class CacheProvider implements Provider<Cache> {
private StatisticsService statisticsService = new DefaultStatisticsService();
private Map<String, Cache> caches = new HashMap<>();
private CacheManager cacheManager;
private Cache cache;
private static final long SIXTY = 60;
private static final long THIRTY = 30;
private static final long FORTY_THOUSAND_ELEMENTS = 40000;
private static final long TWENTY_THOUSAND_ELEMENTS = 20000;
@Inject
@SuppressFBWarnings(value = "FII_USE_FUNCTION_IDENTITY", justification = "Required by cache creation function")
public CacheProvider(Config config) {
Objects.requireNonNull(config, Required.CONFIG.toString());
if (config.isCacheCluserEnable()) {
CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder()
.using(statisticsService)
.with(ClusteringServiceConfigurationBuilder.cluster(URI.create(config.getCacheClusterUrl()))
.autoCreate(b -> b));
this.cacheManager = clusteredCacheManagerBuilder.build(true);
} else {
this.cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.using(statisticsService)
.build();
this.cacheManager.init();
}
initApplicationCache();
initAuthenticationCache();
initRequestCache();
initResponseCache();
initServerEventCache();
initWebSocketCache();
setDefaultApplicationCache();
}
private final void initApplicationCache() {
CacheConfiguration<String, Object> configuration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, Object.class, ResourcePoolsBuilder.heap(TWENTY_THOUSAND_ELEMENTS))
.build();
registerCacheConfiguration(CacheName.APPLICATION.toString(), configuration);
}
private final void initAuthenticationCache() {
CacheConfiguration<String, Object> configuration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, Object.class, ResourcePoolsBuilder.heap(TWENTY_THOUSAND_ELEMENTS))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.of(SIXTY, ChronoUnit.MINUTES)))
.build();
registerCacheConfiguration(CacheName.AUTH.toString(), configuration);
}
private final void initRequestCache() {
CacheConfiguration<String, Object> configuration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, Object.class, ResourcePoolsBuilder.heap(FORTY_THOUSAND_ELEMENTS))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.of(SIXTY, ChronoUnit.SECONDS)))
.build();
registerCacheConfiguration(CacheName.REQUEST.toString(), configuration);
}
private final void initResponseCache() {
CacheConfiguration<String, Object> configuration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, Object.class, ResourcePoolsBuilder.heap(TWENTY_THOUSAND_ELEMENTS))
.build();
registerCacheConfiguration(CacheName.RESPONSE.toString(), configuration);
}
private final void initServerEventCache() {
CacheConfiguration<String, Object> configuration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, Object.class, ResourcePoolsBuilder.heap(TWENTY_THOUSAND_ELEMENTS))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.of(THIRTY, ChronoUnit.MINUTES)))
.build();
registerCacheConfiguration(CacheName.SSE.toString(), configuration);
}
private final void initWebSocketCache() {
CacheConfiguration<String, Object> configuration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, Object.class, ResourcePoolsBuilder.heap(TWENTY_THOUSAND_ELEMENTS))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.of(THIRTY, ChronoUnit.MINUTES)))
.build();
registerCacheConfiguration(CacheName.WSS.toString(), configuration);
}
private final void setDefaultApplicationCache() {
this.cache = getCache(CacheName.APPLICATION);
}
/**
* Registers a new cache with custom configuration
*
* @param name The name of the cache
* @param configuration The configuration for the cache to use
* @return The cache instance
*/
public void registerCacheConfiguration(String name, CacheConfiguration<String, Object> configuration) {
this.caches.put(name, new CacheImpl(cacheManager.createCache(name, configuration)));
}
/**
* Returns a map containing cache names and cache statistics
*
* @return Map of cache statistics
*/
public Map<String, CacheStatistics> getCacheStatistics() {
Map<String, CacheStatistics> statistics = new HashMap<>();
for (Entry<String, Cache> entry : caches.entrySet()) {
String cacheName = entry.getKey();
statistics.put(cacheName, statisticsService.getCacheStatistics(cacheName));
}
return statistics;
}
/**
* Retrieves a cache by its name from the cache pool
*
* @param name The name of the cache
* @return An Cache instance
*/
public Cache getCache(CacheName name) {
return getCache(name.toString());
}
/**
* Retrieves a cache by its name from the cache pool
*
* @param name The name of the cache
* @return An Cache instance
*/
public Cache getCache(String name) {
return this.caches.get(name);
}
/**
* Closes all caches
*/
public void close() {
cacheManager.close();
}
@Override
public Cache get() {
return this.cache;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.